001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others.
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 * Contributors:
017 *     Alexandre Russel
018 *
019 * $Id$
020 */
021
022package org.nuxeo.ecm.platform.mail.action;
023
024import java.io.IOException;
025import java.io.InputStream;
026import java.io.UnsupportedEncodingException;
027import java.util.ArrayList;
028import java.util.HashMap;
029import java.util.List;
030import java.util.Map;
031
032import javax.mail.Address;
033import javax.mail.Message;
034import javax.mail.MessagingException;
035import javax.mail.Part;
036import javax.mail.internet.MimeMessage;
037import javax.mail.internet.MimeMultipart;
038import javax.mail.internet.MimeUtility;
039
040import org.apache.commons.logging.Log;
041import org.apache.commons.logging.LogFactory;
042import org.nuxeo.ecm.core.api.Blob;
043import org.nuxeo.ecm.core.api.Blobs;
044
045/**
046 * Transforms the message using the transformer and puts it in the context under transformed.
047 *
048 * @author Alexandre Russel
049 */
050public class TransformMessageAction implements MessageAction {
051
052    private static final Log log = LogFactory.getLog(TransformMessageAction.class);
053
054    protected final Map<String, Map<String, Object>> schemas = new HashMap<>();
055
056    protected final Map<String, Object> mailSchema = new HashMap<>();
057
058    protected final Map<String, Object> dcSchema = new HashMap<>();
059
060    protected final Map<String, Object> filesSchema = new HashMap<>();
061
062    protected final List<Map<String, Object>> files = new ArrayList<>();
063
064    protected StringBuilder text = new StringBuilder();
065
066    private final HashMap<String, List<Part>> messageBodyParts = new HashMap<>();
067
068    public TransformMessageAction() {
069        messageBodyParts.put("text", new ArrayList<Part>());
070        messageBodyParts.put("html", new ArrayList<Part>());
071        schemas.put("mail", mailSchema);
072        schemas.put("dublincore", dcSchema);
073        filesSchema.put("files", files);
074        schemas.put("files", filesSchema);
075    }
076
077    @Override
078    public boolean execute(ExecutionContext context) throws MessagingException {
079        Message message = context.getMessage();
080        if (log.isDebugEnabled()) {
081            log.debug("Transforming message" + message.getSubject());
082        }
083        if (message.getFrom() != null && message.getFrom().length != 0) {
084            List<String> contributors = new ArrayList<>();
085            for (Address ad : message.getFrom()) {
086                contributors.add(safelyDecodeText(ad.toString()));
087            }
088            dcSchema.put("contributors", contributors);
089            dcSchema.put("creator", contributors.get(0));
090            dcSchema.put("created", message.getReceivedDate());
091        }
092        if (message.getAllRecipients() != null && message.getAllRecipients().length != 0) {
093            List<String> recipients = new ArrayList<>();
094            for (Address address : message.getAllRecipients()) {
095                recipients.add(safelyDecodeText(address.toString()));
096            }
097            mailSchema.put("recipients", recipients);
098        }
099        if (message instanceof MimeMessage) {
100            try {
101                processMimeMessage((MimeMessage) message);
102            } catch (IOException e) {
103                throw new MessagingException(e.getMessage(), e);
104            }
105        }
106        mailSchema.put("text", text.toString());
107        dcSchema.put("title", message.getSubject());
108        context.put("transformed", schemas);
109        return true;
110    }
111
112    private void processMimeMessage(MimeMessage message) throws MessagingException, IOException {
113        Object object = message.getContent();
114        if (object instanceof String) {
115            addToTextMessage(message.getContent().toString(), true);
116        } else if (object instanceof MimeMultipart) {
117            processMultipartMessage((MimeMultipart) object);
118            processSavedTextMessageBody();
119        }
120    }
121
122    private void processMultipartMessage(MimeMultipart parts) throws MessagingException, IOException {
123        log.debug("processing multipart message.");
124        for (int i = 0; i < parts.getCount(); i++) {
125            Part part = parts.getBodyPart(i);
126            if (part.getDataHandler().getContent() instanceof MimeMultipart) {
127                log.debug("** found embedded multipart message");
128                processMultipartMessage((MimeMultipart) part.getDataHandler().getContent());
129                continue;
130            }
131            log.debug("processing single part message: " + part.getClass());
132            processSingleMessagePart(part);
133        }
134    }
135
136    private void processSingleMessagePart(Part part) throws MessagingException, IOException {
137        String partContentType = part.getContentType();
138        String partFileName = getFileName(part);
139
140        if (partFileName != null) {
141            log.debug("Add named attachment: " + partFileName);
142            setFile(partFileName, part.getInputStream());
143            return;
144        }
145
146        if (!contentTypeIsReadableText(partContentType)) {
147            log.debug("Add unnamed binary attachment.");
148            setFile(null, part.getInputStream());
149            return;
150        }
151
152        if (contentTypeIsPlainText(partContentType)) {
153            log.debug("found plain text unnamed attachment [save for later processing]");
154            messageBodyParts.get("text").add(part);
155            return;
156        }
157
158        log.debug("found html unnamed attachment [save for later processing]");
159        messageBodyParts.get("html").add(part);
160    }
161
162    private void processSavedTextMessageBody() throws MessagingException, IOException {
163        if (messageBodyParts.get("text").isEmpty()) {
164            log.debug("entering case 2: no plain text found -> html is the body of the message.");
165            addPartsToTextMessage(messageBodyParts.get("html"));
166        } else {
167            log.debug("entering case 1: text is saved as message body and html as attachment.");
168            addPartsToTextMessage(messageBodyParts.get("text"));
169            addPartsAsAttachements(messageBodyParts.get("html"));
170        }
171    }
172
173    private void addPartsToTextMessage(List<Part> someMessageParts) throws MessagingException, IOException {
174        for (Part part : someMessageParts) {
175            addToTextMessage(part.getContent().toString(), contentTypeIsPlainText(part.getContentType()));
176        }
177    }
178
179    private void addPartsAsAttachements(List<Part> someMessageParts) throws MessagingException, IOException {
180        for (Part part : someMessageParts) {
181            setFile(getFileName(part), part.getInputStream());
182        }
183    }
184
185    private static boolean contentTypeIsReadableText(String contentType) {
186        boolean isText = contentTypeIsPlainText(contentType);
187        boolean isHTML = contentTypeIsHtml(contentType);
188        return isText || isHTML;
189    }
190
191    private static boolean contentTypeIsHtml(String contentType) {
192        contentType = contentType.trim().toLowerCase();
193        return contentType.startsWith("text/html");
194    }
195
196    private static boolean contentTypeIsPlainText(String contentType) {
197        contentType = contentType.trim().toLowerCase();
198        return contentType.startsWith("text/plain");
199    }
200
201    /**
202     * "javax.mail.internet.MimeBodyPart" is decoding the file name (with special characters) if it has the
203     * "mail.mime.decodefilename" sysstem property set but the "com.sun.mail.imap.IMAPBodyPart" subclass of MimeBodyPart
204     * is overriding getFileName() and never deal with encoded file names. the filename is decoded with the utility
205     * function: MimeUtility.decodeText(filename); so we force here a filename decode. MimeUtility.decodeText is doing
206     * nothing if the text is not encoded
207     */
208    private static String getFileName(Part mailPart) throws MessagingException {
209        String sysPropertyVal = System.getProperty("mail.mime.decodefilename");
210        boolean decodeFileName = sysPropertyVal != null && !sysPropertyVal.equalsIgnoreCase("false");
211
212        String encodedFilename = mailPart.getFileName();
213
214        if (!decodeFileName || encodedFilename == null) {
215            return encodedFilename;
216        }
217
218        try {
219            return MimeUtility.decodeText(encodedFilename);
220        } catch (UnsupportedEncodingException ex) {
221            throw new MessagingException("Can't decode attachment filename.", ex);
222        }
223    }
224
225    private static String safelyDecodeText(String textToDecode) {
226        try {
227            return MimeUtility.decodeText(textToDecode);
228        } catch (UnsupportedEncodingException ex) {
229            log.error("Can't decode text. Use undecoded!", ex);
230            return textToDecode;
231        }
232    }
233
234    private void setFile(String fileName, InputStream inputStream) throws IOException {
235        log.debug("* adding attachment: " + fileName);
236        Map<String, Object> map = new HashMap<>();
237        Blob fileBlob = Blobs.createBlob(inputStream);
238        fileBlob.setFilename(fileName);
239        map.put("file", fileBlob);
240        files.add(map);
241    }
242
243    private void addToTextMessage(String message, boolean isPlainText) {
244        log.debug("* adding text to message body: " + message);
245        // if(isPlainText){
246        // message = "<pre>" + message + "</pre>";
247        // }
248        text.append(message);
249    }
250
251    @Override
252    public void reset(ExecutionContext context) {
253        mailSchema.clear();
254        dcSchema.clear();
255        files.clear();
256        text = new StringBuilder();
257
258        messageBodyParts.get("text").clear();
259        messageBodyParts.get("html").clear();
260    }
261
262}