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