001/*
002 *  Copyright 2014 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.contentio.in;
017
018import java.io.ByteArrayOutputStream;
019import java.io.File;
020import java.io.IOException;
021import java.io.PrintStream;
022import java.util.HashMap;
023import java.util.Map;
024import java.util.Set;
025
026import javax.mail.MessagingException;
027
028import org.apache.avalon.framework.parameters.Parameters;
029import org.apache.avalon.framework.service.ServiceException;
030import org.apache.avalon.framework.service.ServiceManager;
031import org.apache.cocoon.acting.ServiceableAction;
032import org.apache.cocoon.environment.ObjectModelHelper;
033import org.apache.cocoon.environment.Redirector;
034import org.apache.cocoon.environment.Request;
035import org.apache.cocoon.environment.SourceResolver;
036import org.apache.cocoon.servlet.multipart.Part;
037import org.apache.cocoon.servlet.multipart.PartOnDisk;
038import org.apache.cocoon.servlet.multipart.RejectedPart;
039import org.apache.commons.io.IOUtils;
040import org.apache.commons.lang.StringUtils;
041import org.apache.excalibur.source.Source;
042
043import org.ametys.plugins.contentio.ContentImportException;
044import org.ametys.plugins.contentio.ContentImportManager;
045import org.ametys.plugins.contentio.ContentImportManager.ImportResult;
046import org.ametys.runtime.config.Config;
047import org.ametys.runtime.i18n.I18nizableText;
048import org.ametys.core.util.I18nUtils;
049import org.ametys.core.util.mail.SendMailHelper;
050
051/**
052 * Import contents from an uploaded file.
053 */
054public class ImportFileAction extends ServiceableAction
055{
056    
057    /** The content import manager. */
058    protected ContentImportManager _importManager;
059    
060    /** The source resolver. */
061    protected org.apache.excalibur.source.SourceResolver _sourceResolver;
062    
063    /** The i18n utils. */
064    protected I18nUtils _i18nUtils;
065    
066    @Override
067    public void service(ServiceManager serviceManager) throws ServiceException
068    {
069        super.service(serviceManager);
070        _importManager = (ContentImportManager) serviceManager.lookup(ContentImportManager.ROLE);
071        _sourceResolver = (org.apache.excalibur.source.SourceResolver) serviceManager.lookup(org.apache.excalibur.source.SourceResolver.ROLE);
072        _i18nUtils = (I18nUtils) serviceManager.lookup(I18nUtils.ROLE);
073    }
074    
075    @Override
076    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
077    {
078        Request request = ObjectModelHelper.getRequest(objectModel);
079        
080        boolean sendMail = parameters.getParameterAsBoolean("send-mail", false);
081        
082        boolean success = false;
083        
084        Map<String, String> result = new HashMap<>();
085        
086        ImportResult importResult = null;
087        
088        Part part = (Part) request.get("file");
089        if (part instanceof RejectedPart || part == null)
090        {
091            result.put("error", "rejected");
092        }
093        else
094        {
095            PartOnDisk uploadedFilePart = (PartOnDisk) part;
096            File uploadedFile = uploadedFilePart.getFile();
097            
098            try
099            {
100                importResult = _importManager.importContents(uploadedFile);
101                
102                if (!importResult.isImporterFound())
103                {
104                    result.put("error", "no-importer");
105                }
106                else
107                {
108                    Set<String> contentIds = importResult.getImportedContentIds();
109                    success = true;
110                    
111                    result.put("importedCount", Integer.toString(contentIds.size()));
112                    result.put("importedIds", StringUtils.join(contentIds, '|'));
113                }
114            }
115            catch (ContentImportException e)
116            {
117                ByteArrayOutputStream os = new ByteArrayOutputStream();
118                e.printStackTrace(new PrintStream(os));
119                getLogger().error("Exception importing contents from file: " + uploadedFile.getName(), e);
120                result.put("message", os.toString());
121            }
122        }
123        
124        result.put("success", String.valueOf(success));
125        
126        if (sendMail)
127        {
128            sendMail(success, importResult);
129        }
130        
131        return result;
132    }
133    
134    /**
135     * Send an import report as e-mail.
136     * @param success true if the import was successful, false otherwise.
137     * @param importResult the import result.
138     */
139    protected void sendMail(boolean success, ImportResult importResult)
140    {
141        try
142        {
143            String mailFrom = Config.getInstance().getValueAsString("smtp.mail.from");
144            String sysadminMail = Config.getInstance().getValueAsString("smtp.mail.sysadminto");
145            String baseUrl = StringUtils.stripEnd(StringUtils.removeEndIgnoreCase(Config.getInstance().getValueAsString("cms.url"), "index.html"), "/");
146            
147            Map<String, Object> mailParams = new HashMap<>();
148            
149            if (success)
150            {
151                mailParams.put("success", true);
152                mailParams.put("baseUrl", baseUrl);
153                mailParams.put("contentIds", importResult.getImportedContentIds());
154            }
155            else
156            {
157                mailParams.put("success", false);
158                if (importResult != null && !importResult.isImporterFound())
159                {
160                    mailParams.put("error", "no-importer");
161                }
162            }
163            
164            Source bodySource = _sourceResolver.resolveURI("cocoon://_plugins/contentio/mail/body", null, mailParams);
165            String body = IOUtils.toString(bodySource.getInputStream());
166            
167            I18nizableText i18nSubject = new I18nizableText("plugin.contentio", "PLUGINS_CONTENTIO_IMPORTFILE_MAIL_SUBJECT");
168            String subject = _i18nUtils.translate(i18nSubject);
169            
170            if (StringUtils.isNotBlank(sysadminMail))
171            {
172                SendMailHelper.sendMail(subject, null, body, sysadminMail, mailFrom);
173            }
174        }
175        catch (IOException e)
176        {
177            getLogger().warn("Error sending the import report e-mail.", e);
178        }
179        catch (MessagingException e)
180        {
181            getLogger().warn("Error sending the import report e-mail.", e);
182        }
183    }
184    
185}