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