1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.messageboards.messaging;
24  
25  import com.liferay.portal.NoSuchUserException;
26  import com.liferay.portal.kernel.json.JSONFactoryUtil;
27  import com.liferay.portal.kernel.log.Log;
28  import com.liferay.portal.kernel.log.LogFactoryUtil;
29  import com.liferay.portal.kernel.mail.Account;
30  import com.liferay.portal.kernel.messaging.MessageListener;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.model.User;
33  import com.liferay.portal.security.permission.PermissionCheckerUtil;
34  import com.liferay.portal.service.ServiceContext;
35  import com.liferay.portal.service.UserLocalServiceUtil;
36  import com.liferay.portal.util.PortalUtil;
37  import com.liferay.portal.util.PortletKeys;
38  import com.liferay.portlet.messageboards.NoSuchMessageException;
39  import com.liferay.portlet.messageboards.model.MBMessage;
40  import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
41  import com.liferay.portlet.messageboards.service.MBMessageServiceUtil;
42  import com.liferay.portlet.messageboards.util.MBMailMessage;
43  import com.liferay.portlet.messageboards.util.MBUtil;
44  import com.liferay.portlet.messageboards.util.MailingListThreadLocal;
45  import com.liferay.util.mail.MailEngine;
46  
47  import javax.mail.Address;
48  import javax.mail.Flags;
49  import javax.mail.Folder;
50  import javax.mail.Message;
51  import javax.mail.MessagingException;
52  import javax.mail.Session;
53  import javax.mail.Store;
54  import javax.mail.URLName;
55  import javax.mail.internet.InternetAddress;
56  
57  /**
58   * <a href="MailingListMessageListener.java.html"><b><i>View Source</i></b></a>
59   *
60   * @author Thiago Moreira
61   */
62  public class MailingListMessageListener implements MessageListener {
63  
64      public void receive(com.liferay.portal.kernel.messaging.Message message) {
65          MailingListRequest mailingListRequest =
66              (MailingListRequest)JSONFactoryUtil.deserialize(
67                  (String)message.getPayload());
68  
69          Folder folder = null;
70  
71          Message[] messages = null;
72  
73          try {
74              folder = getFolder(mailingListRequest);
75  
76              messages = folder.getMessages();
77  
78              processMessages(mailingListRequest, messages);
79          }
80          catch (Exception e) {
81              _log.error(e, e);
82          }
83          finally {
84              if ((folder != null) && folder.isOpen()) {
85                  try {
86                      folder.setFlags(
87                          messages, new Flags(Flags.Flag.DELETED), true);
88                  }
89                  catch (Exception e) {
90                  }
91  
92                  try {
93                      folder.close(true);
94                  }
95                  catch (Exception e) {
96                  }
97              }
98          }
99      }
100 
101     protected Folder getFolder(MailingListRequest mailingListRequest)
102         throws Exception {
103 
104         String protocol = mailingListRequest.getInProtocol();
105         String host = mailingListRequest.getInServerName();
106         int port = mailingListRequest.getInServerPort();
107         String user = mailingListRequest.getInUserName();
108         String password = mailingListRequest.getInPassword();
109 
110         Account account = Account.getInstance(protocol, port);
111 
112         account.setHost(host);
113         account.setPort(port);
114         account.setUser(user);
115         account.setPassword(password);
116 
117         Session session = MailEngine.getSession(account);
118 
119         URLName urlName = new URLName(
120             protocol, host, port, StringPool.BLANK, user, password);
121 
122         Store store = session.getStore(urlName);
123 
124         store.connect();
125 
126         Folder defaultFolder = store.getDefaultFolder();
127 
128         Folder[] folders = defaultFolder.list();
129 
130         if ((folders != null) && (folders.length == 0)) {
131             throw new MessagingException("Inbox not found");
132         }
133 
134         Folder folder = folders[0];
135 
136         folder.open(Folder.READ_WRITE);
137 
138         return folder;
139     }
140 
141     protected void processMessage(
142             MailingListRequest mailingListRequest, Message mailMessage)
143         throws Exception {
144 
145         if (MBUtil.hasMailIdHeader(mailMessage)) {
146             return;
147         }
148 
149         String from = null;
150 
151         Address[] addresses = mailMessage.getFrom();
152 
153         if ((addresses != null) && (addresses.length > 0)) {
154             Address address = addresses[0];
155 
156             if (address instanceof InternetAddress) {
157                 from = ((InternetAddress)address).getAddress();
158             }
159             else {
160                 from = address.toString();
161             }
162         }
163 
164         long companyId = mailingListRequest.getCompanyId();
165         long groupId = mailingListRequest.getGroupId();
166         long categoryId = mailingListRequest.getCategoryId();
167 
168         if (_log.isDebugEnabled()) {
169             _log.debug("Category id " + categoryId);
170         }
171 
172         boolean anonymous = false;
173 
174         User user = UserLocalServiceUtil.getUserById(
175             companyId, mailingListRequest.getUserId());
176 
177         try {
178             user = UserLocalServiceUtil.getUserByEmailAddress(companyId, from);
179         }
180         catch (NoSuchUserException nsue) {
181             anonymous = true;
182         }
183 
184         long parentMessageId = MBUtil.getParentMessageId(mailMessage);
185 
186         if (_log.isDebugEnabled()) {
187             _log.debug("Parent message id " + parentMessageId);
188         }
189 
190         MBMessage parentMessage = null;
191 
192         try {
193             if (parentMessageId > 0) {
194                 parentMessage = MBMessageLocalServiceUtil.getMessage(
195                     parentMessageId);
196             }
197         }
198         catch (NoSuchMessageException nsme) {
199         }
200 
201         if (_log.isDebugEnabled()) {
202             _log.debug("Parent message " + parentMessage);
203         }
204 
205         MBMailMessage collector = new MBMailMessage();
206 
207         MBUtil.collectPartContent(mailMessage, collector);
208 
209         PermissionCheckerUtil.setThreadValues(user);
210 
211         MailingListThreadLocal.setSourceMailingList(true);
212 
213         String subject = MBUtil.getSubjectWithoutMessageId(mailMessage);
214 
215         ServiceContext serviceContext = new ServiceContext();
216 
217         serviceContext.setAddCommunityPermissions(true);
218         serviceContext.setAddGuestPermissions(true);
219         serviceContext.setLayoutFullURL(
220             PortalUtil.getLayoutFullURL(groupId, PortletKeys.MESSAGE_BOARDS));
221         serviceContext.setScopeGroupId(groupId);
222 
223         if (parentMessage == null) {
224             MBMessageServiceUtil.addMessage(
225                 categoryId, subject, collector.getBody(), collector.getFiles(),
226                 anonymous, 0.0, serviceContext);
227         }
228         else {
229             MBMessageServiceUtil.addMessage(
230                 categoryId, parentMessage.getThreadId(),
231                 parentMessage.getMessageId(), subject, collector.getBody(),
232                 collector.getFiles(), anonymous, 0.0, serviceContext);
233         }
234     }
235 
236     protected void processMessages(
237             MailingListRequest mailingListRequest, Message[] messages)
238         throws Exception {
239 
240         for (Message message : messages) {
241             processMessage(mailingListRequest, message);
242         }
243     }
244 
245     private static Log _log =
246         LogFactoryUtil.getLog(MailingListMessageListener.class);
247 
248 }