001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.messageboards.messaging;
016    
017    import com.liferay.portal.NoSuchUserException;
018    import com.liferay.portal.kernel.log.Log;
019    import com.liferay.portal.kernel.log.LogFactoryUtil;
020    import com.liferay.portal.kernel.mail.Account;
021    import com.liferay.portal.kernel.messaging.MessageListener;
022    import com.liferay.portal.kernel.util.StringPool;
023    import com.liferay.portal.model.User;
024    import com.liferay.portal.security.permission.PermissionCheckerUtil;
025    import com.liferay.portal.service.ServiceContext;
026    import com.liferay.portal.service.UserLocalServiceUtil;
027    import com.liferay.portal.util.PortalUtil;
028    import com.liferay.portal.util.PortletKeys;
029    import com.liferay.portlet.messageboards.NoSuchMessageException;
030    import com.liferay.portlet.messageboards.model.MBMessage;
031    import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
032    import com.liferay.portlet.messageboards.service.MBMessageServiceUtil;
033    import com.liferay.portlet.messageboards.util.MBMailMessage;
034    import com.liferay.portlet.messageboards.util.MBUtil;
035    import com.liferay.portlet.messageboards.util.MailingListThreadLocal;
036    import com.liferay.util.mail.MailEngine;
037    
038    import javax.mail.Address;
039    import javax.mail.Flags;
040    import javax.mail.Folder;
041    import javax.mail.Message;
042    import javax.mail.MessagingException;
043    import javax.mail.Session;
044    import javax.mail.Store;
045    import javax.mail.URLName;
046    import javax.mail.internet.InternetAddress;
047    
048    /**
049     * @author Thiago Moreira
050     */
051    public class MailingListMessageListener implements MessageListener {
052    
053            public void receive(com.liferay.portal.kernel.messaging.Message message) {
054                    MailingListRequest mailingListRequest =
055                            (MailingListRequest)message.getPayload();
056    
057                    Store store = null;
058    
059                    Folder folder = null;
060    
061                    Message[] messages = null;
062    
063                    try {
064                            store = getStore(mailingListRequest);
065    
066                            store.connect();
067    
068                            folder = getFolder(store);
069    
070                            messages = folder.getMessages();
071    
072                            processMessages(mailingListRequest, messages);
073                    }
074                    catch (Exception e) {
075                            _log.error(e, e);
076                    }
077                    finally {
078                            if ((folder != null) && folder.isOpen()) {
079                                    try {
080                                            folder.setFlags(
081                                                    messages, new Flags(Flags.Flag.DELETED), true);
082                                    }
083                                    catch (Exception e) {
084                                    }
085    
086                                    try {
087                                            folder.close(true);
088                                    }
089                                    catch (Exception e) {
090                                    }
091                            }
092    
093                            if ((store != null) && store.isConnected()) {
094                                    try {
095                                            store.close();
096                                    }
097                                    catch (MessagingException e) {
098                                    }
099                            }
100                    }
101            }
102    
103            protected Folder getFolder(Store store) throws Exception {
104                    Folder defaultFolder = store.getDefaultFolder();
105    
106                    Folder[] folders = defaultFolder.list();
107    
108                    if ((folders != null) && (folders.length == 0)) {
109                            throw new MessagingException("Inbox not found");
110                    }
111    
112                    Folder folder = folders[0];
113    
114                    folder.open(Folder.READ_WRITE);
115    
116                    return folder;
117            }
118    
119            protected Store getStore(MailingListRequest mailingListRequest)
120                    throws Exception {
121    
122                    String protocol = mailingListRequest.getInProtocol();
123                    String host = mailingListRequest.getInServerName();
124                    int port = mailingListRequest.getInServerPort();
125                    String user = mailingListRequest.getInUserName();
126                    String password = mailingListRequest.getInPassword();
127    
128                    Account account = Account.getInstance(protocol, port);
129    
130                    account.setHost(host);
131                    account.setPort(port);
132                    account.setUser(user);
133                    account.setPassword(password);
134    
135                    Session session = MailEngine.getSession(account);
136    
137                    URLName urlName = new URLName(
138                            protocol, host, port, StringPool.BLANK, user, password);
139    
140                    Store store = session.getStore(urlName);
141    
142                    return store;
143            }
144    
145            protected void processMessage(
146                            MailingListRequest mailingListRequest, Message mailMessage)
147                    throws Exception {
148    
149                    if (MBUtil.hasMailIdHeader(mailMessage)) {
150                            return;
151                    }
152    
153                    String from = null;
154    
155                    Address[] addresses = mailMessage.getFrom();
156    
157                    if ((addresses != null) && (addresses.length > 0)) {
158                            Address address = addresses[0];
159    
160                            if (address instanceof InternetAddress) {
161                                    from = ((InternetAddress)address).getAddress();
162                            }
163                            else {
164                                    from = address.toString();
165                            }
166                    }
167    
168                    long companyId = mailingListRequest.getCompanyId();
169                    long groupId = mailingListRequest.getGroupId();
170                    long categoryId = mailingListRequest.getCategoryId();
171    
172                    if (_log.isDebugEnabled()) {
173                            _log.debug("Category id " + categoryId);
174                    }
175    
176                    boolean anonymous = false;
177    
178                    User user = UserLocalServiceUtil.getUserById(
179                            companyId, mailingListRequest.getUserId());
180    
181                    try {
182                            user = UserLocalServiceUtil.getUserByEmailAddress(companyId, from);
183                    }
184                    catch (NoSuchUserException nsue) {
185                            anonymous = true;
186                    }
187    
188                    long parentMessageId = MBUtil.getParentMessageId(mailMessage);
189    
190                    if (_log.isDebugEnabled()) {
191                            _log.debug("Parent message id " + parentMessageId);
192                    }
193    
194                    MBMessage parentMessage = null;
195    
196                    try {
197                            if (parentMessageId > 0) {
198                                    parentMessage = MBMessageLocalServiceUtil.getMessage(
199                                            parentMessageId);
200                            }
201                    }
202                    catch (NoSuchMessageException nsme) {
203                    }
204    
205                    if (_log.isDebugEnabled()) {
206                            _log.debug("Parent message " + parentMessage);
207                    }
208    
209                    MBMailMessage collector = new MBMailMessage();
210    
211                    MBUtil.collectPartContent(mailMessage, collector);
212    
213                    PermissionCheckerUtil.setThreadValues(user);
214    
215                    MailingListThreadLocal.setSourceMailingList(true);
216    
217                    String subject = MBUtil.getSubjectWithoutMessageId(mailMessage);
218    
219                    ServiceContext serviceContext = new ServiceContext();
220    
221                    serviceContext.setAddCommunityPermissions(true);
222                    serviceContext.setAddGuestPermissions(true);
223                    serviceContext.setLayoutFullURL(
224                            PortalUtil.getLayoutFullURL(groupId, PortletKeys.MESSAGE_BOARDS));
225                    serviceContext.setScopeGroupId(groupId);
226    
227                    if (parentMessage == null) {
228                            MBMessageServiceUtil.addMessage(
229                                    groupId, categoryId, subject, collector.getBody(),
230                                    collector.getFiles(), anonymous, 0.0, true, serviceContext);
231                    }
232                    else {
233                            MBMessageServiceUtil.addMessage(
234                                    groupId, categoryId, parentMessage.getThreadId(),
235                                    parentMessage.getMessageId(), subject, collector.getBody(),
236                                    collector.getFiles(), anonymous, 0.0, true, serviceContext);
237                    }
238            }
239    
240            protected void processMessages(
241                            MailingListRequest mailingListRequest, Message[] messages)
242                    throws Exception {
243    
244                    for (Message message : messages) {
245                            try {
246                                    processMessage(mailingListRequest, message);
247                            }
248                            finally {
249                                    PermissionCheckerUtil.setThreadValues(null);
250                            }
251                    }
252            }
253    
254            private static Log _log = LogFactoryUtil.getLog(
255                    MailingListMessageListener.class);
256    
257    }