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.mail.service.MailServiceUtil;
26  import com.liferay.portal.NoSuchUserException;
27  import com.liferay.portal.kernel.log.Log;
28  import com.liferay.portal.kernel.log.LogFactoryUtil;
29  import com.liferay.portal.kernel.mail.MailMessage;
30  import com.liferay.portal.kernel.messaging.MessageListener;
31  import com.liferay.portal.kernel.util.GetterUtil;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.model.Subscription;
35  import com.liferay.portal.model.User;
36  import com.liferay.portal.service.SubscriptionLocalServiceUtil;
37  import com.liferay.portal.service.UserLocalServiceUtil;
38  import com.liferay.portlet.messageboards.model.MBCategory;
39  import com.liferay.portlet.messageboards.model.MBThread;
40  import com.liferay.portlet.messageboards.util.BBCodeUtil;
41  
42  import java.util.ArrayList;
43  import java.util.HashSet;
44  import java.util.List;
45  import java.util.Set;
46  
47  import javax.mail.internet.InternetAddress;
48  
49  /**
50   * <a href="MBMessageListener.java.html"><b><i>View Source</i></b></a>
51   *
52   * @author Brian Wing Shun Chan
53   *
54   */
55  public class MBMessageListener implements MessageListener {
56  
57      public void receive(com.liferay.portal.kernel.messaging.Message message) {
58          try {
59              doReceive(message);
60          }
61          catch (Exception e) {
62              _log.error("Unable to process message " + message, e);
63          }
64      }
65  
66      public void doReceive(com.liferay.portal.kernel.messaging.Message message)
67          throws Exception {
68  
69          long companyId = message.getLong("companyId");
70          long userId = message.getLong("userId");
71          String categoryIds = message.getString("categoryIds");
72          String threadId = message.getString("threadId");
73          String fromName = message.getString("fromName");
74          String fromAddress = message.getString("fromAddress");
75          String subject = message.getString("subject");
76          String body = message.getString("body");
77          String replyToAddress = message.getString("replyToAddress");
78          String mailId = message.getString("mailId");
79          String inReplyTo = message.getString("inReplyTo");
80          boolean htmlFormat = message.getBoolean("htmlFormat");
81  
82          subject = subject + StringPool.SPACE + mailId;
83  
84          Set<Long> sent = new HashSet<Long>();
85  
86          if (_log.isInfoEnabled()) {
87              _log.info(
88                  "Sending notifications for {mailId=" + mailId + ", threadId=" +
89                      threadId + ", categoryIds=" + categoryIds + "}");
90          }
91  
92          // Threads
93  
94          List<Subscription> subscriptions =
95              SubscriptionLocalServiceUtil.getSubscriptions(
96                  companyId, MBThread.class.getName(),
97                  GetterUtil.getLong(threadId));
98  
99          sendEmail(
100             userId, fromName, fromAddress, subject, body, subscriptions, sent,
101             replyToAddress, mailId, inReplyTo, htmlFormat);
102 
103         // Categories
104 
105         long[] categoryIdsArray = StringUtil.split(categoryIds, 0L);
106 
107         for (long categoryId : categoryIdsArray) {
108             subscriptions = SubscriptionLocalServiceUtil.getSubscriptions(
109                 companyId, MBCategory.class.getName(), categoryId);
110 
111             sendEmail(
112                 userId, fromName, fromAddress, subject, body, subscriptions,
113                 sent, replyToAddress, mailId, inReplyTo, htmlFormat);
114         }
115 
116         if (_log.isInfoEnabled()) {
117             _log.info("Finished sending notifications");
118         }
119     }
120 
121     protected void sendEmail(
122             long userId, String fromName, String fromAddress, String subject,
123             String body, List<Subscription> subscriptions, Set<Long> sent,
124             String replyToAddress, String mailId, String inReplyTo,
125             boolean htmlFormat)
126         throws Exception {
127 
128         List<InternetAddress> addresses =
129             new ArrayList<InternetAddress>();
130 
131         for (Subscription subscription : subscriptions) {
132             long subscribedUserId = subscription.getUserId();
133 
134             if (sent.contains(subscribedUserId)) {
135                 if (_log.isDebugEnabled()) {
136                     _log.debug(
137                         "Do not send a duplicate email to user " +
138                             subscribedUserId);
139                 }
140 
141                 continue;
142             }
143             else {
144                 if (_log.isDebugEnabled()) {
145                     _log.debug(
146                         "Add user " + subscribedUserId +
147                             " to the list of users who have received an email");
148                 }
149 
150                 sent.add(subscribedUserId);
151             }
152 
153             User user = null;
154 
155             try {
156                 user = UserLocalServiceUtil.getUserById(
157                     subscription.getUserId());
158             }
159             catch (NoSuchUserException nsue) {
160                 if (_log.isInfoEnabled()) {
161                     _log.info(
162                         "Subscription " + subscription.getSubscriptionId() +
163                             " is stale and will be deleted");
164                 }
165 
166                 SubscriptionLocalServiceUtil.deleteSubscription(
167                     subscription.getSubscriptionId());
168 
169                 continue;
170             }
171 
172             if (!user.isActive()) {
173                 continue;
174             }
175 
176             InternetAddress userAddress = new InternetAddress(
177                 user.getEmailAddress(), user.getFullName());
178 
179             addresses.add(userAddress);
180         }
181 
182         try {
183             InternetAddress[] bulkAddresses = addresses.toArray(
184                 new InternetAddress[addresses.size()]);
185 
186             if (bulkAddresses.length == 0) {
187                 return;
188             }
189 
190             InternetAddress from = new InternetAddress(fromAddress, fromName);
191 
192             InternetAddress to = new InternetAddress(
193                 replyToAddress, replyToAddress);
194 
195             String curSubject = StringUtil.replace(
196                 subject,
197                 new String[] {
198                     "[$TO_ADDRESS$]",
199                     "[$TO_NAME$]"
200                 },
201                 new String[] {
202                     replyToAddress,
203                     replyToAddress
204                 });
205 
206             String curBody = StringUtil.replace(
207                 body,
208                 new String[] {
209                     "[$TO_ADDRESS$]",
210                     "[$TO_NAME$]"
211                 },
212                 new String[] {
213                     replyToAddress,
214                     replyToAddress
215                 });
216 
217             InternetAddress replyTo = new InternetAddress(
218                 replyToAddress, replyToAddress);
219 
220             if (htmlFormat) {
221                 try {
222                     curBody = BBCodeUtil.getHTML(curBody);
223                 }
224                 catch (Exception e) {
225                     _log.error(
226                         "Could not parse message " + mailId + " " +
227                             e.getMessage());
228                 }
229             }
230 
231             MailMessage message = new MailMessage(
232                 from, to, curSubject, curBody, htmlFormat);
233 
234             message.setBulkAddresses(bulkAddresses);
235             message.setMessageId(mailId);
236             message.setInReplyTo(inReplyTo);
237             message.setReplyTo(new InternetAddress[] {replyTo});
238 
239             MailServiceUtil.sendEmail(message);
240         }
241         catch (Exception e) {
242             _log.error(e);
243         }
244     }
245 
246     private static Log _log = LogFactoryUtil.getLog(MBMessageListener.class);
247 
248 }