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