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