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.Company;
33  import com.liferay.portal.model.User;
34  import com.liferay.portal.security.permission.PermissionCheckerUtil;
35  import com.liferay.portal.service.CompanyLocalServiceUtil;
36  import com.liferay.portal.service.ServiceContext;
37  import com.liferay.portal.service.UserLocalServiceUtil;
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   */
63  public class MailingListMessageListener implements MessageListener {
64  
65      public void receive(com.liferay.portal.kernel.messaging.Message message) {
66          MailingListRequest mailingListRequest =
67              (MailingListRequest)JSONFactoryUtil.deserialize(
68                  (String)message.getPayload());
69  
70          Folder folder = null;
71  
72          Message[] messages = null;
73  
74          try {
75              folder = getFolder(mailingListRequest);
76  
77              messages = folder.getMessages();
78  
79              processMessages(mailingListRequest, messages);
80          }
81          catch (Exception e) {
82              _log.error(e, e);
83          }
84          finally {
85              if ((folder != null) && folder.isOpen()) {
86                  try {
87                      folder.setFlags(
88                          messages, new Flags(Flags.Flag.DELETED), true);
89                  }
90                  catch (Exception e) {
91                  }
92  
93                  try {
94                      folder.close(true);
95                  }
96                  catch (Exception e) {
97                  }
98              }
99          }
100     }
101 
102     protected Folder getFolder(MailingListRequest mailingListRequest)
103         throws Exception {
104 
105         String protocol = mailingListRequest.getInProtocol();
106         String host = mailingListRequest.getInServerName();
107         int port = mailingListRequest.getInServerPort();
108         String user = mailingListRequest.getInUserName();
109         String password = mailingListRequest.getInPassword();
110 
111         Account account = Account.getInstance(protocol, port);
112 
113         account.setHost(host);
114         account.setPort(port);
115         account.setUser(user);
116         account.setPassword(password);
117 
118         Session session = MailEngine.getSession(account);
119 
120         URLName urlName = new URLName(
121             protocol, host, port, StringPool.BLANK, user, password);
122 
123         Store store = session.getStore(urlName);
124 
125         store.connect();
126 
127         Folder defaultFolder = store.getDefaultFolder();
128 
129         Folder[] folders = defaultFolder.list();
130 
131         if ((folders != null) && (folders.length == 0)) {
132             throw new MessagingException("Inbox not found");
133         }
134 
135         Folder folder = folders[0];
136 
137         folder.open(Folder.READ_WRITE);
138 
139         return folder;
140     }
141 
142     protected void processMessage(
143             MailingListRequest mailingListRequest, Message mailMessage)
144         throws Exception {
145 
146         if (MBUtil.hasMailIdHeader(mailMessage)) {
147             return;
148         }
149 
150         String from = null;
151 
152         Address[] addresses = mailMessage.getFrom();
153 
154         if ((addresses != null) && (addresses.length > 0)) {
155             Address address = addresses[0];
156 
157             if (address instanceof InternetAddress) {
158                 from = ((InternetAddress)address).getAddress();
159             }
160             else {
161                 from = address.toString();
162             }
163         }
164 
165         Company company = CompanyLocalServiceUtil.getCompany(
166             mailingListRequest.getCompanyId());
167 
168         long categoryId = mailingListRequest.getCategoryId();
169 
170         if (_log.isDebugEnabled()) {
171             _log.debug("Category id " + categoryId);
172         }
173 
174         boolean anonymous = false;
175 
176         User user = UserLocalServiceUtil.getUserById(
177             company.getCompanyId(), mailingListRequest.getUserId());
178 
179         try {
180             user = UserLocalServiceUtil.getUserByEmailAddress(
181                 company.getCompanyId(), from);
182         }
183         catch (NoSuchUserException nsue) {
184             anonymous = true;
185         }
186 
187         long parentMessageId = MBUtil.getParentMessageId(mailMessage);
188 
189         if (_log.isDebugEnabled()) {
190             _log.debug("Parent message id " + parentMessageId);
191         }
192 
193         MBMessage parentMessage = null;
194 
195         try {
196             if (parentMessageId > 0) {
197                 parentMessage = MBMessageLocalServiceUtil.getMessage(
198                     parentMessageId);
199             }
200         }
201         catch (NoSuchMessageException nsme) {
202         }
203 
204         if (_log.isDebugEnabled()) {
205             _log.debug("Parent message " + parentMessage);
206         }
207 
208         MBMailMessage collector = new MBMailMessage();
209 
210         MBUtil.collectPartContent(mailMessage, collector);
211 
212         PermissionCheckerUtil.setThreadValues(user);
213 
214         MailingListThreadLocal.setSourceMailingList(true);
215 
216         String subject = MBUtil.getSubjectWithoutMessageId(mailMessage);
217 
218         ServiceContext serviceContext = new ServiceContext();
219 
220         serviceContext.setAddCommunityPermissions(true);
221         serviceContext.setAddGuestPermissions(true);
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 }