001/*
002 *  Copyright 2016 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.workspaces.activities.activitystream;
017
018import java.util.Arrays;
019import java.util.Collections;
020import java.util.Date;
021import java.util.HashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025import java.util.stream.Collectors;
026
027import org.apache.avalon.framework.parameters.Parameters;
028import org.apache.avalon.framework.service.ServiceException;
029import org.apache.avalon.framework.service.ServiceManager;
030import org.apache.cocoon.acting.ServiceableAction;
031import org.apache.cocoon.environment.ObjectModelHelper;
032import org.apache.cocoon.environment.Redirector;
033import org.apache.cocoon.environment.Request;
034import org.apache.cocoon.environment.SourceResolver;
035import org.apache.commons.lang3.StringUtils;
036
037import org.ametys.core.cocoon.ActionResultGenerator;
038import org.ametys.core.user.CurrentUserProvider;
039import org.ametys.core.user.UserIdentity;
040import org.ametys.core.userpref.UserPreferencesManager;
041import org.ametys.core.util.DateUtils;
042import org.ametys.plugins.workspaces.project.ProjectManager;
043import org.ametys.plugins.workspaces.project.modules.WorkspaceModule;
044import org.ametys.plugins.workspaces.project.modules.WorkspaceModuleExtensionPoint;
045import org.ametys.plugins.workspaces.project.objects.Project;
046import org.ametys.web.WebHelper;
047
048/**
049 * Get the activities for activity stream
050 *
051 */
052public class ActivityStreamServiceAction extends ServiceableAction
053{
054    private ActivityStreamClientInteraction _activityStream;
055    private ProjectManager _projectManager;
056    private UserPreferencesManager _userPrefManager;
057    private CurrentUserProvider _currentUserProvider;
058    private WorkspaceModuleExtensionPoint _moduleEP;
059    
060    @Override
061    public void service(ServiceManager smanager) throws ServiceException
062    {
063        super.service(smanager);
064        _activityStream = (ActivityStreamClientInteraction) smanager.lookup(ActivityStreamClientInteraction.ROLE);
065        _projectManager = (ProjectManager) smanager.lookup(ProjectManager.ROLE);
066        _userPrefManager = (UserPreferencesManager) smanager.lookup(UserPreferencesManager.ROLE);
067        _currentUserProvider = (CurrentUserProvider) smanager.lookup(CurrentUserProvider.ROLE);
068        _moduleEP = (WorkspaceModuleExtensionPoint) smanager.lookup(WorkspaceModuleExtensionPoint.ROLE);
069    }
070    
071    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
072    {
073        Request request = ObjectModelHelper.getRequest(objectModel);
074        
075        int limit = parameters.getParameterAsInteger("max-results", Integer.MAX_VALUE);
076        
077        boolean allActivities = parameters.getParameterAsBoolean("all", false);
078        boolean markAsRead = parameters.getParameterAsBoolean("mark-as-read", false);
079        
080        // The filtered modules
081        Set<String> activityTypes = _getFilteredActivityTypes(request);
082        
083        // The filtered projects' categories
084        Set<String> categories = _getFilteredCategories(request);
085        
086        // Fultext search
087        String pattern = request.getParameter("pattern");
088        
089        // Dante range
090        Date fromDate = null;
091        String fromDateAsStr = request.getParameter("fromDate");
092        if (StringUtils.isNotEmpty(fromDateAsStr))
093        {
094            fromDate = DateUtils.asDate(DateUtils.parseZonedDateTime(fromDateAsStr));
095        }
096        Date untilDate = null;
097        String untilDateAsStr = request.getParameter("untilDate");
098        if (StringUtils.isNotEmpty(untilDateAsStr))
099        {
100            untilDate = DateUtils.asDate(DateUtils.parseZonedDateTime(untilDateAsStr));
101        }
102        
103        String siteName = WebHelper.getSiteName(request);
104        
105        List<String> projects = _projectManager.getProjectsForSite(siteName);
106        
107        List<Map<String, Object>> activities;
108        if (projects.isEmpty() || allActivities)
109        {
110            // Get activity stream of all current user's projects
111            activities = _activityStream.getActivitiesForCurrentUser(pattern, categories, activityTypes, fromDate, untilDate, limit);
112        }
113        else
114        {
115            // Get activity stream  of current project only
116            Project project = _projectManager.getProject(projects.get(0));
117            activities = _activityStream.getActivitiesForCurrentUser(Collections.singleton(project), activityTypes, fromDate, untilDate, pattern, limit);
118        }
119        
120        UserIdentity user = _currentUserProvider.getUser();
121        if (markAsRead && user != null)
122        {
123            // Mark as read in user prefs
124            _userPrefManager.setUserPreferences(user, ActivityStreamClientInteraction.ACTIVITY_STREAM_USER_PREF_CONTEXT, Map.of(), Map.of(ActivityStreamClientInteraction.ACTIVITY_STREAM_USER_PREF_LAST_UPDATE, DateUtils.dateToString(new Date())));
125        }
126        
127        Map<String, Object> result = new HashMap<>();
128        // FIXME this should be rename activities
129        result.put("events", activities);
130        
131        request.setAttribute(ActionResultGenerator.MAP_REQUEST_ATTR, result);
132        
133        return EMPTY_MAP;
134    }
135    
136    @SuppressWarnings("cast")
137    private Set<String> _getFilteredActivityTypes(Request request)
138    {
139        String[] moduleIds = request.getParameterValues("modules");
140        if (moduleIds != null)
141        {
142            return Arrays.stream(moduleIds)
143                    .filter(StringUtils::isNotEmpty)
144                    .map(id -> (WorkspaceModule) _moduleEP.getModule(id))
145                    .map(WorkspaceModule::getAllowedEventTypes)
146                    .flatMap(Set::stream)
147                    .collect(Collectors.toSet());
148        }
149        else
150        {
151            return Set.of();
152        }
153    }
154    
155    private Set<String> _getFilteredCategories(Request request)
156    {
157        String[] categoryIds = request.getParameterValues("categories");
158        if (categoryIds != null)
159        {
160            return Arrays.stream(categoryIds)
161                    .filter(StringUtils::isNotEmpty)
162                    .collect(Collectors.toSet());
163        }
164        else
165        {
166            return Set.of();
167        }
168    }
169
170}