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.time.ZonedDateTime;
019import java.util.ArrayList;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.HashSet;
023import java.util.List;
024import java.util.Map;
025import java.util.Set;
026import java.util.function.Predicate;
027import java.util.stream.Collectors;
028
029import org.apache.avalon.framework.component.Component;
030import org.apache.avalon.framework.service.ServiceException;
031import org.apache.avalon.framework.service.ServiceManager;
032import org.apache.avalon.framework.service.Serviceable;
033import org.apache.commons.lang3.StringUtils;
034
035import org.ametys.core.right.RightManager;
036import org.ametys.core.ui.Callable;
037import org.ametys.core.user.CurrentUserProvider;
038import org.ametys.core.user.UserIdentity;
039import org.ametys.core.userpref.UserPreferencesException;
040import org.ametys.core.userpref.UserPreferencesManager;
041import org.ametys.core.util.DateUtils;
042import org.ametys.plugins.explorer.resources.ModifiableResourceCollection;
043import org.ametys.plugins.repository.AmetysObjectIterable;
044import org.ametys.plugins.repository.AmetysObjectResolver;
045import org.ametys.plugins.repository.activities.Activity;
046import org.ametys.plugins.repository.activities.ActivityHelper;
047import org.ametys.plugins.repository.activities.ActivityTypeExpression;
048import org.ametys.plugins.repository.activities.ActivityTypeExtensionPoint;
049import org.ametys.plugins.repository.query.expression.AndExpression;
050import org.ametys.plugins.repository.query.expression.DateExpression;
051import org.ametys.plugins.repository.query.expression.Expression;
052import org.ametys.plugins.repository.query.expression.Expression.Operator;
053import org.ametys.plugins.repository.query.expression.ExpressionContext;
054import org.ametys.plugins.repository.query.expression.OrExpression;
055import org.ametys.plugins.repository.query.expression.StringExpression;
056import org.ametys.plugins.workspaces.activities.AbstractWorkspacesActivityType;
057import org.ametys.plugins.workspaces.project.ProjectManager;
058import org.ametys.plugins.workspaces.project.modules.WorkspaceModule;
059import org.ametys.plugins.workspaces.project.objects.Project;
060import org.ametys.runtime.plugin.component.AbstractLogEnabled;
061
062/**
063 * Component gathering methods for the activity stream service
064 */
065public class ActivityStreamClientInteraction extends AbstractLogEnabled implements Component, Serviceable
066{
067    /** The Avalon role */
068    public static final String ROLE = ActivityStreamClientInteraction.class.getName();
069    
070    /** the user preferences context for activity stream */
071    public static final String ACTIVITY_STREAM_USER_PREF_CONTEXT = "/workspaces/activity-stream";
072    
073    /** the id of user preferences for the last update of activity stream*/
074    public static final String ACTIVITY_STREAM_USER_PREF_LAST_UPDATE = "lastUpdate";
075
076    private ProjectManager _projectManager;
077    private ActivityTypeExtensionPoint _activityTypeExtensionPoint;
078
079    private CurrentUserProvider _currentUserProvider;
080
081    private RightManager _rightManager;
082
083    private UserPreferencesManager _userPrefManager;
084
085    private AmetysObjectResolver _resolver;
086
087    @Override
088    public void service(ServiceManager serviceManager) throws ServiceException
089    {
090        _projectManager = (ProjectManager) serviceManager.lookup(ProjectManager.ROLE);
091        _rightManager = (RightManager) serviceManager.lookup(RightManager.ROLE);
092        _activityTypeExtensionPoint = (ActivityTypeExtensionPoint) serviceManager.lookup(ActivityTypeExtensionPoint.ROLE);
093        _currentUserProvider = (CurrentUserProvider) serviceManager.lookup(CurrentUserProvider.ROLE);
094        _userPrefManager = (UserPreferencesManager) serviceManager.lookup(UserPreferencesManager.ROLE);
095        _resolver = (AmetysObjectResolver) serviceManager.lookup(AmetysObjectResolver.ROLE);
096    }
097    
098    /**
099     * Get the activities of the given projects and of the given event types
100     * @param projectNames the names of the projects. Can not be null.
101     * @param filterEventTypes the type of events to retain. Can be empty to get all activities.
102     * @param limit The max number of activities
103     * @return the retained activities
104     */
105    @Callable (rights = Callable.CHECKED_BY_IMPLEMENTATION)
106    public List<Map<String, Object>> getActivities(List<String> projectNames, List<String> filterEventTypes, int limit)
107    {
108        return getActivities(projectNames, filterEventTypes, null, null, null, limit);
109    }
110    
111    /**
112     * Get the activities of the given projects and of the given event types
113     * @param projectNames the names of the projects. Can not be null.
114     * @param filterEventTypes the type of events to retain. Can be empty to get all activities.
115     * @param fromDate To get activities after the given date. Can be null.
116     * @param untilDate To get activities before the given date. Can be null.
117     * @param pattern A filter pattern. Can be null or empty
118     * @param limit The max number of activities
119     * @return the retained activities
120     */
121    public List<Map<String, Object>> getActivities(List<String> projectNames, List<String> filterEventTypes, ZonedDateTime fromDate, ZonedDateTime untilDate, String pattern, int limit)
122    {
123        List<Map<String, Object>> mergedActivities = new ArrayList<>();
124        
125        if (projectNames.isEmpty())
126        {
127            return mergedActivities;
128        }
129        
130        try (AmetysObjectIterable<Activity> activitiesIterable = _getActivities(projectNames, filterEventTypes, fromDate, untilDate, pattern))
131        {
132            if (activitiesIterable != null)
133            {
134                // FIXME Add 20% to requested limit to take into account merge of activities
135                List<Activity> activities = activitiesIterable.stream().limit(Math.round(limit + limit * 0.5)).toList();
136                
137                // FIXME After merge, the number of activities could be lower than limit
138                mergedActivities.addAll(_activityTypeExtensionPoint.mergeActivities(activities));
139            }
140        }
141        
142        return mergedActivities.stream().limit(limit).toList();
143    }
144    
145    private AmetysObjectIterable<Activity> _getActivities(List<String> projectNames, List<String> filterEventTypes, ZonedDateTime fromDate, ZonedDateTime untilDate, String pattern)
146    {
147        OrExpression exprs = new OrExpression();
148        
149        Set<String> allAllowedEventTypes = new HashSet<>();
150        
151        for (String projectName : projectNames)
152        {
153            Project project = _projectManager.getProject(projectName);
154            
155            Set<String> allowedEventTypes = _getAllowedEventTypesByProject(project);
156            
157            if (filterEventTypes != null && filterEventTypes.size() > 0)
158            {
159                allowedEventTypes.retainAll(filterEventTypes);
160            }
161            
162            allAllowedEventTypes.addAll(allowedEventTypes);
163            
164            if (allowedEventTypes.size() > 0)
165            {
166                Expression activityTypeExpr = new ActivityTypeExpression(Operator.EQ, allowedEventTypes.toArray(new String[allowedEventTypes.size()]));
167                Expression projectExpr = new StringExpression(AbstractWorkspacesActivityType.PROJECT_NAME, Operator.EQ, projectName);
168                
169                exprs.add(new AndExpression(activityTypeExpr, projectExpr));
170            }
171        }
172        
173        if (!exprs.isEmpty())
174        {
175            AndExpression finalExpr = new AndExpression();
176            
177            finalExpr.add(exprs);
178            
179            if (untilDate != null)
180            {
181                finalExpr.add(new DateExpression("date", Operator.LT, untilDate));
182            }
183            
184            if (fromDate != null)
185            {
186                finalExpr.add(new DateExpression("date", Operator.GT, fromDate));
187            }
188            
189            if (StringUtils.isNotEmpty(pattern))
190            {
191                OrExpression patternExprs = new OrExpression();
192                
193                patternExprs.add(new StringExpression(AbstractWorkspacesActivityType.PROJECT_TITLE, Operator.WD, pattern, ExpressionContext.newInstance().withCaseInsensitive(true)));
194                
195                for (String allowedEventType : allAllowedEventTypes)
196                {
197                    _activityTypeExtensionPoint.getActivityTypes(allowedEventType)
198                            .stream()
199                            .filter(AbstractWorkspacesActivityType.class::isInstance)
200                            .map(AbstractWorkspacesActivityType.class::cast)
201                            .forEach(wsActivityType -> {
202                                Expression patternExpr = wsActivityType.getFilterPatternExpression(pattern);
203                                if (patternExpr != null)
204                                {
205                                    patternExprs.add(patternExpr);
206                                }
207                            });
208                }
209                
210                finalExpr.add(patternExprs);
211            }
212            
213            String xpathQuery = ActivityHelper.getActivityXPathQuery(finalExpr);
214            return _resolver.query(xpathQuery);
215        }
216        
217        
218        return null;
219    }
220    
221    /**
222     * Get the date of last activity regardless the current user's rights
223     * @param projectName The project's name
224     * @param excludeActivityTypes the types of activity to ignore from this search
225     * @return the date of last activity or null if no activity found or an error occurred
226     */
227    public ZonedDateTime getDateOfLastActivity(String projectName, List<String> excludeActivityTypes)
228    {
229        AndExpression expressions = new AndExpression();
230        
231        for (String eventType : excludeActivityTypes)
232        {
233            expressions.add(new ActivityTypeExpression(Operator.NE, eventType));
234        }
235        
236        return _getDateOfLastActivity(projectName, expressions);
237    }
238
239    /**
240     * Get the date of last activity regardless the current user's rights
241     * @param projectName The project's name
242     * @param includeActivityTypes the types of activity to ignore from this search
243     * @return the date of last activity or null if no activity found or an error occurred
244     */
245    public ZonedDateTime getDateOfLastActivityByActivityType(String projectName, Collection<String> includeActivityTypes)
246    {
247        OrExpression expressions = new OrExpression();
248        
249        for (String eventType : includeActivityTypes)
250        {
251            expressions.add(new ActivityTypeExpression(Operator.EQ, eventType));
252        }
253        
254        return _getDateOfLastActivity(projectName, expressions);
255    }
256    
257    private ZonedDateTime _getDateOfLastActivity(String projectName, Expression eventTypesExpression)
258    {
259        Expression projectNameExpression = new StringExpression("projectName", Operator.EQ, projectName);
260        
261        Expression eventExpr = new AndExpression(projectNameExpression, eventTypesExpression);
262        
263        String xpathQuery = ActivityHelper.getActivityXPathQuery(eventExpr);
264        AmetysObjectIterable<Activity> activities = _resolver.query(xpathQuery);
265        
266        for (Activity activity: activities)
267        {
268            return activity.getDate();
269        }
270        
271        return null;
272    }
273    
274    /**
275     * Get the list of allowed event types for the given projects
276     * @param projects The projects
277     * @return The allowed event types
278     */
279    public Set<String> getAllowedEventTypes (Set<Project> projects)
280    {
281        Set<String> allowedTypes = new HashSet<>();
282        
283        for (Project project : projects)
284        {
285            allowedTypes.addAll(_getAllowedEventTypesByProject(project));
286        }
287        
288        return allowedTypes;
289    }
290    
291    // FIXME temporary method
292    // The allowed types are hard coded according the user access on root modules.
293    private Set<String> _getAllowedEventTypesByProject (Project project)
294    {
295        Set<String> allowedTypes = new HashSet<>();
296        
297        for (WorkspaceModule moduleManager : _projectManager.getModules(project))
298        {
299            ModifiableResourceCollection moduleRoot = moduleManager.getModuleRoot(project, false);
300            if (moduleRoot != null && _rightManager.currentUserHasReadAccess(moduleRoot))
301            {
302                allowedTypes.addAll(moduleManager.getAllowedEventTypes());
303            }
304        }
305        
306        return allowedTypes;
307    }
308    
309    /**
310     * Get the number of unread events for the current user
311     * @return the number of unread events or -1 if user never read events
312     */
313    @Callable (rights = Callable.NO_CHECK_REQUIRED)
314    public long getNumberOfUnreadActivitiesForCurrentUser()
315    {
316        ZonedDateTime lastUpdate = _getLastReadDate();
317        if (lastUpdate != null)
318        {
319            Set<Project> userProjects = _getProjectsForCurrentUser(null);
320            List<String> projectNames = transformProjectsToName(userProjects);
321            Set<String> allowedEventTypes = getAllowedEventTypes(userProjects);
322            
323            AmetysObjectIterable<Activity> activities = _getActivities(projectNames, new ArrayList<>(allowedEventTypes), lastUpdate, null, null);
324            return activities != null ? activities.getSize() : -1;
325        }
326        return -1;
327    }
328    
329    /**
330     * Get the activities for the current user with the allowed event types get from the user projects.
331     * @param limit The max number of results
332     * @return The activities for the user projects
333     */
334    public List<Map<String, Object>> getActivitiesForCurrentUser(int limit)
335    {
336        return getActivitiesForCurrentUser((String) null, null, null, limit);
337    }
338    
339    /**
340     * Get the activities for the current user with the allowed event types get from the user projects.
341     * @param pattern Pattern to search on activity. Can null or empty to not filter on pattern.
342     * @param activityTypes the type of activities to retrieve. Can null or empty to not filter on activity types.
343     * @param categories the categories of projects to retrieve. Can null or empty to not filter on themes.
344     * @param limit The max number of results
345     * @return The activities for the user projects
346     */
347    public List<Map<String, Object>> getActivitiesForCurrentUser(String pattern, Set<String> categories, Set<String> activityTypes, int limit)
348    {
349        return getActivitiesForCurrentUser(pattern,  categories, activityTypes, null, null, limit);
350    }
351    
352    /**
353     * Get the activities for the current user with the allowed event types get from the user projects.
354     * @param pattern Pattern to search on activity. Can null or empty to not filter on pattern.
355     * @param activityTypes the type of activities to retrieve. Can null or empty to not filter on activity types.
356     * @param categories the categories of projects to retrieve. Can null or empty to not filter on themes.
357     * @param fromDate To get activities after the given date. Can be null.
358     * @param untilDate To get activities before the given date. Can be null.
359     * @param limit The max number of results
360     * @return The activities for the user projects
361     */
362    public List<Map<String, Object>> getActivitiesForCurrentUser(String pattern, Set<String> categories, Set<String> activityTypes, ZonedDateTime fromDate, ZonedDateTime untilDate, int limit)
363    {
364        Set<Project> userProjects = _getProjectsForCurrentUser(categories);
365        return getActivitiesForCurrentUser(userProjects, activityTypes, fromDate, untilDate, pattern, limit);
366    }
367    
368    /**
369     * Get the activities for the current user with the allowed event types get from the given projects.
370     * @param projects the projects
371     * @param activityTypes the type of activities to retrieve. Can null or empty to not filter on activity types.
372     * @param fromDate To get activities after the given date. Can be null.
373     * @param untilDate To get activities before the given date. Can be null.
374     * @param pattern Pattern to search on activity. Can null or empty to not filter on pattern.
375     * @param limit The max number of results
376     * @return The activities for the user projects
377     */
378    public List<Map<String, Object>> getActivitiesForCurrentUser(Set<Project> projects, Set<String> activityTypes, ZonedDateTime fromDate, ZonedDateTime untilDate, String pattern, int limit)
379    {
380        List<String> projectNames = transformProjectsToName(projects);
381        Set<String> allowedActivityTypes = getAllowedEventTypes(projects);
382        
383        if (activityTypes != null && activityTypes.size() > 0)
384        {
385            allowedActivityTypes.retainAll(activityTypes);
386        }
387        
388        List<Map<String, Object>> activities = getActivities(projectNames, new ArrayList<>(allowedActivityTypes), fromDate, untilDate, pattern, limit);
389        
390        // Add a parameter representing the date in the ISO 8601 format
391        activities.stream().forEach(activity ->
392        {
393            String eventDate = (String) activity.get("date");
394            
395            ZonedDateTime lastReadDate = _getLastReadDate();
396            if (lastReadDate != null)
397            {
398                activity.put("unread", DateUtils.parseZonedDateTime(eventDate).compareTo(lastReadDate) > 0);
399            }
400            // start date
401            activity.put("date-iso", eventDate);
402            
403            // optional end date
404            String endDate = (String) activity.get("endDate");
405            if (endDate != null)
406            {
407                activity.put("end-date-iso", endDate);
408            }
409        });
410        
411        return activities;
412    }
413    
414    private ZonedDateTime _getLastReadDate()
415    {
416        UserIdentity user = _currentUserProvider.getUser();
417        try
418        {
419            return _userPrefManager.getUserPreferenceAsDate(user, ACTIVITY_STREAM_USER_PREF_CONTEXT, Map.of(), ACTIVITY_STREAM_USER_PREF_LAST_UPDATE);
420        }
421        catch (UserPreferencesException e)
422        {
423            getLogger().warn("Unable to get last unread events date from user preferences", e);
424            return null;
425        }
426    }
427    
428    private Set<Project> _getProjectsForCurrentUser(Set<String> filteredCategories)
429    {
430        UserIdentity user = _currentUserProvider.getUser();
431        
432        Predicate<Project> matchCategories = p -> filteredCategories == null || filteredCategories.isEmpty() || !Collections.disjoint(p.getCategories(), filteredCategories);
433        
434        return _projectManager.getUserProjects(user).keySet()
435                   .stream()
436                   .filter(matchCategories)
437                   .collect(Collectors.toSet());
438    }
439    
440    private List<String> transformProjectsToName(Set<Project> userProjects)
441    {
442        return userProjects.stream()
443            .map(p -> p.getName())
444            .collect(Collectors.toList());
445    }
446}