1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.messageboards.messaging;
16  
17  import com.liferay.portal.NoSuchUserException;
18  import com.liferay.portal.kernel.json.JSONFactoryUtil;
19  import com.liferay.portal.kernel.log.Log;
20  import com.liferay.portal.kernel.log.LogFactoryUtil;
21  import com.liferay.portal.kernel.mail.Account;
22  import com.liferay.portal.kernel.messaging.MessageListener;
23  import com.liferay.portal.kernel.util.StringPool;
24  import com.liferay.portal.model.User;
25  import com.liferay.portal.security.permission.PermissionCheckerUtil;
26  import com.liferay.portal.service.ServiceContext;
27  import com.liferay.portal.service.UserLocalServiceUtil;
28  import com.liferay.portal.util.PortalUtil;
29  import com.liferay.portal.util.PortletKeys;
30  import com.liferay.portlet.messageboards.NoSuchMessageException;
31  import com.liferay.portlet.messageboards.model.MBMessage;
32  import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
33  import com.liferay.portlet.messageboards.service.MBMessageServiceUtil;
34  import com.liferay.portlet.messageboards.util.MBMailMessage;
35  import com.liferay.portlet.messageboards.util.MBUtil;
36  import com.liferay.portlet.messageboards.util.MailingListThreadLocal;
37  import com.liferay.util.mail.MailEngine;
38  
39  import javax.mail.Address;
40  import javax.mail.Flags;
41  import javax.mail.Folder;
42  import javax.mail.Message;
43  import javax.mail.MessagingException;
44  import javax.mail.Session;
45  import javax.mail.Store;
46  import javax.mail.URLName;
47  import javax.mail.internet.InternetAddress;
48  
49  /**
50   * <a href="MailingListMessageListener.java.html"><b><i>View Source</i></b></a>
51   *
52   * @author Thiago Moreira
53   */
54  public class MailingListMessageListener implements MessageListener {
55  
56      public void receive(com.liferay.portal.kernel.messaging.Message message) {
57          MailingListRequest mailingListRequest =
58              (MailingListRequest)JSONFactoryUtil.deserialize(
59                  (String)message.getPayload());
60  
61          Folder folder = null;
62  
63          Message[] messages = null;
64  
65          try {
66              folder = getFolder(mailingListRequest);
67  
68              messages = folder.getMessages();
69  
70              processMessages(mailingListRequest, messages);
71          }
72          catch (Exception e) {
73              _log.error(e, e);
74          }
75          finally {
76              if ((folder != null) && folder.isOpen()) {
77                  try {
78                      folder.setFlags(
79                          messages, new Flags(Flags.Flag.DELETED), true);
80                  }
81                  catch (Exception e) {
82                  }
83  
84                  try {
85                      folder.close(true);
86                  }
87                  catch (Exception e) {
88                  }
89              }
90          }
91      }
92  
93      protected Folder getFolder(MailingListRequest mailingListRequest)
94          throws Exception {
95  
96          String protocol = mailingListRequest.getInProtocol();
97          String host = mailingListRequest.getInServerName();
98          int port = mailingListRequest.getInServerPort();
99          String user = mailingListRequest.getInUserName();
100         String password = mailingListRequest.getInPassword();
101 
102         Account account = Account.getInstance(protocol, port);
103 
104         account.setHost(host);
105         account.setPort(port);
106         account.setUser(user);
107         account.setPassword(password);
108 
109         Session session = MailEngine.getSession(account);
110 
111         URLName urlName = new URLName(
112             protocol, host, port, StringPool.BLANK, user, password);
113 
114         Store store = session.getStore(urlName);
115 
116         store.connect();
117 
118         Folder defaultFolder = store.getDefaultFolder();
119 
120         Folder[] folders = defaultFolder.list();
121 
122         if ((folders != null) && (folders.length == 0)) {
123             throw new MessagingException("Inbox not found");
124         }
125 
126         Folder folder = folders[0];
127 
128         folder.open(Folder.READ_WRITE);
129 
130         return folder;
131     }
132 
133     protected void processMessage(
134             MailingListRequest mailingListRequest, Message mailMessage)
135         throws Exception {
136 
137         if (MBUtil.hasMailIdHeader(mailMessage)) {
138             return;
139         }
140 
141         String from = null;
142 
143         Address[] addresses = mailMessage.getFrom();
144 
145         if ((addresses != null) && (addresses.length > 0)) {
146             Address address = addresses[0];
147 
148             if (address instanceof InternetAddress) {
149                 from = ((InternetAddress)address).getAddress();
150             }
151             else {
152                 from = address.toString();
153             }
154         }
155 
156         long companyId = mailingListRequest.getCompanyId();
157         long groupId = mailingListRequest.getGroupId();
158         long categoryId = mailingListRequest.getCategoryId();
159 
160         if (_log.isDebugEnabled()) {
161             _log.debug("Category id " + categoryId);
162         }
163 
164         boolean anonymous = false;
165 
166         User user = UserLocalServiceUtil.getUserById(
167             companyId, mailingListRequest.getUserId());
168 
169         try {
170             user = UserLocalServiceUtil.getUserByEmailAddress(companyId, from);
171         }
172         catch (NoSuchUserException nsue) {
173             anonymous = true;
174         }
175 
176         long parentMessageId = MBUtil.getParentMessageId(mailMessage);
177 
178         if (_log.isDebugEnabled()) {
179             _log.debug("Parent message id " + parentMessageId);
180         }
181 
182         MBMessage parentMessage = null;
183 
184         try {
185             if (parentMessageId > 0) {
186                 parentMessage = MBMessageLocalServiceUtil.getMessage(
187                     parentMessageId);
188             }
189         }
190         catch (NoSuchMessageException nsme) {
191         }
192 
193         if (_log.isDebugEnabled()) {
194             _log.debug("Parent message " + parentMessage);
195         }
196 
197         MBMailMessage collector = new MBMailMessage();
198 
199         MBUtil.collectPartContent(mailMessage, collector);
200 
201         PermissionCheckerUtil.setThreadValues(user);
202 
203         MailingListThreadLocal.setSourceMailingList(true);
204 
205         String subject = MBUtil.getSubjectWithoutMessageId(mailMessage);
206 
207         ServiceContext serviceContext = new ServiceContext();
208 
209         serviceContext.setAddCommunityPermissions(true);
210         serviceContext.setAddGuestPermissions(true);
211         serviceContext.setLayoutFullURL(
212             PortalUtil.getLayoutFullURL(groupId, PortletKeys.MESSAGE_BOARDS));
213         serviceContext.setScopeGroupId(groupId);
214 
215         if (parentMessage == null) {
216             MBMessageServiceUtil.addMessage(
217                 categoryId, subject, collector.getBody(), collector.getFiles(),
218                 anonymous, 0.0, serviceContext);
219         }
220         else {
221             MBMessageServiceUtil.addMessage(
222                 categoryId, parentMessage.getThreadId(),
223                 parentMessage.getMessageId(), subject, collector.getBody(),
224                 collector.getFiles(), anonymous, 0.0, serviceContext);
225         }
226     }
227 
228     protected void processMessages(
229             MailingListRequest mailingListRequest, Message[] messages)
230         throws Exception {
231 
232         for (Message message : messages) {
233             try {
234                 processMessage(mailingListRequest, message);
235             }
236             finally {
237                 PermissionCheckerUtil.setThreadValues(null);
238             }
239         }
240     }
241 
242     private static Log _log = LogFactoryUtil.getLog(
243         MailingListMessageListener.class);
244 
245 }