Esempio n. 1
0
        public object Put(CommunityUpdateRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                if (string.IsNullOrEmpty(request.Identifier))
                {
                    throw new Exception("Invalid request - missing community identifier");
                }

                context.LogInfo(this, string.Format("/community PUT Identifier='{0}'", request.Identifier));

                ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Identifier);

                if (!domain.CanUserManage(context.UserId))
                {
                    throw new UnauthorizedAccessException("Action only allowed to manager of the domain");
                }

                domain = request.ToEntity(context, domain);
                domain.Store();

                domain.UpdateAppsLinks(request.Apps);
                domain.UpdateDomainsLinks(domain.Links);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new WebResponseBool(true));
        }
Esempio n. 2
0
        public object Post(ThematicAppAddToCommunityRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            context.LogInfo(this, string.Format("/community/{{domain}}/apps POST domain='{0}', appurl='{1}'", request.Domain, request.AppUrl));
            if (string.IsNullOrEmpty(request.AppUrl))
            {
                throw new Exception("Invalid Application Url");
            }

            var domain = ThematicCommunity.FromIdentifier(context, request.Domain);

            if (!domain.CanUserManage(context.UserId))
            {
                throw new UnauthorizedAccessException("Action only allowed to manager of the domain");
            }

            var app = domain.GetThematicApplication();
            var res = new RemoteResource(context);

            res.Location = request.AppUrl;
            app.AddResourceItem(res);

            context.Close();
            return(new WebResponseBool(true));
        }
Esempio n. 3
0
        public object Delete(CommunityRemoveSyncInfoRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            try
            {
                context.Open();
                context.AccessLevel = EntityAccessLevel.Privilege;
                context.LogInfo(this, string.Format("/community/{{Identifier}}/sync/info DELETE Identifier='{0}' , SyncIdentifier='{1}'", request.Identifier, request.SyncIdentifier));
                var domain = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (!domain.CanUserManage(context.UserId))
                {
                    throw new UnauthorizedAccessException(CustomErrorMessages.ADMINISTRATOR_ONLY_ACTION);
                }
                if (domain.UserSyncIdentifier != null)
                {
                    domain.UserSyncIdentifier = domain.UserSyncIdentifier.Replace(request.SyncIdentifier, "").Replace(",,", ",").Trim(',');
                }
                domain.Store();

                //remove all users already in the community
                domain.SyncExistingUsersRemove(request.SyncIdentifier);

                context.Close();
            }
            catch (Exception e)
            {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Esempio n. 4
0
        /// <summary>
        /// Delete the specified request.
        /// </summary>
        /// <returns>The delete.</returns>
        /// <param name="request">Request.</param>
        public object Delete(CommunityRemoveCollectionRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.AccessLevel = EntityAccessLevel.Privilege;
                context.LogInfo(this, string.Format("/community/{{Identifier}}/collection/{{CollIdentifier}} DELETE Identifier='{0}' , CollIdentifier='{1}'", request.Identifier, request.CollIdentifier));
                var domain = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (!domain.CanUserManageCollection(context.UserId))
                {
                    throw new UnauthorizedAccessException(CustomErrorMessages.ADMINISTRATOR_ONLY_ACTION);
                }
                var collection = Collection.FromIdentifier(context, request.CollIdentifier);
                var owner      = User.FromId(context, collection.UserId);
                collection.Domain = owner.Domain;
                collection.Store();
                context.LogDebug(this, string.Format("Collection removed from Community {0}, put in owner's domain {1}", domain.Identifier, User.FromId(context, context.UserId).Username));
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Esempio n. 5
0
        /// <summary>
        /// Delete the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Delete(CommunityDeleteRequest request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/community/{{Identifier}} DELETE Identifier='{0}'", request.Identifier));
                ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (domain.CanUserManage(context.UserId))
                {
                    domain.Delete();
                }
                else
                {
                    throw new UnauthorizedAccessException(CustomErrorMessages.ADMINISTRATOR_ONLY_ACTION);
                }
                context.LogDebug(this, string.Format("Community {0} deleted by user {1}", domain.Identifier, User.FromId(context, context.UserId).Username));
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Esempio n. 6
0
        public object Delete(CommunityRemoveUserRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                if (string.IsNullOrEmpty(request.Identifier))
                {
                    throw new Exception("Invalid request - missing community identifier");
                }

                User user = string.IsNullOrEmpty(request.Username) ? User.FromId(context, context.UserId) : User.FromUsername(context, request.Username);
                context.LogInfo(this, string.Format("/community/user DELETE Identifier='{0}', Username='******', Reason='{2}'", request.Identifier, request.Username, request.Reason));

                ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Identifier);

                domain.RemoveUser(user, request.Reason);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new WebResponseBool(true));
        }
Esempio n. 7
0
        /// <summary>
        /// Post the specified request.
        /// </summary>
        /// <returns>The post.</returns>
        /// <param name="request">Request.</param>
        public object Post(CommunityAddWpsServiceRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.AccessLevel = EntityAccessLevel.Privilege;
                context.LogInfo(this, string.Format("/community/{{Identifier}}/service/wps/{{WpsIdentifier}} POST Identifier='{0}' , WpsIdentifier='{1}'", request.Identifier, request.WpsIdentifier));
                var domain = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (!domain.CanUserManageService(context.UserId))
                {
                    throw new UnauthorizedAccessException(CustomErrorMessages.ADMINISTRATOR_ONLY_ACTION);
                }
                var wps = WpsProcessOffering.FromIdentifier(context, request.WpsIdentifier);
                wps.AccessLevel = EntityAccessLevel.Privilege;
                wps.Domain      = domain;
                wps.Store();
                context.LogDebug(this, string.Format("Wps service added to Community {0}", domain.Identifier));
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Esempio n. 8
0
        public object Get(AnalyticsRequestTep request)
        {
            var          context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            WebAnalytics result  = new WebAnalytics();

            try {
                context.Open();
                context.LogInfo(this, string.Format("/analytics GET - type='{0}', identifier='{1}'", request.Type, request.Identifier));

                Analytics analytics = null;

                if (context.UserId == 0)
                {
                    request.Type = "all";
                }

                switch (request.Type)
                {
                case "user":
                    analytics = new Analytics(context, UserTep.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "community":
                    analytics = new Analytics(context, ThematicCommunity.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "group":
                    analytics = new Analytics(context, Group.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "service":
                    analytics = new Analytics(context, Service.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "all":
                    analytics = new Analytics(context);
                    analytics.Load(request.startdate, request.enddate);
                    break;

                default:
                    break;
                }
                if (analytics != null)
                {
                    result = new WebAnalytics(analytics);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Esempio n. 9
0
        public object Post(PostDiscourseTopic request)
        {
            var    context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            string result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/discourse/posts POST community='{0}'{1}{2}",
                                                    request.communityIdentifier,
                                                    !string.IsNullOrEmpty(request.subject) ? ", subject='" + request.subject + "'" : "",
                                                    !string.IsNullOrEmpty(request.body) ? ", body='" + request.body + "'" : ""
                                                    ));

                if (string.IsNullOrEmpty(request.subject))
                {
                    throw new Exception("Unable to post new topic, subject is null");
                }
                if (string.IsNullOrEmpty(request.body))
                {
                    throw new Exception("Unable to post new topic, body is null");
                }

                var community       = ThematicCommunity.FromIdentifier(context, request.communityIdentifier);
                var discussCategory = community.DiscussCategory;
                if (string.IsNullOrEmpty(discussCategory))
                {
                    throw new Exception("Unable to post new topic, the selected community has no Discuss category associated");
                }

                var user = UserTep.FromId(context, context.UserId);
                if (string.IsNullOrEmpty(user.TerradueCloudUsername))
                {
                    throw new Exception("Unable to post new topic, please set first your Terradue Cloud username");
                }

                var discussClient = new DiscussClient(context.GetConfigValue("discussBaseUrl"), context.GetConfigValue("discussApiKey"), user.TerradueCloudUsername);
                var category      = discussClient.GetCategory(discussCategory);
                if (category == null)
                {
                    throw new Exception("Unable to post new topic, the selected community has no valid Discuss category associated");
                }
                var catId = category.id;

                var response = discussClient.PostTopic(catId, request.subject, request.body);
                result = string.Format("{0}/t/{1}/{2}", discussClient.Host, response.topic_slug, response.topic_id);
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebService.Model.WebResponseString(result));
        }
Esempio n. 10
0
        public object Get(ThematicAppCacheRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            try {
                context.LogInfo(this, string.Format("/apps/cache GET"));
                var appFactory = new ThematicAppCachedFactory(context);
                if (!string.IsNullOrEmpty(request.Uid))
                {
                    //refresh only a given app
                    appFactory.RefreshCachedApp(request.Uid);
                }
                else if (!string.IsNullOrEmpty(request.Username))
                {
                    //refresh only for private apps
                    var user = UserTep.FromIdentifier(context, request.Username);
                    if (user.Id == context.UserId)
                    {
                        appFactory.RefreshCachedAppsForUser(user);
                    }
                }
                else if (!string.IsNullOrEmpty(request.Community))
                {
                    //refresh only for community apps
                    var community = ThematicCommunity.FromIdentifier(context, request.Community);
                    if (community.CanUserManage(context.UserId))
                    {
                        appFactory.RefreshCachedAppsForCommunity(community);
                    }
                }
                else
                {
                    //user should be admin
                    if (context.UserLevel == UserLevel.Administrator)
                    {
                        //case TEP -- we don't want user privates apps to be cached
                        appFactory.RefreshCachedApps(false, true, true);
                    }
                }
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Esempio n. 11
0
        public void JoinPublicCommunity()
        {
            context.AccessLevel = EntityAccessLevel.Privilege;
            var usr1 = User.FromUsername(context, "testusr1");
            var usr2 = User.FromUsername(context, "testusr2");

            context.StartImpersonation(usr1.Id);

            try {
                ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-public-1");
                var roles = Role.GetUserRolesForDomain(context, usr1.Id, community.Id);

                //user not part of community
                Assert.AreEqual(0, roles.Length);

                community.TryJoinCurrentUser();
                roles = Role.GetUserRolesForDomain(context, usr1.Id, community.Id);

                //user part of community
                Assert.AreEqual(1, roles.Length);
                Assert.AreEqual(RoleTep.MEMBER, roles [0].Name);

                //check user cannot joins twice
                community.TryJoinCurrentUser();
                roles = Role.GetUserRolesForDomain(context, usr1.Id, community.Id);
                Assert.AreEqual(1, roles.Length);

                context.EndImpersonation();
                context.StartImpersonation(usr2.Id);

                var role = Role.FromIdentifier(context, RoleTep.STARTER);

                community.SetUserRole(usr1, role);
                roles = Role.GetUserRolesForDomain(context, usr1.Id, community.Id);

                //user part of community
                Assert.AreEqual(1, roles.Length);
                Assert.AreEqual(RoleTep.STARTER, roles [0].Name);

                community.RemoveUser(usr1);
            } catch (Exception e) {
                Assert.Fail(e.Message);
            } finally {
                context.EndImpersonation();
            }
        }
Esempio n. 12
0
        public void GetCommunityOwner()
        {
            ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-public-1");
            var usr = community.Owners[0];

            Assert.AreEqual("testusr2", usr.Username);

            community = ThematicCommunity.FromIdentifier(context, "community-public-2");
            usr       = community.Owners[0];
            Assert.AreEqual("testusr2", usr.Username);

            community = ThematicCommunity.FromIdentifier(context, "community-private-1");
            usr       = community.Owners[0];
            Assert.AreEqual("testusr2", usr.Username);

            community = ThematicCommunity.FromIdentifier(context, "community-private-2");
            usr       = community.Owners[0];
            Assert.AreEqual("testusr2", usr.Username);
        }
Esempio n. 13
0
        /// <summary>
        /// Post the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Post(CommunityAddUserRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                if (string.IsNullOrEmpty(request.Identifier))
                {
                    throw new Exception("Invalid request - missing community identifier");
                }

                User user = string.IsNullOrEmpty(request.Username) ? User.FromId(context, context.UserId) : User.FromUsername(context, request.Username);

                //we use administrator access level to be able to load the community
                context.AccessLevel = EntityAccessLevel.Administrator;
                ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Identifier);

                Role role = Role.FromIdentifier(context, string.IsNullOrEmpty(request.Role) ? domain.DefaultRoleName : request.Role);
                context.LogInfo(this, string.Format("/community/user POST Identifier='{0}', Username='******', Role='{2}'", request.Identifier, user.Username, role.Identifier));

                if (string.IsNullOrEmpty(request.Username))
                {
                    //case user auto Join
                    domain.TryJoinCurrentUser(request.Objectives);
                }
                else
                {
                    //case owner add user with role
                    domain.SetUserRole(user, role);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new WebResponseBool(true));
        }
Esempio n. 14
0
        public void SearchCommunitiesForWpsJob()
        {
            context.AccessLevel = EntityAccessLevel.Administrator;
            ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-public-1");
            var wpsjob = WpsJob.FromIdentifier(context, "private-job-usr1");

            context.AccessLevel = EntityAccessLevel.Privilege;

            var usr1 = User.FromUsername(context, "testusr1");

            context.StartImpersonation(usr1.Id);

            try {
                community.TryJoinCurrentUser();

                //share as owner and member of community
                community.ShareEntity(wpsjob);

                var communities = new EntityList <ThematicCommunity>(context);
                var parameters  = new NameValueCollection();
                parameters.Set("correlatedTo", string.Format("{0}/job/wps/search?uid={1}", context.BaseUrl, "private-job-usr1"));
                IOpenSearchResultCollection osr = ose.Query(communities, parameters);
                Assert.AreEqual(1, osr.TotalResults);

                //unshare the job
                wpsjob.RevokePermissionsFromAll(true, false);
                wpsjob.DomainId = wpsjob.Owner.DomainId;
                wpsjob.Store();

                Assert.False(wpsjob.IsSharedToCommunity());
            } catch (Exception e) {
                Assert.Fail(e.Message);
            } finally {
                context.EndImpersonation();
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Put the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Put(CommunityUpdateUserRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                if (string.IsNullOrEmpty(request.Identifier))
                {
                    throw new Exception("Invalid request - missing community identifier");
                }
                if (string.IsNullOrEmpty(request.Username))
                {
                    throw new Exception("Invalid request - missing username");
                }
                if (string.IsNullOrEmpty(request.Role))
                {
                    throw new Exception("Invalid request - missing role");
                }

                User user = User.FromUsername(context, request.Username);
                Role role = Role.FromIdentifier(context, request.Role);
                context.LogInfo(this, string.Format("/community/user PUT Identifier='{0}', Username='******', Role='{2}'", request.Identifier, user.Username, role.Identifier));

                ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Identifier);

                domain.SetUserRole(user, role);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new WebResponseBool(true));
        }
Esempio n. 16
0
        public object Get(ActivityByCommunitySearchRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.AccessLevel = EntityAccessLevel.Administrator;
            context.Open();
            context.LogInfo(this, string.Format("/community/{{community}}/activity/search GET - community='{0}'", request.Domain));

            ThematicCommunity domain = ThematicCommunity.FromIdentifier(context, request.Domain);

            //We only want some Privileges
            var privlist = new List <int> ();

            var privs = Privilege.Get(EntityType.GetEntityType(typeof(WpsJob)));

            foreach (var priv in privs)
            {
                privlist.Add(priv.Id);
            }

            privs = Privilege.Get(EntityType.GetEntityType(typeof(DataPackage)));
            foreach (var priv in privs)
            {
                privlist.Add(priv.Id);
            }

            privs = Privilege.Get(EntityType.GetEntityType(typeof(Series)));
            foreach (var priv in privs)
            {
                privlist.Add(priv.Id);
            }

            EntityList <ActivityTep> activities = new EntityList <ActivityTep> (context);

            activities.AddSort("CreationTime", SortDirection.Descending);
            activities.SetFilter("PrivilegeId", string.Join(",", privlist));
            activities.SetFilter("DomainId", domain.Id.ToString());
            activities.Identifier = "activity";
            activities.Load();

            // Load the complete request
            HttpRequest      httpRequest = HttpContext.Current.Request;
            OpenSearchEngine ose         = MasterCatalogue.OpenSearchEngine;

            // the opensearch cache system uses the query parameters
            // we add to the parameters the filters added to the load in order to avoir wrong cache
            // we use 't2-' in order to not interfer with possibly used query parameters
            var qs = new NameValueCollection(Request.QueryString);

            foreach (var filter in activities.FilterValues)
            {
                qs.Set("t2-" + filter.Key.FieldName, filter.Value.ToString());
            }

            Type responseType = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);
            IOpenSearchResultCollection osr = ose.Query(activities, qs, responseType);

            OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(activities, osr);

            context.Close();
            return(new HttpResult(osr.SerializeToString(), osr.ContentType));
        }
Esempio n. 17
0
        public void JoinPrivateCommunity()
        {
            context.AccessLevel = EntityAccessLevel.Privilege;
            var usr1       = User.FromUsername(context, "testusr1");
            var usr2       = User.FromUsername(context, "testusr2");
            var ose        = MasterCatalogue.OpenSearchEngine;
            var parameters = new NameValueCollection();

            try {
                context.StartImpersonation(usr1.Id);

                ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-private-1");
                Role role = Role.FromIdentifier(context, RoleTep.MEMBER);

                //check how many communities user can see
                var communities = new CommunityCollection(context);
                communities.Identifier       = "community";
                communities.OpenSearchEngine = ose;
                IOpenSearchResultCollection osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);

                context.EndImpersonation();
                context.StartImpersonation(usr2.Id);

                //add user in community
                community.SetUserAsTemporaryMember(usr1);
                Assert.True(community.IsUserPending(usr1.Id));

                context.EndImpersonation();
                context.StartImpersonation(usr1.Id);

                //check how many communities user can see
                communities                  = new CommunityCollection(context);
                communities.Identifier       = "community";
                communities.OpenSearchEngine = ose;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC + 1, osr.TotalResults);

                //check visibility is private + pending
                var  items = osr.Items;
                bool isprivate = false, isVisibilityPending = false, ispublic = false;
                foreach (var item in items)
                {
                    if (item.Title.Text == "community-private-1")
                    {
                        foreach (var cat in item.Categories)
                        {
                            if (cat.Name == "visibility")
                            {
                                if (cat.Label == "hidden")
                                {
                                    isprivate = true;
                                }
                                else if (cat.Label == "public")
                                {
                                    ispublic = true;
                                }
                            }
                            else if (cat.Name == "status" && cat.Label == "pending")
                            {
                                isVisibilityPending = true;
                            }
                        }
                    }
                }
                Assert.True(isprivate);
                Assert.True(isVisibilityPending);
                Assert.False(ispublic);

                //usr1 validates
                community.TryJoinCurrentUser();
                Assert.True(community.IsUserPending(usr1.Id));

                //check how many communities user can see
                communities                  = new CommunityCollection(context);
                communities.Identifier       = "community";
                communities.OpenSearchEngine = ose;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC + 1, osr.TotalResults);

                //remove from community
                community.RemoveUser(usr1);

                //check how many communities user can see
                communities                  = new CommunityCollection(context);
                communities.Identifier       = "community";
                communities.OpenSearchEngine = ose;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);
            } catch (Exception e) {
                Assert.Fail(e.Message);
            } finally {
                context.EndImpersonation();
            }
        }
Esempio n. 18
0
        public object Put(AnalyticsServicesCommunityRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            var result  = new List <WebAnalyticsService>();

            try {
                context.Open();
                context.LogInfo(this, string.Format("/analytics/service/community/{0} PUT", request.Identifier));

                if (string.IsNullOrEmpty(request.Usernames))
                {
                    return(new List <WebAnalyticsService>());
                }
                var usernames  = request.Usernames.Split(',');
                var usernamesS = "'" + string.Join("','", usernames) + "'";

                string sql = string.Format("SELECT id FROM usr WHERE username IN ({0});", usernamesS);
                context.LogDebug(this, sql);
                var requestids = context.GetQueryIntegerValues(sql);
                context.LogDebug(this, "found " + requestids.Length);

                ServiceAnalytics analytics = new ServiceAnalytics(context);
                var community = ThematicCommunity.FromIdentifier(context, request.Identifier);
                if (!community.CanUserManage(context.UserId))
                {
                    return(new List <WebAnalyticsService>());
                }
                var userids = community.GetUsersIds();
                context.LogDebug(this, "found " + userids.Count);

                var ids = new List <int>();
                foreach (var id in requestids)
                {
                    if (userids.Contains(id))
                    {
                        if (!ids.Contains(id))
                        {
                            ids.Add(id);
                        }
                    }
                }

                context.LogDebug(this, ids.Count + " in common");

                var apps       = new List <string>();
                var cachedapps = community.GetThematicApplicationsCached();
                foreach (var app in cachedapps)
                {
                    apps.Add(app.UId);
                }

                context.LogDebug(this, "found " + apps.Count + " apps");

                analytics.AddServices(request.startdate, request.enddate, ids, apps);
                foreach (var service in analytics.Services)
                {
                    result.Add(new WebAnalyticsService(service));
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Esempio n. 19
0
        public void SearchAllCommunities()
        {
            var ose        = MasterCatalogue.OpenSearchEngine;
            var parameters = new NameValueCollection();

            context.AccessLevel = EntityAccessLevel.Privilege;
            var usr1 = User.FromUsername(context, "testusr1");
            var usr2 = User.FromUsername(context, "testusr2");
            var usr3 = User.FromUsername(context, "testusr3");

            try {
                context.StartImpersonation(usr1.Id);

                var communities = new CommunityCollection(context);
                communities.Identifier       = "community";
                communities.OpenSearchEngine = ose;
                //communities.UserId = usr1.Id;
                var osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);

                parameters.Set("q", "public");
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);

                parameters.Set("q", "public*");
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);

                parameters.Set("q", "*");
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(NBCOMMUNITY_PUBLIC, osr.TotalResults);

                parameters.Remove("q");
                parameters.Set("status", "joined");
                communities.UserStatus = ThematicCommunity.USERSTATUS_JOINED;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(0, osr.TotalResults);

                context.EndImpersonation();

                context.StartImpersonation(usr2.Id);
                communities.UserId = usr2.Id;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(4, osr.TotalResults);
                context.EndImpersonation();

                context.StartImpersonation(usr3.Id);
                ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-public-1");
                community.TryJoinCurrentUser();
                var roles = Role.GetUserRolesForDomain(context, usr3.Id, community.Id);

                //user part of community
                Assert.AreEqual(1, roles.Length);
                Assert.AreEqual(RoleTep.MEMBER, roles[0].Name);

                communities.UserId = usr3.Id;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(1, osr.TotalResults);

                context.EndImpersonation();
                communities.UserId = usr3.Id;
                osr = ose.Query(communities, parameters);
                Assert.AreEqual(1, osr.TotalResults);
            } catch (Exception e) {
                context.EndImpersonation();
                Assert.Fail(e.Message);
            }
        }
Esempio n. 20
0
        public object Get(ThematicAppByCommunitySearchRequestTep request)
        {
            IfyWebContext context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/community/{{domain}}/apps/search GET domain='{0}'", request.Domain));

            var domain = ThematicCommunity.FromIdentifier(context, request.Domain);
            IOpenSearchResultCollection result;
            OpenSearchEngine            ose = MasterCatalogue.OpenSearchEngine;
            HttpRequest httpRequest         = HttpContext.Current.Request;
            Type        responseType        = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);

            if (request.cache)
            {
                bool isjoined = domain.IsUserJoined(context.UserId);

                EntityList <ThematicApplicationCached> appsCached = new EntityList <ThematicApplicationCached>(context);
                if (isjoined)
                {
                    appsCached.SetFilter("DomainId", domain.Id.ToString());
                }
                else
                {
                    appsCached.SetFilter("DomainId", "-1");//if user is not joined we dont want him to see results
                }
                appsCached.AddSort("LastUpdate", SortDirection.Descending);
                result = ose.Query(appsCached, httpRequest.QueryString, responseType);
                OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(appsCached, result);
            }
            else
            {
                if (MasterCatalogue.SearchCache != null)
                {
                    MasterCatalogue.SearchCache.ClearCache(".*", DateTime.Now);
                }

                var apps = new EntityList <DataPackage>(context);
                apps.SetFilter("Kind", ThematicApplication.KINDRESOURCESETAPPS.ToString());
                apps.SetFilter("DomainId", domain.Id.ToString());
                apps.Load();

                // the opensearch cache system uses the query parameters
                // we add to the parameters the filters added to the load in order to avoir wrong cache
                // we use 't2-' in order to not interfer with possibly used query parameters
                var qs = new NameValueCollection(Request.QueryString);
                foreach (var filter in apps.FilterValues)
                {
                    qs.Add("t2-" + filter.Key.FieldName, filter.Value.ToString());
                }

                apps.OpenSearchEngine = ose;

                List <Terradue.OpenSearch.IOpenSearchable> osentities = new List <Terradue.OpenSearch.IOpenSearchable>();
                foreach (var app in apps.Items)
                {
                    app.OpenSearchEngine = ose;
                    osentities.AddRange(app.GetOpenSearchableArray());
                }

                var settings = MasterCatalogue.OpenSearchFactorySettings;
                MultiGenericOpenSearchable multiOSE = new MultiGenericOpenSearchable(osentities, settings);
                result = ose.Query(multiOSE, httpRequest.QueryString, responseType);
            }

            var sresult = result.SerializeToString();

            //replace usernames in apps
            try {
                var user = UserTep.FromId(context, context.UserId);
                sresult = sresult.Replace("${USERNAME}", user.Username);
                sresult = sresult.Replace("${T2USERNAME}", user.TerradueCloudUsername);
                sresult = sresult.Replace("${T2APIKEY}", user.GetSessionApiKey());
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
            }

            context.Close();
            return(new HttpResult(sresult, result.ContentType));
        }
Esempio n. 21
0
        public void ShareWpsJobToCommunity()
        {
            context.AccessLevel = EntityAccessLevel.Administrator;
            ThematicCommunity community = ThematicCommunity.FromIdentifier(context, "community-public-1");
            var wpsjob  = WpsJob.FromIdentifier(context, "private-job-usr1");
            var wpsjob2 = WpsJob.FromIdentifier(context, "private-job-usr2");

            context.AccessLevel = EntityAccessLevel.Privilege;

            var usr1 = User.FromUsername(context, "testusr1");

            context.StartImpersonation(usr1.Id);

            try {
                //share as non owner
                try {
                    community.ShareEntity(wpsjob2);
                    Assert.Fail("Cannot share as non owner");
                } catch (Exception) { }

                //share as owner and not member of community
                try {
                    community.ShareEntity(wpsjob2);
                    Assert.Fail("Cannot share as non member");
                } catch (Exception) { }

                community.TryJoinCurrentUser();

                //share as owner and member of community
                community.ShareEntity(wpsjob);

                Assert.True(wpsjob.IsSharedToCommunity());

                EntityList <WpsJob> wpsjobs = new EntityList <WpsJob>(context);
                var parameters = new NameValueCollection();
                parameters.Set("q", "private-job-usr1");
                IOpenSearchResultCollection osr = ose.Query(wpsjobs, parameters);
                Assert.AreEqual(1, osr.TotalResults);
                bool hasSharedLink = false;
                foreach (var item in osr.Items)
                {
                    if (item.Identifier == "private-job-usr1")
                    {
                        foreach (var link in item.Links)
                        {
                            if (link.RelationshipType == "results")
                            {
                                hasSharedLink = true;
                            }
                        }
                    }
                }
                Assert.True(hasSharedLink);

                //unshare the job
                wpsjob.RevokePermissionsFromAll(true, false);
                wpsjob.DomainId = wpsjob.Owner.DomainId;
                wpsjob.Store();

                Assert.False(wpsjob.IsSharedToCommunity());

                wpsjobs    = new EntityList <WpsJob>(context);
                parameters = new NameValueCollection();
                parameters.Set("q", "private-job-usr1");
                osr = ose.Query(wpsjobs, parameters);
                Assert.AreEqual(1, osr.TotalResults);
                hasSharedLink = false;
                foreach (var item in osr.Items)
                {
                    if (item.Identifier == "private-job-usr1")
                    {
                        foreach (var link in item.Links)
                        {
                            if (link.RelationshipType == "results")
                            {
                                hasSharedLink = true;
                            }
                        }
                    }
                }
                Assert.False(hasSharedLink);
            } catch (Exception e) {
                Assert.Fail(e.Message);
            } finally {
                context.EndImpersonation();
            }
        }