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.pop;
24  
25  import com.liferay.portal.kernel.log.Log;
26  import com.liferay.portal.kernel.log.LogFactoryUtil;
27  import com.liferay.portal.kernel.pop.MessageListener;
28  import com.liferay.portal.kernel.pop.MessageListenerException;
29  import com.liferay.portal.kernel.util.GetterUtil;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.model.Company;
33  import com.liferay.portal.model.User;
34  import com.liferay.portal.security.auth.PrincipalException;
35  import com.liferay.portal.security.permission.PermissionCheckerUtil;
36  import com.liferay.portal.service.CompanyLocalServiceUtil;
37  import com.liferay.portal.service.ServiceContext;
38  import com.liferay.portal.service.UserLocalServiceUtil;
39  import com.liferay.portlet.messageboards.NoSuchMessageException;
40  import com.liferay.portlet.messageboards.model.MBCategory;
41  import com.liferay.portlet.messageboards.model.MBMessage;
42  import com.liferay.portlet.messageboards.service.MBCategoryLocalServiceUtil;
43  import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
44  import com.liferay.portlet.messageboards.service.MBMessageServiceUtil;
45  import com.liferay.portlet.messageboards.util.MBMailMessage;
46  import com.liferay.portlet.messageboards.util.MBUtil;
47  
48  import javax.mail.Message;
49  
50  import org.apache.commons.lang.time.StopWatch;
51  
52  /**
53   * <a href="MessageListenerImpl.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Brian Wing Shun Chan
56   * @author Jorge Ferrer
57   * @author Michael C. Han
58   *
59   */
60  public class MessageListenerImpl implements MessageListener {
61  
62      public boolean accept(String from, String recipient, Message message) {
63          try {
64              String messageId = getMessageId(recipient, message);
65  
66              if ((messageId == null) ||
67                  (!messageId.startsWith(
68                      MBUtil.POP_PORTLET_PREFIX, getOffset()))) {
69  
70                  return false;
71              }
72  
73              Company company = getCompany(recipient);
74              long categoryId = getCategoryId(messageId);
75  
76              MBCategory category = MBCategoryLocalServiceUtil.getCategory(
77                  categoryId);
78  
79              if (category.getCompanyId() != company.getCompanyId()) {
80                  return false;
81              }
82  
83              if (_log.isDebugEnabled()) {
84                  _log.debug("Check to see if user " + from + " exists");
85              }
86  
87              UserLocalServiceUtil.getUserByEmailAddress(
88                  company.getCompanyId(), from);
89  
90              return true;
91          }
92          catch (Exception e) {
93              if (_log.isErrorEnabled()) {
94                  _log.error("Unable to process message: " + message, e);
95              }
96  
97              return false;
98          }
99      }
100 
101     public void deliver(String from, String recipient, Message message)
102         throws MessageListenerException {
103 
104         try {
105             StopWatch stopWatch = null;
106 
107             if (_log.isDebugEnabled()) {
108                 stopWatch = new StopWatch();
109 
110                 stopWatch.start();
111 
112                 _log.debug("Deliver message from " + from + " to " + recipient);
113             }
114 
115             Company company = getCompany(recipient);
116 
117             String messageId = getMessageId(recipient, message);
118 
119             if (_log.isDebugEnabled()) {
120                 _log.debug("Message id " + messageId);
121             }
122 
123             long categoryId = getCategoryId(messageId);
124 
125             if (_log.isDebugEnabled()) {
126                 _log.debug("Category id " + categoryId);
127             }
128 
129             User user = UserLocalServiceUtil.getUserByEmailAddress(
130                 company.getCompanyId(), from);
131 
132             long parentMessageId = getParentMessageId(recipient, message);
133 
134             if (_log.isDebugEnabled()) {
135                 _log.debug("Parent message id " + parentMessageId);
136             }
137 
138             MBMessage parentMessage = null;
139 
140             try {
141                 if (parentMessageId > 0) {
142                     parentMessage = MBMessageLocalServiceUtil.getMessage(
143                         parentMessageId);
144                 }
145             }
146             catch (NoSuchMessageException nsme) {
147 
148                 // If the parent message does not exist we ignore it and post
149                 // the message as a new thread.
150 
151             }
152 
153             if (_log.isDebugEnabled()) {
154                 _log.debug("Parent message " + parentMessage);
155             }
156 
157             String subject = MBUtil.getSubjectWithoutMessageId(message);
158 
159             MBMailMessage collector = new MBMailMessage();
160 
161             MBUtil.collectPartContent(message, collector);
162 
163             PermissionCheckerUtil.setThreadValues(user);
164 
165             ServiceContext serviceContext = new ServiceContext();
166 
167             serviceContext.setAddCommunityPermissions(true);
168             serviceContext.setAddGuestPermissions(true);
169 
170             if (parentMessage == null) {
171                 MBMessageServiceUtil.addMessage(
172                     categoryId, subject, collector.getBody(),
173                     collector.getFiles(), false, 0.0, serviceContext);
174             }
175             else {
176                 MBMessageServiceUtil.addMessage(
177                     categoryId, parentMessage.getThreadId(),
178                     parentMessage.getMessageId(), subject, collector.getBody(),
179                     collector.getFiles(), false, 0.0, serviceContext);
180             }
181 
182             if (_log.isDebugEnabled()) {
183                 _log.debug(
184                     "Delivering message takes " + stopWatch.getTime() + " ms");
185             }
186         }
187         catch (PrincipalException pe) {
188             if (_log.isDebugEnabled()) {
189                 _log.debug("Prevented unauthorized post from " + from);
190             }
191 
192             throw new MessageListenerException(pe);
193         }
194         catch (Exception e) {
195             _log.error(e, e);
196 
197             throw new MessageListenerException(e);
198         }
199     }
200 
201     public String getId() {
202         return MessageListenerImpl.class.getName();
203     }
204 
205     protected long getCategoryId(String recipient) {
206         int pos = recipient.indexOf(StringPool.AT);
207 
208         String target = recipient.substring(
209             MBUtil.POP_PORTLET_PREFIX.length() + getOffset(), pos);
210 
211         String[] parts = StringUtil.split(target, StringPool.PERIOD);
212 
213         return GetterUtil.getLong(parts[0]);
214     }
215 
216     protected Company getCompany(String recipient) throws Exception {
217         int pos =
218             recipient.indexOf(StringPool.AT) +
219                 MBUtil.POP_SERVER_SUBDOMAIN_LENGTH + 1;
220 
221         if (MBUtil.POP_SERVER_SUBDOMAIN_LENGTH > 0) {
222             pos++;
223         }
224 
225         String mx = recipient.substring(pos);
226 
227         return CompanyLocalServiceUtil.getCompanyByMx(mx);
228     }
229 
230     protected String getMessageId(String recipient, Message message)
231         throws Exception {
232 
233         if (MBUtil.POP_SERVER_SUBDOMAIN_LENGTH > 0) {
234             return recipient;
235         }
236         else {
237             return MBUtil.getParentMessageIdString(message);
238         }
239     }
240 
241     protected int getOffset() {
242         if (MBUtil.POP_SERVER_SUBDOMAIN_LENGTH == 0) {
243             return 1;
244         }
245         return 0;
246     }
247 
248     protected long getParentMessageId(String recipient, Message message)
249         throws Exception {
250 
251         // Get the parent message ID from the recipient address
252 
253         int pos = recipient.indexOf(StringPool.AT);
254 
255         String target = recipient.substring(
256             MBUtil.POP_PORTLET_PREFIX.length(), pos);
257 
258         String[] parts = StringUtil.split(target, StringPool.PERIOD);
259 
260         long parentMessageId = 0;
261 
262         if (parts.length == 2) {
263             parentMessageId = GetterUtil.getLong(parts[1]);
264         }
265 
266         if (parentMessageId > 0) {
267             return parentMessageId;
268         }
269         else {
270             return MBUtil.getParentMessageId(message);
271         }
272     }
273 
274     private static Log _log = LogFactoryUtil.getLog(MessageListenerImpl.class);
275 
276 }