1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.portlet.messageboards.messaging;
21  
22  import com.liferay.mail.service.MailServiceUtil;
23  import com.liferay.portal.NoSuchUserException;
24  import com.liferay.portal.kernel.log.Log;
25  import com.liferay.portal.kernel.log.LogFactoryUtil;
26  import com.liferay.portal.kernel.mail.MailMessage;
27  import com.liferay.portal.kernel.messaging.MessageListener;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.StringUtil;
31  import com.liferay.portal.model.Subscription;
32  import com.liferay.portal.model.User;
33  import com.liferay.portal.service.SubscriptionLocalServiceUtil;
34  import com.liferay.portal.service.UserLocalServiceUtil;
35  import com.liferay.portlet.messageboards.model.MBCategory;
36  import com.liferay.portlet.messageboards.model.MBThread;
37  import com.liferay.portlet.messageboards.util.BBCodeUtil;
38  
39  import java.util.ArrayList;
40  import java.util.HashSet;
41  import java.util.List;
42  import java.util.Set;
43  
44  import javax.mail.internet.InternetAddress;
45  
46  /**
47   * <a href="MBMessageListener.java.html"><b><i>View Source</i></b></a>
48   *
49   * @author Brian Wing Shun Chan
50   *
51   */
52  public class MBMessageListener implements MessageListener {
53  
54      public void receive(com.liferay.portal.kernel.messaging.Message message) {
55          try {
56              doReceive(message);
57          }
58          catch (Exception e) {
59              _log.error("Unable to process message " + message, e);
60          }
61      }
62  
63      public void doReceive(com.liferay.portal.kernel.messaging.Message message)
64          throws Exception {
65  
66          long companyId = message.getLong("companyId");
67          long userId = message.getLong("userId");
68          String categoryIds = message.getString("categoryIds");
69          String threadId = message.getString("threadId");
70          String fromName = message.getString("fromName");
71          String fromAddress = message.getString("fromAddress");
72          String subject = message.getString("subject");
73          String body = message.getString("body");
74          String replyToAddress = message.getString("replyToAddress");
75          String mailId = message.getString("mailId");
76          String inReplyTo = message.getString("inReplyTo");
77          boolean htmlFormat = message.getBoolean("htmlFormat");
78  
79          subject = subject + StringPool.SPACE + mailId;
80  
81          Set<Long> sent = new HashSet<Long>();
82  
83          if (_log.isInfoEnabled()) {
84              _log.info(
85                  "Sending notifications for {mailId=" + mailId + ", threadId=" +
86                      threadId + ", categoryIds=" + categoryIds + "}");
87          }
88  
89          // Threads
90  
91          List<Subscription> subscriptions =
92              SubscriptionLocalServiceUtil.getSubscriptions(
93                  companyId, MBThread.class.getName(),
94                  GetterUtil.getLong(threadId));
95  
96          sendEmail(
97              userId, fromName, fromAddress, subject, body, subscriptions, sent,
98              replyToAddress, mailId, inReplyTo, htmlFormat);
99  
100         // Categories
101 
102         long[] categoryIdsArray = StringUtil.split(categoryIds, 0L);
103 
104         for (long categoryId : categoryIdsArray) {
105             subscriptions = SubscriptionLocalServiceUtil.getSubscriptions(
106                 companyId, MBCategory.class.getName(), categoryId);
107 
108             sendEmail(
109                 userId, fromName, fromAddress, subject, body, subscriptions,
110                 sent, replyToAddress, mailId, inReplyTo, htmlFormat);
111         }
112 
113         if (_log.isInfoEnabled()) {
114             _log.info("Finished sending notifications");
115         }
116     }
117 
118     protected void sendEmail(
119             long userId, String fromName, String fromAddress, String subject,
120             String body, List<Subscription> subscriptions, Set<Long> sent,
121             String replyToAddress, String mailId, String inReplyTo,
122             boolean htmlFormat)
123         throws Exception {
124 
125         List<InternetAddress> addresses =
126             new ArrayList<InternetAddress>();
127 
128         for (Subscription subscription : subscriptions) {
129             long subscribedUserId = subscription.getUserId();
130 
131             if (sent.contains(subscribedUserId)) {
132                 if (_log.isDebugEnabled()) {
133                     _log.debug(
134                         "Do not send a duplicate email to user " +
135                             subscribedUserId);
136                 }
137 
138                 continue;
139             }
140             else {
141                 if (_log.isDebugEnabled()) {
142                     _log.debug(
143                         "Add user " + subscribedUserId +
144                             " to the list of users who have received an email");
145                 }
146 
147                 sent.add(subscribedUserId);
148             }
149 
150             User user = null;
151 
152             try {
153                 user = UserLocalServiceUtil.getUserById(
154                     subscription.getUserId());
155             }
156             catch (NoSuchUserException nsue) {
157                 if (_log.isInfoEnabled()) {
158                     _log.info(
159                         "Subscription " + subscription.getSubscriptionId() +
160                             " is stale and will be deleted");
161                 }
162 
163                 SubscriptionLocalServiceUtil.deleteSubscription(
164                     subscription.getSubscriptionId());
165 
166                 continue;
167             }
168 
169             if (!user.isActive()) {
170                 continue;
171             }
172 
173             InternetAddress userAddress = new InternetAddress(
174                 user.getEmailAddress(), user.getFullName());
175 
176             addresses.add(userAddress);
177         }
178 
179         try {
180             InternetAddress[] bulkAddresses = addresses.toArray(
181                 new InternetAddress[addresses.size()]);
182 
183             if (bulkAddresses.length == 0) {
184                 return;
185             }
186 
187             InternetAddress from = new InternetAddress(fromAddress, fromName);
188 
189             InternetAddress to = new InternetAddress(
190                 replyToAddress, replyToAddress);
191 
192             String curSubject = StringUtil.replace(
193                 subject,
194                 new String[] {
195                     "[$TO_ADDRESS$]",
196                     "[$TO_NAME$]"
197                 },
198                 new String[] {
199                     replyToAddress,
200                     replyToAddress
201                 });
202 
203             String curBody = StringUtil.replace(
204                 body,
205                 new String[] {
206                     "[$TO_ADDRESS$]",
207                     "[$TO_NAME$]"
208                 },
209                 new String[] {
210                     replyToAddress,
211                     replyToAddress
212                 });
213 
214             InternetAddress replyTo = new InternetAddress(
215                 replyToAddress, replyToAddress);
216 
217             if (htmlFormat) {
218                 try {
219                     curBody = BBCodeUtil.getHTML(curBody);
220                 }
221                 catch (Exception e) {
222                     _log.error(
223                         "Could not parse message " + mailId + " " +
224                             e.getMessage());
225                 }
226             }
227 
228             MailMessage message = new MailMessage(
229                 from, to, curSubject, curBody, htmlFormat);
230 
231             message.setBulkAddresses(bulkAddresses);
232             message.setMessageId(mailId);
233             message.setInReplyTo(inReplyTo);
234             message.setReplyTo(new InternetAddress[] {replyTo});
235 
236             MailServiceUtil.sendEmail(message);
237         }
238         catch (Exception e) {
239             _log.error(e);
240         }
241     }
242 
243     private static Log _log = LogFactoryUtil.getLog(MBMessageListener.class);
244 
245 }