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 */
016package org.ametys.web.frontoffice.search.metamodel.impl;
017
018import java.io.InputStream;
019import java.util.ArrayList;
020import java.util.Date;
021import java.util.List;
022
023import org.apache.cocoon.xml.XMLUtils;
024import org.apache.commons.lang.StringUtils;
025import org.apache.tika.Tika;
026import org.slf4j.Logger;
027import org.xml.sax.ContentHandler;
028import org.xml.sax.SAXException;
029
030import org.ametys.cms.repository.Content;
031import org.ametys.core.util.DateUtils;
032import org.ametys.core.util.URIUtils;
033import org.ametys.plugins.explorer.resources.Resource;
034import org.ametys.plugins.repository.AmetysObject;
035import org.ametys.runtime.i18n.I18nizableText;
036import org.ametys.web.frontoffice.search.metamodel.ReturnableSaxer;
037import org.ametys.web.frontoffice.search.requesttime.SearchComponentArguments;
038import org.ametys.web.repository.page.Page;
039import org.ametys.web.repository.site.Site;
040
041/**
042 * {@link ReturnableSaxer} for {@link ResourceReturnable}
043 */
044public class ResourceSaxer implements ReturnableSaxer
045{
046    /** The associated returnable on resources */
047    protected ResourceReturnable _resourceReturnable;
048    
049    /**
050     * Constructor
051     * @param resourceReturnable The associated returnable on resources
052     */
053    public ResourceSaxer(ResourceReturnable resourceReturnable)
054    {
055        _resourceReturnable = resourceReturnable;
056    }
057    
058    @Override
059    public boolean canSax(AmetysObject hit, Logger logger, SearchComponentArguments args)
060    {
061        return hit instanceof Resource;
062    }
063
064    @Override
065    public void sax(ContentHandler contentHandler, AmetysObject hit, Logger logger, SearchComponentArguments args) throws SAXException
066    {
067        Resource resource = (Resource) hit;
068        String filename = resource.getName();
069        XMLUtils.createElement(contentHandler, "filename", filename);
070        XMLUtils.createElement(contentHandler, "title", StringUtils.substringBeforeLast(resource.getName(), "."));
071        
072        String dcDescription = resource.getDCDescription();
073        String excerpt = _getResourceExcerpt(resource, logger);
074        if (StringUtils.isNotBlank(dcDescription))
075        {
076            XMLUtils.createElement(contentHandler, "excerpt", dcDescription);
077        }
078        else if (StringUtils.isNotBlank(excerpt))
079        {
080            XMLUtils.createElement(contentHandler, "excerpt", excerpt + "...");
081        }
082        
083        XMLUtils.createElement(contentHandler, "type", "resource");
084        
085        Page page = _getResourcePage(resource);
086        Content content = _getResourceContent(resource);
087        _saxUri(contentHandler, resource, page, content);
088        XMLUtils.createElement(contentHandler, "mime-types", resource.getMimeType());
089        _saxSize(contentHandler, resource.getLength());
090        _saxIcon(contentHandler, filename);
091        
092        Date lastModified = resource.getLastModified();
093        if (lastModified != null)
094        {
095            XMLUtils.createElement(contentHandler, "lastModified", DateUtils.dateToString(lastModified));
096        }
097        if (page != null)
098        {
099            Site site = page.getSite();
100            XMLUtils.createElement(contentHandler, "siteName", site.getName());
101            XMLUtils.createElement(contentHandler, "siteTitle", site.getTitle());
102            XMLUtils.createElement(contentHandler, "siteUrl", site.getUrl());
103        }
104    }
105    
106    private String _getResourceExcerpt(Resource resource, Logger logger)
107    {
108        try (InputStream is = resource.getInputStream())
109        {
110            Tika tika = _resourceReturnable._tikaProvider.getTika();
111            String value = tika.parseToString(is);
112            if (StringUtils.isNotBlank(value))
113            {
114                int summaryEndIndex = value.lastIndexOf(' ', 200);
115                if (summaryEndIndex == -1)
116                {
117                    summaryEndIndex = value.length();
118                }
119                return value.substring(0, summaryEndIndex) + (summaryEndIndex != value.length() ? "…" : "");
120            }
121        }
122        catch (Exception e)
123        {
124            logger.error("Unable to index resource at " + resource.getPath(), e);
125        }
126        return null;
127    }
128    
129    private Page _getResourcePage(Resource resource)
130    {
131        if (resource != null)
132        {
133            AmetysObject parent = resource.getParent();
134            while (parent != null)
135            {
136                if (parent instanceof Page)
137                {
138                    // We have gone up to the page
139                    return (Page) parent;
140                }
141                parent = parent.getParent();
142            }
143        }
144        
145        return null;
146    }
147    
148    private Content _getResourceContent(Resource resource)
149    {
150        if (resource != null)
151        {
152            AmetysObject parent = resource.getParent();
153            while (parent != null)
154            {
155                if (parent instanceof Content)
156                {
157                    // We have gone up to the content
158                    return (Content) parent;
159                }
160                parent = parent.getParent();
161            }
162        }
163        
164        return null;
165    }
166    
167    private void _saxUri(ContentHandler contentHandler, Resource resource, Page page, Content content) throws SAXException
168    {
169        String uri;
170        if (page != null)
171        {
172            String pageUri = page.getSitemapName() + "/" + page.getPathInSitemap();
173            String encodedPath = _encodePath(_encodePath(resource.getResourcePath().substring(1)));
174            uri = pageUri + "/_attachments/" + encodedPath + "?download=true";
175        }
176        else if (content != null)
177        {
178            String contentName = content.getName();
179            String path = resource.getResourcePath();
180            String encodedPath = _encodePath(_encodePath(contentName + path));
181            uri = "_attachments/" + encodedPath + "?download=true";
182        }
183        else
184        {
185            String path = resource.getResourcePath();
186            String encodedPath = _encodePath(_encodePath(path));
187            uri = "_resources" + encodedPath + "?download=true";
188        }
189        XMLUtils.createElement(contentHandler, "uri", uri);
190    }
191    
192    private String _encodePath(String path)
193    {
194        return URIUtils.encodePath(path);
195    }
196    
197    private void _saxSize(ContentHandler contentHandler, long size) throws SAXException
198    {
199        XMLUtils.startElement(contentHandler, "size");
200        if (size < 1024)
201        {
202            // Bytes
203            List<String> params = new ArrayList<>();
204            params.add(String.valueOf(size));
205            I18nizableText i18nSize = new I18nizableText("plugin.web", "ATTACHMENTS_FILE_SIZE_BYTES", params);
206            i18nSize.toSAX(contentHandler);
207        }
208        else if (size < 1024 * 1024)
209        {
210            // Kb
211            int sizeInKb = Math.round(size * 10 / 1024 / 10);
212            List<String> params = new ArrayList<>();
213            params.add(String.valueOf(sizeInKb));
214            I18nizableText i18nSize = new I18nizableText("plugin.web", "ATTACHMENTS_FILE_SIZE_KB", params);
215            i18nSize.toSAX(contentHandler);
216
217        }
218        else
219        {
220            // Mb
221            int sizeInMb = Math.round(size * 10 / (1024 * 1024) / 10);
222            List<String> params = new ArrayList<>();
223            params.add(String.valueOf(sizeInMb));
224            I18nizableText i18nSize = new I18nizableText("plugin.web", "ATTACHMENTS_FILE_SIZE_MB", params);
225            i18nSize.toSAX(contentHandler);
226        }
227        XMLUtils.endElement(contentHandler, "size");
228    }
229    
230    private void _saxIcon(ContentHandler contentHandler, String filename) throws SAXException
231    {
232        int index = filename.lastIndexOf('.');
233        String extension = filename.substring(index + 1);
234
235        XMLUtils.createElement(contentHandler, "icon", "plugins/explorer/icon-medium/" + extension + ".png");
236    }
237}