001/*
002 *  Copyright 2018 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 */
016
017package org.ametys.plugins.calendar.helpers;
018
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Map;
025import java.util.stream.Collectors;
026
027import org.apache.avalon.framework.component.Component;
028import org.apache.avalon.framework.service.ServiceException;
029import org.apache.avalon.framework.service.ServiceManager;
030import org.apache.avalon.framework.service.Serviceable;
031import org.apache.cocoon.environment.Request;
032
033import org.ametys.core.user.CurrentUserProvider;
034import org.ametys.core.user.UserIdentity;
035import org.ametys.core.userpref.UserPreferencesException;
036import org.ametys.core.userpref.UserPreferencesManager;
037import org.ametys.core.util.JSONUtils;
038import org.ametys.web.WebHelper;
039
040/**
041 * helper to manage calendar categories
042 */
043public class CalendarCategoriesHelper implements Component, Serviceable
044{
045    /** The component role. */
046    public static final String ROLE = CalendarCategoriesHelper.class.getName();
047    /**
048     * Parameter name for the zone item id
049     */
050    protected static final String ZONEITEMID = "zoneItemId";
051    
052    /**
053     * user pref id where the categories should be stored
054     */
055    protected static final String USER_PREF_ID = "plugin-calendar-categories";
056    
057    /** The current user provider */
058    protected CurrentUserProvider _currentUserProvider;
059    
060    /** The user preferences */
061    protected UserPreferencesManager _userPref;
062    
063    /** Json utils */
064    protected JSONUtils _jsonUtils;
065    
066    public void service(ServiceManager manager) throws ServiceException
067    {
068        _currentUserProvider = (CurrentUserProvider) manager.lookup(CurrentUserProvider.ROLE);
069        _userPref = (UserPreferencesManager) manager.lookup(UserPreferencesManager.ROLE);
070        _jsonUtils = (JSONUtils) manager.lookup(JSONUtils.ROLE);
071    }
072
073    /**
074     * Set the user preferences for this calendar
075     * @param request the request from the service
076     * @return true if the preference was set
077     * @throws UserPreferencesException impossible to set the preference
078     */
079    public boolean setUserCategories(Request request) throws UserPreferencesException
080    {
081        UserIdentity identity = _currentUserProvider.getUser();
082        
083        if (identity != null)
084        {
085            String siteName = WebHelper.getSiteName(request);
086            String zoneItemId = request.getParameter(ZONEITEMID);
087            String categorieString = request.getParameter("categories");
088            List<String> categories = new ArrayList<>();
089            if (categorieString != null)
090            {
091                categories.add(categorieString);
092            }
093            else
094            {
095                String[] categoriesString = request.getParameterValues("categories[]");
096                categories.addAll(Arrays.asList(categoriesString));
097            }
098            
099            return setUserCategories(identity, siteName, zoneItemId, categories);
100        }
101        else
102        {
103            return false;
104        }
105    }
106    
107    /**
108     * Set the user preferences for this calendar
109     * @param siteName Site name
110     * @param zoneItemId Zone Item Id where the service is put
111     * @param categories categories to set
112     * @return true if the preference was set
113     * @throws UserPreferencesException impossible to set the preference
114     */
115    public boolean setUserCategories(String siteName, String zoneItemId, List<String> categories) throws UserPreferencesException
116    {
117        UserIdentity identity = _currentUserProvider.getUser();
118        return setUserCategories(identity, siteName, zoneItemId, categories);
119    }
120    
121    /**
122     * Set the user preferences for this calendar
123     * @param identity User
124     * @param siteName Site name
125     * @param zoneItemId Zone Item Id where the service is put
126     * @param categories categories to set
127     * @return true if the preference was set
128     * @throws UserPreferencesException impossible to set the preference
129     */
130    public boolean setUserCategories(UserIdentity identity, String siteName, String zoneItemId, List<String> categories) throws UserPreferencesException
131    {
132        if (identity == null)
133        {
134            return false;
135        }
136        
137        String jsonCategories = _jsonUtils.convertObjectToJson(categories);
138        
139        String jsonString = _userPref.getUserPreferenceAsString(identity, "/sites/" + siteName, Collections.emptyMap(), USER_PREF_ID);
140        
141        Map<String, Object> jsonMap = _jsonUtils.convertJsonToMap(jsonString);
142        
143        if (jsonMap == null)
144        {
145            jsonMap = new HashMap<>();
146        }
147        
148        jsonMap.put(zoneItemId, jsonCategories);
149        
150        jsonString = _jsonUtils.convertObjectToJson(jsonMap);
151        
152        Map<String, String> preferences = new HashMap<>();
153        preferences.put(USER_PREF_ID, jsonString);
154        
155        _userPref.setUserPreferences(identity, "/sites/" + siteName, Collections.emptyMap(), preferences);
156        
157        return true;
158    }
159    
160    /**
161     * Get the user preferences for this calendar
162     * @param request the request from the service
163     * @return a List of categories
164     * @throws UserPreferencesException impossible to get the preference
165     */
166    public List<String> getUserCategories(Request request) throws UserPreferencesException
167    {
168        UserIdentity identity = _currentUserProvider.getUser();
169        
170        String siteName = WebHelper.getSiteName(request);
171        String zoneItemId = request.getParameter(ZONEITEMID);
172        
173        return getUserCategories(identity, siteName, zoneItemId);
174    }
175    
176    /**
177     * Get the user preferences for this calendar
178     * @param siteName Site name
179     * @param zoneItemId Zone Item Id where the service is put
180     * @return a List of categories
181     * @throws UserPreferencesException impossible to get the preference
182     */
183    public List<String> getUserCategories(String siteName, String zoneItemId) throws UserPreferencesException
184    {
185        UserIdentity identity = _currentUserProvider.getUser();
186        return getUserCategories(identity, siteName, zoneItemId);
187    }
188    
189    /**
190     * Get the user preferences for this calendar
191     * @param identity User
192     * @param siteName Site name
193     * @param zoneItemId Zone Item Id where the service is put
194     * @return a List of categories
195     * @throws UserPreferencesException impossible to set the preference
196     */
197    public List<String> getUserCategories(UserIdentity identity, String siteName, String zoneItemId) throws UserPreferencesException
198    {
199        List<String> result = new ArrayList<>();
200        if (identity != null)
201        {
202            String jsonString = _userPref.getUserPreferenceAsString(identity, "/sites/" + siteName, Collections.emptyMap(), USER_PREF_ID);
203            
204            Map<String, ? extends Object> jsonMap = _jsonUtils.convertJsonToMap(jsonString);
205            
206            if (jsonMap != null && jsonMap.containsKey(zoneItemId))
207            {
208                Object object = jsonMap.get(zoneItemId);
209                if (object instanceof String)
210                {
211                    result = _jsonUtils.convertJsonToList((String) object).stream()
212                            .filter(String.class::isInstance)
213                            .map(String.class::cast)
214                            .collect(Collectors.toList());
215                }
216                else if (object instanceof List<?>)
217                {
218                    result = ((List<?>) object).stream()
219                    .filter(String.class::isInstance)
220                    .map(String.class::cast)
221                    .collect(Collectors.toList());
222                }
223            }
224            else
225            {
226                result.add("all");
227            }
228        }
229        else
230        {
231            result.add("all");
232        }
233        
234        return result;
235    }
236
237}