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  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         Company company = CompanyLocalServiceUtil.getCompany(
165             mailingListRequest.getCompanyId());
166 
167         long categoryId = mailingListRequest.getCategoryId();
168 
169         if (_log.isDebugEnabled()) {
170             _log.debug("Category id " + categoryId);
171         }
172 
173         boolean anonymous = false;
174 
175         User user = UserLocalServiceUtil.getUserById(
176             company.getCompanyId(), mailingListRequest.getUserId());
177 
178         try {
179             user = UserLocalServiceUtil.getUserByEmailAddress(
180                 company.getCompanyId(), from);
181         }
182         catch (NoSuchUserException nsue) {
183             anonymous = true;
184         }
185 
186         long parentMessageId = MBUtil.getParentMessageId(mailMessage);
187 
188         if (_log.isDebugEnabled()) {
189             _log.debug("Parent message id " + parentMessageId);
190         }
191 
192         MBMessage parentMessage = null;
193 
194         try {
195             if (parentMessageId > 0) {
196                 parentMessage = MBMessageLocalServiceUtil.getMessage(
197                     parentMessageId);
198             }
199         }
200         catch (NoSuchMessageException nsme) {
201         }
202 
203         if (_log.isDebugEnabled()) {
204             _log.debug("Parent message " + parentMessage);
205         }
206 
207         MBMailMessage collector = new MBMailMessage();
208 
209         MBUtil.collectPartContent(mailMessage, collector);
210 
211         PermissionCheckerUtil.setThreadValues(user);
212 
213         MailingListThreadLocal.setSourceMailingList(true);
214 
215         String subject = MBUtil.getSubjectWithoutMessageId(mailMessage);
216 
217         ServiceContext serviceContext = new ServiceContext();
218 
219         serviceContext.setAddCommunityPermissions(true);
220         serviceContext.setAddGuestPermissions(true);
221 
222         if (parentMessage == null) {
223             MBMessageServiceUtil.addMessage(
224                 categoryId, subject, collector.getBody(), collector.getFiles(),
225                 anonymous, 0.0, serviceContext);
226         }
227         else {
228             MBMessageServiceUtil.addMessage(
229                 categoryId, parentMessage.getThreadId(),
230                 parentMessage.getMessageId(), subject, collector.getBody(),
231                 collector.getFiles(), anonymous, 0.0, serviceContext);
232         }
233     }
234 
235     protected void processMessages(
236             MailingListRequest mailingListRequest, Message[] messages)
237         throws Exception {
238 
239         for (Message message : messages) {
240             processMessage(mailingListRequest, message);
241         }
242     }
243 
244     private static Log _log =
245         LogFactoryUtil.getLog(MailingListMessageListener.class);
246 
247 }