001/*
002 *  Copyright 2017 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.glpi;
017
018import java.io.ByteArrayOutputStream;
019import java.io.IOException;
020import java.io.InputStream;
021import java.net.URI;
022import java.net.URISyntaxException;
023import java.util.ArrayList;
024import java.util.Collections;
025import java.util.HashMap;
026import java.util.List;
027import java.util.Map;
028import java.util.concurrent.Callable;
029import java.util.concurrent.TimeUnit;
030import java.util.stream.Collectors;
031
032import org.apache.avalon.framework.activity.Initializable;
033import org.apache.avalon.framework.component.Component;
034import org.apache.avalon.framework.service.ServiceException;
035import org.apache.avalon.framework.service.ServiceManager;
036import org.apache.avalon.framework.service.Serviceable;
037import org.apache.commons.io.IOUtils;
038import org.apache.commons.lang3.StringUtils;
039import org.apache.http.client.config.RequestConfig;
040import org.apache.http.client.methods.CloseableHttpResponse;
041import org.apache.http.client.methods.HttpGet;
042import org.apache.http.client.utils.URIBuilder;
043import org.apache.http.impl.client.CloseableHttpClient;
044import org.apache.http.impl.client.HttpClientBuilder;
045
046import org.ametys.core.user.UserIdentity;
047import org.ametys.core.util.JSONUtils;
048import org.ametys.runtime.config.Config;
049import org.ametys.runtime.i18n.I18nizableText;
050import org.ametys.runtime.plugin.component.AbstractLogEnabled;
051import org.ametys.runtime.plugin.component.PluginAware;
052
053import com.google.common.cache.Cache;
054import com.google.common.cache.CacheBuilder;
055import com.google.common.cache.CacheLoader;
056import com.google.common.cache.LoadingCache;
057
058/**
059 * Connection and information from GLPI webservice
060 */
061public class TicketGlpiManager extends AbstractLogEnabled implements Component, Initializable, Serviceable, PluginAware
062{
063    /** Avalon ROLE. */
064    public static final String ROLE = TicketGlpiManager.class.getName();
065
066    private static final String __GLPI_INIT_SESSION = "/initSession/";
067
068    private static final String __GLPI_SEARCH_USERS = "/search/User/";
069
070    private static final String __GLPI_SEARCH_TICKET = "/search/Ticket/";
071
072    private static final String __GLPI_KILL_SESSION = "/killSession/";
073
074    /** Maximum cache size, in number of records. */
075    protected long _maxCacheSize;
076
077    /** The cache TTL in minutes. */
078    protected long _cacheTtl;
079
080    /**
081     * The user information cache. The key of the cache is the user identity it self
082     */
083    protected LoadingCache<UserIdentity, Map<String, Object>> _cache;
084
085    /**
086     * The user information cache. The key of the cache is the user identity it self
087     */
088    protected Cache<String, Integer> _cacheIdentities;
089
090    private JSONUtils _jsonUtils;
091
092    private Map<Integer, I18nizableText> _glpiStatus;
093    private Map<Integer, I18nizableText> _glpiType;
094
095    private String _pluginName;
096
097    public void setPluginInfo(String pluginName, String featureName, String id)
098    {
099        _pluginName = pluginName;
100    }
101    
102    @Override
103    public void service(ServiceManager manager) throws ServiceException
104    {
105        _jsonUtils = (JSONUtils) manager.lookup(JSONUtils.ROLE);
106    }
107
108    @Override
109    public void initialize()
110    {
111        // Tickets cache
112        GlpiCacheLoader loader = new GlpiCacheLoader();
113
114        Long maxCacheSizeConf = Config.getInstance().getValue("org.ametys.plugins.glpi.maxsize");
115        Long maxCacheSize = (long) (maxCacheSizeConf != null ? maxCacheSizeConf.intValue() : 1000);
116
117        Long cacheTtlConf = Config.getInstance().getValue("org.ametys.plugins.glpi.ttl");
118        Long cacheTtl = (long) (cacheTtlConf != null && cacheTtlConf.intValue() >= 0 ? cacheTtlConf.intValue() : 60);
119
120        CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().expireAfterWrite(cacheTtl, TimeUnit.MINUTES);
121
122        if (maxCacheSize > 0)
123        {
124            cacheBuilder.maximumSize(maxCacheSize);
125        }
126
127        _cache = cacheBuilder.build(loader);
128
129        // Identities cache
130        maxCacheSizeConf = Config.getInstance().getValue("org.ametys.plugins.glpi.maxsize.identities");
131        maxCacheSize = (long) (maxCacheSizeConf != null ? maxCacheSizeConf.intValue() : 5000);
132
133        cacheTtlConf = Config.getInstance().getValue("org.ametys.plugins.glpi.ttl.identities");
134        cacheTtl = (long) (cacheTtlConf != null && cacheTtlConf.intValue() >= 0 ? cacheTtlConf.intValue() : 60);
135
136        CacheBuilder<Object, Object> cacheIdentitiesBuilder = CacheBuilder.newBuilder().expireAfterWrite(cacheTtl, TimeUnit.MINUTES);
137
138        if (maxCacheSize > 0)
139        {
140            cacheIdentitiesBuilder.maximumSize(maxCacheSize);
141        }
142
143        _cacheIdentities = cacheIdentitiesBuilder.build();
144    }
145
146    /**
147     * Get the user collaboration information from the exchange server.
148     * 
149     * @param userIdentity the user identity.
150     * @return the user collaboration information as a Map.
151     * @throws Exception If an error occurred
152     */
153    protected Map<String, Object> loadUserInfo(UserIdentity userIdentity) throws Exception
154    {
155        Map<String, Object> userInfo = new HashMap<>();
156
157        String glpiUrl = Config.getInstance().getValue("org.ametys.plugins.glpi.url");
158        String usertoken = Config.getInstance().getValue("org.ametys.plugins.glpi.usertoken");
159        String apptoken = Config.getInstance().getValue("org.ametys.plugins.glpi.apptoken");
160
161        if (glpiUrl == null || usertoken == null || apptoken == null)
162        {
163            if (getLogger().isWarnEnabled())
164            {
165                getLogger().warn("Missing configuration: unable to contact the GLPI WebService Rest API, the configuration is incomplete.");
166            }
167
168            return userInfo;
169        }
170
171        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
172
173        try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).useSystemProperties().build())
174        {
175            String sessionToken = _getGlpiSessionToken(httpclient, glpiUrl, usertoken, apptoken);
176            if (sessionToken == null)
177            {
178                return userInfo;
179            }
180
181            try
182            {
183                Integer userId = _cacheIdentities.get(userIdentity.getLogin().toLowerCase(), new Callable<Integer>()
184                {
185                    @Override
186                    public Integer call() throws Exception
187                    {
188                        return getUserIdentity(httpclient, userIdentity, glpiUrl, sessionToken, apptoken);
189                    }
190                });
191
192                if (userId != null && userId != -1)
193                {
194                    Map<String, Object> glpiOpenTickets = getGlpiTickets(httpclient, glpiUrl, sessionToken, apptoken, userId);
195                    if (glpiOpenTickets != null && !glpiOpenTickets.isEmpty())
196                    {
197                        userInfo.put("countOpenTickets", glpiOpenTickets.get("countOpenTickets"));
198                        userInfo.put("openTickets", glpiOpenTickets.get("openTickets"));
199                    }
200                }
201                else
202                {
203                    getLogger().debug("GPLI identity not found for user {}", userIdentity);
204                }
205            }
206            finally
207            {
208                _killGlpiSessionToken(httpclient, glpiUrl, sessionToken, apptoken);
209            }
210        }
211
212        return userInfo;
213    }
214
215    private String _getGlpiSessionToken(CloseableHttpClient httpclient, String glpiUrl, String usertoken, String apptoken) throws IOException, URISyntaxException
216    {
217        URIBuilder builder = new URIBuilder(glpiUrl + __GLPI_INIT_SESSION).addParameter("user_token", usertoken).addParameter("app_token", apptoken);
218        
219        if (getLogger().isDebugEnabled())
220        {
221            getLogger().debug("Call GLPI webservice to init session : " + builder.build());
222        }
223        
224        Map<String, Object> jsonObject = _callWebServiceApi(httpclient, builder.build(), true);
225        if (jsonObject != null && jsonObject.containsKey("session_token"))
226        {
227            String token = (String) jsonObject.get("session_token");
228            if (getLogger().isDebugEnabled())
229            {
230                getLogger().debug("GPLI WS returned session token '" + token + "'");
231            }
232            return token;
233        }
234        
235        if (getLogger().isDebugEnabled())
236        {
237            getLogger().debug("GPLI WS returned no session token for user token '" + usertoken + "'");
238        }
239
240        return null;
241    }
242
243    /**
244     * Get the user identity and fill the user identities cache
245     * 
246     * @param httpclient The http client to send a request to the webservice
247     * @param userIdentity The current user identity
248     * @param glpiUrl The GLPI Url
249     * @param sessionToken The session token
250     * @param apptoken The app token
251     * @return The user identity corresponding, or null if not found
252     * @throws Exception if an error occurred
253     */
254    @SuppressWarnings("unchecked")
255    protected Integer getUserIdentity(CloseableHttpClient httpclient, UserIdentity userIdentity, String glpiUrl, String sessionToken, String apptoken) throws Exception
256    {
257        Long maxIdentitiesSize = Config.getInstance().getValue("org.ametys.plugins.glpi.maxsize.identities");
258        URIBuilder builder = new URIBuilder(glpiUrl + __GLPI_SEARCH_USERS)
259                .addParameter("range", "0-" + (maxIdentitiesSize != null ? maxIdentitiesSize : 1000))
260                .addParameter("forcedisplay[0]", "1")
261                .addParameter("forcedisplay[1]", "2")
262                .addParameter("criteria[0][field]", "8")
263                .addParameter("criteria[0][searchtype]", "contains")
264                .addParameter("criteria[0][value]", "1")
265                .addParameter("session_token", sessionToken)
266                .addParameter("app_token", apptoken);
267        Map<String, Object> jsonObject = _callWebServiceApi(httpclient, builder.build(), true);
268        if (jsonObject != null && jsonObject.containsKey("data"))
269        {
270            List<Map<String, Object>> data = (List<Map<String, Object>>) jsonObject.get("data");
271            Map<String, Integer> userIdentities = data.stream().filter(user -> StringUtils.isNotEmpty((String) user.get("1")) && user.containsKey("2")).collect(
272                    Collectors.toMap(user -> ((String) user.get("1")).toLowerCase(), user -> (Integer) user.get("2")));
273            _cacheIdentities.putAll(userIdentities);
274            
275            if (userIdentities.containsKey(userIdentity.getLogin().toLowerCase()))
276            {
277                return userIdentities.get(userIdentity.getLogin().toLowerCase());
278            }
279        }
280        return -1;
281    }
282
283    /**
284     * Get the GLPI tickets
285     * @param httpclient the HTTP client
286     * @param glpiUrl The url of GLPI server
287     * @param sessionToken The session token
288     * @param apptoken The app token
289     * @param userId The user id
290     * @return The tickets
291     * @throws IOException if an error occurred
292     * @throws URISyntaxException if failed to build uri
293     */
294    protected Map<String, Object> getGlpiTickets(CloseableHttpClient httpclient, String glpiUrl, String sessionToken, String apptoken, Integer userId) throws IOException, URISyntaxException
295    {
296        StringBuilder uri = new StringBuilder(glpiUrl + __GLPI_SEARCH_TICKET + "?");
297        
298        uri.append(getTicketSearchQuery(userId))
299            .append("&session_token=").append(sessionToken)
300            .append("&app_token=").append(apptoken);
301        
302        if (getLogger().isDebugEnabled())
303        {
304            getLogger().debug("Call GLPI webservice to search tickets : " + uri.toString());
305        }
306        
307        Map<String, Object> jsonObject = _callWebServiceApi(httpclient, new URI(uri.toString()), true);
308        if (jsonObject != null)
309        {
310            Map<String, Object> glpiTicketsInfo = new HashMap<>();
311            if (jsonObject.containsKey("totalcount"))
312            {
313                glpiTicketsInfo.put("countOpenTickets", jsonObject.get("totalcount"));
314            }
315            if (jsonObject.containsKey("data"))
316            {
317                Object dataObject = jsonObject.get("data");
318                List<GlpiTicket> glpiTickets = new ArrayList<>();
319                if (dataObject instanceof List)
320                {
321                    @SuppressWarnings("unchecked")
322                    List<Object> dataList = (List<Object>) dataObject;
323                    for (Object object : dataList)
324                    {
325                        if (object instanceof Map)
326                        {
327                            @SuppressWarnings("unchecked")
328                            Map<String, Object> ticketData = (Map<String, Object>) object;
329                            glpiTickets.add(parseTicket(ticketData));
330                        }
331                    }
332                    glpiTicketsInfo.put("openTickets", glpiTickets);
333                }
334            }
335            return glpiTicketsInfo;
336        }
337        return null;
338    }
339    
340    /**
341     * Parse data into {@link GlpiTicket}
342     * @param data the json data
343     * @return the {@link GlpiTicket}
344     */
345    protected GlpiTicket parseTicket(Map<String, Object> data)
346    {
347        int ticketId = (int) data.get("2");
348        String ticketTitle = (String) data.get("1");
349        int status = (int) data.get("12");
350        
351        int type = data.containsKey("14") ? (int) data.get("14") : -1;
352        String category = (String) data.get("7");
353        
354        GlpiTicket ticket = new GlpiTicket(ticketId, ticketTitle, status, type, category);
355        return ticket;
356    }
357    
358    /**
359     * Get the part of rest API url for tickets search
360     * @param userId The user id
361     * @return The search query to concat to rest API url
362     */
363    protected String getTicketSearchQuery(Integer userId)
364    {
365        StringBuilder sb = new StringBuilder();
366        
367        // forcedisplay is used for data to return
368        
369        // To get all available search options, call GLPI_URL/listSearchOptions/Ticket?session_token=...
370        
371        sb.append("forcedisplay[0]=1") // title
372            .append("&forcedisplay[1]=12") // status
373            .append("&forcedisplay[2]=4") // user id
374            .append("&forcedisplay[3]=2") // ticket id
375            .append("&forcedisplay[4]=7") // category
376            .append("&forcedisplay[6]=14") // type
377            .append("&criteria[0][field]=12&criteria[0][searchtype]=0&criteria[0][value]=notold") // status=notold (unresolved)
378            .append("&criteria[1][link]=AND")
379            .append("&criteria[1][field]=4&criteria[1][searchtype]=equals&criteria[1][value]=" + userId) // current user is the creator
380            .append("&sort=4"); // sort
381        
382        // Get tickets with unresolved status (notold)
383        return sb.toString();
384    }
385
386    private void _killGlpiSessionToken(CloseableHttpClient httpclient, String glpiUrl, String sessionToken, String apptoken) throws IOException, URISyntaxException
387    {
388        URIBuilder builder = new URIBuilder(glpiUrl + __GLPI_KILL_SESSION).addParameter("session_token", sessionToken).addParameter("app_token", apptoken);
389        _callWebServiceApi(httpclient, builder.build(), false);
390    }
391
392    private Map<String, Object> _callWebServiceApi(CloseableHttpClient httpclient, URI uri, boolean getJsonObject) throws IOException
393    {
394        HttpGet get = new HttpGet(uri);
395
396        try (CloseableHttpResponse httpResponse = httpclient.execute(get))
397        {
398            if (!_isSuccess(httpResponse.getStatusLine().getStatusCode()))
399            {
400                String msg = null;
401                if (httpResponse.getEntity() != null)
402                {
403                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
404                    try (InputStream is = httpResponse.getEntity().getContent())
405                    {
406                        IOUtils.copy(is, bos);
407                    }
408                    
409                    msg = bos.toString("UTF-8");
410                }
411                
412                getLogger().error("An error occurred while contacting the GLPI Rest API (status code : " + httpResponse.getStatusLine().getStatusCode() + "). Response is : " + msg);
413                return null;
414            }
415
416            if (getJsonObject)
417            {
418                ByteArrayOutputStream bos = new ByteArrayOutputStream();
419                try (InputStream is = httpResponse.getEntity().getContent())
420                {
421                    IOUtils.copy(is, bos);
422                }
423
424                if (getLogger().isDebugEnabled())
425                {
426                    getLogger().debug("GLPI webservice at uri " + uri + " returned : " + bos.toString("UTF-8"));
427                }
428                
429                return _jsonUtils.convertJsonToMap(bos.toString("UTF-8"));
430            }
431        }
432
433        return null;
434    }
435
436    private boolean _isSuccess(int statusCode)
437    {
438        return statusCode >= 200 && statusCode < 300;
439    }
440
441    /**
442     * Get the number of open tickets
443     * @param userIdentity The user identity
444     * @return the number of unread mail
445     */
446    public int getCountOpenTickets(UserIdentity userIdentity)
447    {
448        if (userIdentity == null)
449        {
450            throw new IllegalArgumentException("User is not connected");
451        }
452        
453        Map<String, Object> userInfo = _cache.getUnchecked(userIdentity);
454        if (userInfo.get("countOpenTickets") != null)
455        {
456            return (Integer) userInfo.get("countOpenTickets");
457        }
458        else
459        {
460            return -1;
461            //throw new IllegalArgumentException("Unable to get open tickets count. No user matches in GPLI with login " + userIdentity.getLogin());
462        }
463    }
464
465    /**
466     * Get all information about open tickets
467     * @param userIdentity The user identity
468     * @return List of all information about open tickets
469     */
470    @SuppressWarnings("unchecked")
471    public List<GlpiTicket> getOpenTickets(UserIdentity userIdentity)
472    {
473        if (userIdentity == null)
474        {
475            throw new IllegalArgumentException("User is not connected");
476        }
477        
478        Map<String, Object> userInfo = _cache.getUnchecked(userIdentity);
479        if (userInfo.get("openTickets") != null)
480        {
481            return (List<GlpiTicket>) userInfo.get("openTickets");
482        }
483        else
484        {
485            return Collections.EMPTY_LIST;
486            //throw new IllegalArgumentException("Unable to get open tickets. No user matches in GPLI with login " + userIdentity.getLogin());
487        }
488    }
489
490    /**
491     * Get the i18n label of a GLPI status
492     * @param status The GLPI status
493     * @return the label of status as {@link I18nizableText}
494     */
495    public I18nizableText getGlpiStatusLabel(int status)
496    {
497        if (_glpiStatus == null)
498        {
499            _glpiStatus = new HashMap<>();
500            _glpiStatus.put(1, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_INCOMMING_STATUS"));
501            _glpiStatus.put(2, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_ASSIGNED_STATUS"));
502            _glpiStatus.put(3, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_PLANNED_STATUS"));
503            _glpiStatus.put(4, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_WAITING_STATUS"));
504            _glpiStatus.put(5, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_SOLVED_STATUS"));
505            _glpiStatus.put(6, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_CLOSED_STATUS"));
506            
507        }
508        return _glpiStatus.get(Integer.valueOf(status));
509    }
510    
511    /**
512     * Get the i18n label of a GLPI ticket type
513     * @param type The GLPI type
514     * @return the label of status as {@link I18nizableText}
515     */
516    public I18nizableText getGlpiTypeLabel(int type)
517    {
518        if (_glpiType == null)
519        {
520            _glpiType = new HashMap<>();
521            _glpiType.put(1, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_INCIDENT_TYPE"));
522            _glpiType.put(2, new I18nizableText("plugin." + _pluginName, "PLUGINS_GLPI_DEMAND_TYPE"));
523            
524        }
525        return _glpiType.get(Integer.valueOf(type));
526    }
527
528    /**
529     * The Glpi cache loader.
530     */
531    protected class GlpiCacheLoader extends CacheLoader<UserIdentity, Map<String, Object>>
532    {
533        @Override
534        public Map<String, Object> load(UserIdentity userIdentity) throws Exception
535        {
536            return loadUserInfo(userIdentity);
537        }
538    }
539}