9.4.3.4.4. Space and Space membership

You can download all source code used in this section here.

Searching for space

To search for spaces that match an input string, use a GET request to call the /rest/v1/social/spaces API and pass this string to the call via a q parameter.

  1. Create a file named SocialSpaceAPIs.xml under the /gadgets/SocialAPIsGadgets/ folder, then add the following script to this file:

    
    <?xml version="1.0" encoding="UTF-8" ?>
    <Module>
        <ModulePrefs title="Social Space Gadget">
        </ModulePrefs>
        <Content type="html">
            <![CDATA[
                <!--Including platform css-->
                <link href="/eXoSkin/skin/css/Core.css" rel="stylesheet"></link>
                <link href="/eXoSkin/skin/css/sub-core.css" rel="stylesheet"></link>
                <!--Including JQuery library-->
                <script src="jquery-2.1.3.js"></script>
                
                <!--Gadget's main body which will be added by HTML DOM Object later-->
                <div id="main-body" style="max-width: 850px" class="uiComposer uiGrayLightBox">
                        <div class="input-append" style="margin: 20px 30px 20px 30px">
                            //control button for searching for spaces
                            <button id="search_space_btn" onclick="searchSpace()" class="btn btn-primary">Search for space</button>
                            <input type="text" id="search_space_txt" placeholder="Enter space information...">
                        </div>
                </div>
                <!--Start calling js function-->
                <script type="text/javascript">
                    function searchSpace(){
                        //send http request
                        $.ajax({
                             type: "GET",
                             url: "/rest/v1/social/spaces?q="+$("#search_space_txt").val(),
                             success: function (data, status, jqXHR) {
                                //print the result
                                printSpacesList(data.spaces);
                                addSpaceBtn();
                             },
                             error: function (jqXHR, status) {
                                 alert("Cannot retrieve data!");
                             }
                        });
                    }
                    function printSpacesList(spaces){
                        //clear screen
                        $('#main-content').remove();
                        $('#sub-content').remove();
                        if(spaces.length==0){
                            $('#main-body').append("<div id=\"main-content\">No space was found!</div>");
                        }
                        else {
                            //print a list of spaces in a table
                            //initialize html content
                            var obj_content="<div id=\"main-content\"><table class=\"uiGrid table table-hover table-striped\"><thead><tr><th>&nbsp;</th><th>Name</th><th>Description</th><th>Id</th><th>Edit</th><th>Delete</th></tr></thead><tbody>";
                                //loop through the list
                                $.each(spaces, function(key, value) {
                                    obj_content+="<tr><td>"+key+"</td><td>"+value.displayName+"</td><td>"+value.description+"</td><td>"+value.id+"</td><td><a class=\"actionHover\" href=\"#\"><i class=\"uiIconEditMini uiIconLightGray\" onclick=\"editSpace('"+value.id+"')\"> </i></a></td><td><a class=\"actionHover\" href=\"#\"><i class=\"uiIconTrashMini uiIconLightGray\" onclick=\"deleteSpace('"+value.id+"')\"></i></a></td></tr>";
                                });
                            //add closing tag
                            obj_content+="</tbody></table></div>";
                            //add to screen
                            $('#main-body').append(obj_content);
                        }
                    }
                </script>]]>
        </Content>
    </Module>

    The searchSpace() function returns a JSON object containing an array of spaces that match the input string. The object will then be printed out in the printSpacesList() function.

  2. Deploy this gadget and create some spaces to check this function. For example, search for "documentation".

Editing a space

To edit a space, we use the /rest/v1/social/spaces/{id} API. In this section, you are going to modify the space description information.

  1. Implement the editSpace() function as below:

    function editSpace(space_id){
    	var content = prompt("Please enter your space description", "Space description");
    	
    	if (content != null) {
    		//update content of comment
    		var space_json_obj={
    			"description":content
    		}
    		//send http request
    		$.ajax({
    			url: "/rest/v1/social/spaces/"+space_id,
    			contentType: "application/json",
    			data: JSON.stringify(space_json_obj),
    			method: "PUT"
    			}).done(function (data, status, xhr) {
    				alert("Updated successfully!");
    				searchSpace();
    			}).fail(function (jqxhr, textStatus, error) {
    				alert("Fail!");
    		});
    	}
    }

    This function generates a form to enter the space description information, then packages this content in a JSON object. This object will be passed to a PUT request to call the /rest/v1/social/spaces/{id} API.

  2. Deploy this gadget, then click the edit icon and try changing some space descriptions.

Deleting a space

To delete a space, use the /rest/v1/social/spaces/{id} API with a DELETE request.

  1. Implement the deleteSpace() function as below:

    function deleteSpace(space_id){
    	//send http request
    	$.ajax({
    		url: "/rest/v1/social/spaces/"+space_id,
    		method: "DELETE"
    		}).done(function () {
    			alert("Deleted successfully!");
    		//reload space list
    		   searchSpace();
    		}).fail(function (jqxhr, textStatus, error) {
    			alert("fail");
    	});
    }
  2. Deploy this gadget, then click the delete icon. The corresponding space will be deleted.

Creating a space

In this section, you are going to create a new space using the /rest/v1/social/spaces API.

  1. Add the following functions to the JavaScript part of the gadget:

    function addSpaceBtn(){
    	var obj_content="<button id=\"add_space_btn\" onclick=\"addNewSpace()\" class=\"btn btn-primary\" style=\"margin: 20px 30px 20px 30px\">Add a new space</button>";
    	//add to screen
    	$('#main-content').append(obj_content);
    }
    function addNewSpace(){
    	//clean screen
    	$('#sub-content').remove();
    	//initialize html content
    	var obj_content="<div id=\"sub-content\"><table class=\"uiGrid table table-hover table-striped\"><tr><td>Space name: </td><td><input type=\"text\" id=\"spacename\"></td></tr><tr><td>Description: </td><td><input type=\"text\" id=\"space_description\"></td></tr><tr><td></td><td><button id=\"add_new_space_proc_btn\" onclick=\"addNewSpaceProc()\">Submit</button></td></tr></table></div>";
    	//add to screen
    	$('#main-body').append(obj_content);
    }
    function addNewSpaceProc(){
    	//check entered data
    	if($("#spacename").val().trim()=="") {
    		alert("Missing information");
    		return;
    	}
    	//initialize space information as a json object
    	var space_json_obj={
    		"displayName":$("#spacename").val(),
    		"description":$("#space_description").val()
    		};
    	//send http request
    	$.ajax({
    		url: "/rest/v1/social/spaces",
    		contentType: "application/json",
    		data: JSON.stringify(space_json_obj),
    		method: "POST"
    		}).done(function (data, status, xhr) {
    		   //clean screen
    		   $('#sub-content').remove();
    		   //print the newly created space id
    		   $('#main-content').append("Created successfully! Space id: "+data.id);
    		}).fail(function (jqxhr, textStatus, error) {
    			alert("fail");
    	});
    }

    The Add a new space function generates a form to enter the space information. The content will then be packaged in a JSON object and passed to a POST request to call the /rest/v1/social/spaces API.

  2. Deploy this gadget and test the Add a new space function.

Getting a space by Id

eXo Platform provides the /rest/v1/social/spaces/{id} API to retrieve information of a specified space.

  1. Add a control button and a text box next to the Search for space button by this script:

    //control button for getting a space by id
    <button id="get_space_by_id_btn" onclick="getSpaceById()" class="btn btn-primary">Get a space by id</button>
    <input type="text" id="space_id_txt" placeholder="Enter space id...">
  2. Declare a global variable named current_space and implement the getSpaceById() function as follows:

    function getSpaceById(){
    	//send http request
    	$.ajax({
    		 type: "GET",
    		 url: "/rest/v1/social/spaces/"+$("#space_id_txt").val(),
    		 success: function (data, status, jqXHR) {
    			//update current space
    			current_space=data;
    			//print the result
    			var array=new Array(data);
    			printSpacesList(array);
    			getUsersList($("#space_id_txt").val());
    		 },
    		 error: function (jqXHR, status) {
    			 alert("Cannot retrieve data!");
    		 }
    	});
    }

    The getUsersList() function will be implemented in the next section.

  3. Deploy this gadget, then copy any space Id in the Id column of the spaces table (after searching for space) to test this function.

Getting users and user membership roles of a space

In this section, you are going to deal with two APIs, including:

  1. Declare a global array variable named roles to store the membership roles of all users in a space.

  2. Add the following functions to the JavaScript part of the gadget:

    function getUsersList(space_id){
    	//send http request
    	$.ajax({
    		 type: "GET",
    		 url: "/rest/v1/social/spaces/"+space_id+"/users",
    		 success: function (data, status, jqXHR) {
    			//print the result
    			getMembershipRole(data.users);
    			setTimeout(function(){
    				printUsersList(data.users);
    			}, 2000);
    		 },
    		 error: function(jqXHR, status) {
    			 alert("Cannot retrieve data!");
    		 }
    	});
    }
    function printUsersList(users){
    	//print a list of users in a table
    	//initialize html content
    	var obj_content="<div id=\"sub-content\"><h4>Users list</h4><table class=\"uiGrid table table-hover table-striped\"><thead><tr><th>&nbsp;</th><th>User name</th><th>First name</th><th>Last name</th><th>Email</th><th>Edit</th><th>Delete</th></tr></thead><tbody>";
    		//loop through the list
    		$.each(users, function(key, value) {
    			obj_content+="<tr><td>"+key+"</td><td>"+value.username+"</td><td>"+value.firstname+"</td><td>"+value.lastname+"</td><td>"+value.email+"</td><td><a class=\"actionHover\" href=\"#\"><i class=\"uiIconEditMini uiIconLightGray\" onclick=\"editMembership('"+value.username+"','"+roles[key]+"' )\"> </i></a></td><td><a class=\"actionHover\" href=\"#\"><i class=\"uiIconTrashMini uiIconLightGray\" onclick=\"deleteMembership('"+value.username+"','"+roles[key]+"')\"></i></a></td></tr>";
    		});
    	//add closing tag
    	obj_content+="</tbody></table></div>";
    	//add to screen
    	$('#main-content').append(obj_content);
    }
    function getMembershipRole(users_data){
    	$.each(users_data, function(key, value) {
    			$.ajax({
    				 type: "GET",
    				 url: "/rest/v1/social/spacesMemberships?space="+current_space.displayName+"&user="+value.username,
    				 success: function(data, status, jqXHR){
    							 if(data.spacesMemberships.length<=1)
    								roles[key]=data.spacesMemberships[0].role;
    							 else
    								roles[key]=data.spacesMemberships[1].role;
    						 },
    				 error: function (jqXHR, status) {
    					 alert("Cannot retrieve data!");
    				 }
    			});
    		});
    }

    The /rest/v1/social/spacesMemberships API requires two input parameters which are space - the display name of space and user - the username. It returns the membership roles of the user in the space.

  3. Deploy this gadget and add some users to a space to test. You will see the list of users and their memberships as below:

Editing a user membership in a space

To edit a user membership, send a PUT request to call the /rest/v1/social/spacesMemberships/{id} API.

  1. Implement the editMembership() function as follows:

    function editMembership(user_name, role){
    	var content = prompt("Please enter a membership", "manager");
    	
    	if (content != null) {
    		//generate membership id
    		var membership_id=getSpaceName(current_space.groupId)+":"+user_name+":"+role;
    		var new_role_json_obj={
    			"role": content
    		};
    		//send http request
    		$.ajax({
    			url: "/rest/v1/social/spacesMemberships/"+membership_id,
    			contentType: "application/json",
    			data: JSON.stringify(new_role_json_obj),
    			method: "PUT"
    			}).done(function (data, status, xhr) {
    				alert("Updated successfully!");
    			}).fail(function (jqxhr, textStatus, error) {
    				alert("Fail!");
    		});
    	}
    }

    This function requires the membership Id in format spaceName:userName:type, so you need a getSpaceName() function to get the space name from the current_space variable.

  2. Implement the getSpaceName() function as below:

    function getSpaceName(original_name, new_name){
    	//get space name, because the displayName was run through standardizing to generate the spaceName
    	var space_name_temp=original_name.split("/");
    	return space_name_temp[space_name_temp.length-1];
    }
  3. Deploy this gadget and test the function by clicking the edit icon, then change the current membership of any user.

Deleting a user membership in a space

To delete a user membership in a space, send a DELETE request to call the /rest/v1/social/spacesMemberships/{id} API.

  1. Implement the deleteMembership() function as follows:

    function deleteMembership(user_name, role){
    	//generate membership id
    	var membership_id=getSpaceName(current_space.groupId)+":"+user_name+":"+role;
    	//send http request
    	$.ajax({
    		url: "/rest/v1/social/spacesMemberships/"+membership_id,
    		contentType: "application/json",
    		method: "DELETE"
    		}).done(function (data, status, xhr) {
    			alert("Deleted successfully!");
    		}).fail(function (jqxhr, textStatus, error) {
    			alert("Fail!");
    	});
    }
  2. Deploy this gadget and test the function by clicking the delete icon. The corresponding membership will be deleted.

    Note

    To remove users who are managers from a space, you need to delete both their member and manager memberships.

Copyright ©. All rights reserved. eXo Platform SAS
blog comments powered byDisqus