001/*
002 * (C) Copyright 2006-2018 Nuxeo (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 *     Nuxeo - initial API and implementation
018 */
019
020package org.nuxeo.ecm.platform.mail.utils;
021
022import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.CORE_SESSION_KEY;
023import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.EMAILS_LIMIT_PROPERTY_NAME;
024import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.EMAIL_PROPERTY_NAME;
025import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.HOST_PROPERTY_NAME;
026import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.IMAP;
027import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.IMAPS;
028import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.LEAVE_ON_SERVER_KEY;
029import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.MIMETYPE_SERVICE_KEY;
030import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PARENT_PATH_KEY;
031import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PASSWORD_PROPERTY_NAME;
032import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.POP3S;
033import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PORT_PROPERTY_NAME;
034import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PROTOCOL_TYPE_KEY;
035import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.PROTOCOL_TYPE_PROPERTY_NAME;
036import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SOCKET_FACTORY_FALLBACK_PROPERTY_NAME;
037import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SOCKET_FACTORY_PORT_PROPERTY_NAME;
038import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.SSL_PROTOCOLS_PROPERTY_NAME;
039import static org.nuxeo.ecm.platform.mail.utils.MailCoreConstants.STARTTLS_ENABLE_PROPERTY_NAME;
040
041import java.util.ArrayList;
042import java.util.List;
043import java.util.Properties;
044import java.util.concurrent.CopyOnWriteArrayList;
045
046import javax.mail.FetchProfile;
047import javax.mail.Flags;
048import javax.mail.Flags.Flag;
049import javax.mail.Folder;
050import javax.mail.Message;
051import javax.mail.MessagingException;
052import javax.mail.Session;
053import javax.mail.Store;
054
055import org.apache.commons.lang3.StringUtils;
056import org.apache.commons.logging.Log;
057import org.apache.commons.logging.LogFactory;
058import org.nuxeo.ecm.core.api.CoreSession;
059import org.nuxeo.ecm.core.api.DocumentModel;
060import org.nuxeo.ecm.platform.mail.action.ExecutionContext;
061import org.nuxeo.ecm.platform.mail.action.MessageActionPipe;
062import org.nuxeo.ecm.platform.mail.action.Visitor;
063import org.nuxeo.ecm.platform.mail.listener.MailEventListener;
064import org.nuxeo.ecm.platform.mail.service.MailService;
065import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;
066import org.nuxeo.runtime.api.Framework;
067
068import com.sun.mail.imap.IMAPFolder;
069
070/**
071 * Helper for Mail Core.
072 *
073 * @author Catalin Baican
074 */
075public final class MailCoreHelper {
076
077    private static final Log log = LogFactory.getLog(MailEventListener.class);
078
079    public static final String PIPE_NAME = "nxmail";
080
081    public static final String INBOX = "INBOX";
082
083    public static final String DELETED_LIFECYCLE_STATE = "deleted";
084
085    public static final long EMAILS_LIMIT_DEFAULT = 100;
086
087    private static MailService mailService;
088
089    private static MimetypeRegistry mimeService;
090
091    public static final String IMAP_DEBUG = "org.nuxeo.mail.imap.debug";
092
093    protected static final CopyOnWriteArrayList<String> processingMailBoxes = new CopyOnWriteArrayList<>();
094
095    private MailCoreHelper() {
096    }
097
098    private static MailService getMailService() {
099        if (mailService == null) {
100            mailService = Framework.getService(MailService.class);
101        }
102        return mailService;
103    }
104
105    private static MimetypeRegistry getMimeService() {
106        if (mimeService == null) {
107            mimeService = Framework.getService(MimetypeRegistry.class);
108        }
109        return mimeService;
110    }
111
112    /**
113     * Creates MailMessage documents for every unread mail found in the INBOX. The parameters needed to connect to the
114     * email INBOX are retrieved from the MailFolder document passed as a parameter.
115     */
116    public static void checkMail(DocumentModel currentMailFolder, CoreSession coreSession) throws MessagingException {
117
118        if (processingMailBoxes.addIfAbsent(currentMailFolder.getId())) {
119            try {
120                doCheckMail(currentMailFolder, coreSession);
121            } finally {
122                processingMailBoxes.remove(currentMailFolder.getId());
123            }
124        } else {
125            log.info("Mailbox " + currentMailFolder.getPathAsString() + " is already being processed");
126        }
127    }
128
129    protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
130            throws MessagingException {
131        String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
132        String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
133        if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
134            mailService = getMailService();
135
136            MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);
137
138            Visitor visitor = new Visitor(pipe);
139            Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());
140
141            // initialize context
142            ExecutionContext initialExecutionContext = new ExecutionContext();
143
144            initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());
145
146            initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());
147
148            initialExecutionContext.put(CORE_SESSION_KEY, coreSession);
149
150            initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
151                                                                            // schema
152
153            Folder rootFolder = null;
154            Store store = null;
155            try {
156                String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
157                initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
158                // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));
159
160                String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
161                String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
162                Boolean socketFactoryFallback = (Boolean) currentMailFolder.getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
163                String socketFactoryPort = (String) currentMailFolder.getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
164                Boolean starttlsEnable = (Boolean) currentMailFolder.getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
165                String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
166                Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
167                long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();
168
169                String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");
170
171                Properties properties = new Properties();
172                properties.put("mail.store.protocol", protocolType);
173                // properties.put("mail.host", host);
174                // Is IMAP connection
175                if (IMAP.equals(protocolType)) {
176                    properties.put("mail.imap.host", host);
177                    properties.put("mail.imap.port", port);
178                    properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
179                    properties.put("mail.imap.debug", imapDebug);
180                    properties.put("mail.imap.partialfetch", "false");
181                } else if (IMAPS.equals(protocolType)) {
182                    properties.put("mail.imaps.host", host);
183                    properties.put("mail.imaps.port", port);
184                    properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
185                    properties.put("mail.imaps.ssl.protocols", sslProtocols);
186                    properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
187                    properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
188                    properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
189                    properties.put("mail.imap.partialfetch", "false");
190                    properties.put("mail.imaps.partialfetch", "false");
191                } else if (POP3S.equals(protocolType)) {
192                    properties.put("mail.pop3s.host", host);
193                    properties.put("mail.pop3s.port", port);
194                    properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
195                    properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
196                    properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
197                    properties.put("mail.pop3s.ssl.protocols", sslProtocols);
198                } else {
199                    // Is POP3 connection
200                    properties.put("mail.pop3.host", host);
201                    properties.put("mail.pop3.port", port);
202                }
203
204                properties.put("user", email);
205                properties.put("password", password);
206
207                Session session = Session.getInstance(properties);
208
209                store = session.getStore();
210                store.connect(email, password);
211
212                String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
213                rootFolder = store.getFolder(folderName);
214
215                // need RW access to update message flags
216                rootFolder.open(Folder.READ_WRITE);
217
218                Message[] allMessages = rootFolder.getMessages();
219                // VDU
220                log.debug("nbr of messages in folder:" + allMessages.length);
221
222                FetchProfile fetchProfile = new FetchProfile();
223                fetchProfile.add(FetchProfile.Item.FLAGS);
224                fetchProfile.add(FetchProfile.Item.ENVELOPE);
225                fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
226                fetchProfile.add("Message-ID");
227                fetchProfile.add("Content-Transfer-Encoding");
228
229                rootFolder.fetch(allMessages, fetchProfile);
230
231                if (rootFolder instanceof IMAPFolder) {
232                    // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
233                }
234
235                List<Message> unreadMessagesList = new ArrayList<>();
236                for (Message message : allMessages) {
237                    Flags flags = message.getFlags();
238                    int unreadMessagesListSize = unreadMessagesList.size();
239                    if (flags != null && !flags.contains(Flag.SEEN) && unreadMessagesListSize < emailsLimitLongValue) {
240                        unreadMessagesList.add(message);
241                        if (unreadMessagesListSize == emailsLimitLongValue - 1) {
242                            break;
243                        }
244                    }
245                }
246
247                Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);
248
249                // perform email import
250                visitor.visit(unreadMessagesArray, initialExecutionContext);
251
252                // perform flag update globally
253                Flags flags = new Flags();
254                flags.add(Flag.SEEN);
255
256                boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
257                if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
258                    flags.add(Flag.SEEN);
259                } else {
260                    flags.add(Flag.DELETED);
261                }
262                rootFolder.setFlags(unreadMessagesArray, flags, true);
263
264            } finally {
265                if (rootFolder != null && rootFolder.isOpen()) {
266                    rootFolder.close(true);
267                }
268                if (store != null) {
269                    store.close();
270                }
271            }
272        }
273    }
274
275}