001/*
002 *  Copyright 2020 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.mobileapp.action;
017
018import java.util.HashMap;
019import java.util.List;
020import java.util.Map;
021import java.util.stream.Collectors;
022
023import org.apache.avalon.framework.service.ServiceException;
024import org.apache.avalon.framework.service.ServiceManager;
025import org.apache.cocoon.environment.Request;
026
027import org.ametys.plugins.workspaces.project.ProjectsCatalogueManager;
028
029/**
030 * Returns the list of projects for a user
031 */
032public class GetProjectsAction extends AbstractLoggedAction
033{
034    /** The project catalogue manager component */
035    private ProjectsCatalogueManager _projectsCatalogueManager;
036    
037    @Override
038    public void service(ServiceManager smanager) throws ServiceException
039    {
040        super.service(smanager);
041        _projectsCatalogueManager = (ProjectsCatalogueManager) smanager.lookup(ProjectsCatalogueManager.ROLE);
042    }
043    
044    @Override
045    protected Map<String, Object> doLoggedInAction(Request request, Map<String, Object> jsonParams)
046    {
047        Map<String, Object> result = new HashMap<>();
048
049        List<Map<String, Object>> userProjects = _projectsCatalogueManager.getUserProjects();
050        
051        List<Map<String, Object>> feedList = userProjects.stream()
052            .map(up -> _mapResult(up))
053            .collect(Collectors.toList());
054        result.put("feed_list", feedList);
055        
056        return result;
057    }
058    
059    /**
060     * Map a json used for project list to a map used by the mobile app
061     * @param userProject a map representing a project
062     * @return a map used by the mobile app
063     */
064    private Map<String, Object> _mapResult(Map<String, Object> userProject)
065    {
066        Map<String, Object> result = new HashMap<>();
067
068        result.put("feed_id", userProject.get("id"));
069        result.put("name", userProject.get("title"));
070        result.put("url", userProject.get("url"));
071        result.put("illustration", userProject.get("illustration"));
072        if (userProject.containsKey("category"))
073        {
074            result.put("color", ((Map) userProject.get("category")).get("color"));
075        }
076        
077        return result;
078    }
079}