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.blogs.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.Message;
31  import com.liferay.portal.kernel.messaging.MessageListener;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.model.Subscription;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.service.SubscriptionLocalServiceUtil;
36  import com.liferay.portal.service.UserLocalServiceUtil;
37  import com.liferay.portlet.blogs.model.BlogsEntry;
38  
39  import java.util.HashSet;
40  import java.util.List;
41  import java.util.Set;
42  
43  import javax.mail.internet.InternetAddress;
44  
45  /**
46   * <a href="BlogsMessageListener.java.html"><b><i>View Source</i></b></a>
47   *
48   * @author Thiago Moreira
49   */
50  public class BlogsMessageListener implements MessageListener {
51  
52      public void receive(Message message) {
53          try {
54              doReceive(message);
55          }
56          catch (Exception e) {
57              _log.error("Unable to process message " + message, e);
58          }
59      }
60  
61      protected void doReceive(Message message) throws Exception {
62          long companyId = message.getLong("companyId");
63          long userId = message.getLong("userId");
64          long groupId = message.getLong("groupId");
65          long entryId = message.getLong("entryId");
66          String fromName = message.getString("fromName");
67          String fromAddress = message.getString("fromAddress");
68          String subject = message.getString("subject");
69          String body = message.getString("body");
70          String replyToAddress = message.getString("replyToAddress");
71          String mailId = message.getString("mailId");
72          boolean htmlFormat = message.getBoolean("htmlFormat");
73  
74          Set<Long> sent = new HashSet<Long>();
75  
76          if (_log.isInfoEnabled()) {
77              _log.info(
78                  "Sending notifications for {mailId=" + mailId + ", entryId=" +
79                      entryId + "}");
80          }
81  
82          // Entries
83  
84          List<Subscription> subscriptions =
85              SubscriptionLocalServiceUtil.getSubscriptions(
86                  companyId, BlogsEntry.class.getName(), groupId);
87  
88          sendEmail(
89              userId, fromName, fromAddress, subject, body, subscriptions, sent,
90              replyToAddress, mailId, htmlFormat);
91  
92          if (_log.isInfoEnabled()) {
93              _log.info("Finished sending notifications");
94          }
95      }
96  
97      protected void sendEmail(
98              long userId, String fromName, String fromAddress, String subject,
99              String body, List<Subscription> subscriptions, Set<Long> sent,
100             String replyToAddress, String mailId, boolean htmlFormat)
101         throws Exception {
102 
103         for (Subscription subscription : subscriptions) {
104             long subscribedUserId = subscription.getUserId();
105 
106             if (sent.contains(subscribedUserId)) {
107                 if (_log.isDebugEnabled()) {
108                     _log.debug(
109                         "Do not send a duplicate email to user " +
110                             subscribedUserId);
111                 }
112 
113                 continue;
114             }
115             else {
116                 if (_log.isDebugEnabled()) {
117                     _log.debug(
118                         "Add user " + subscribedUserId +
119                             " to the list of users who have received an email");
120                 }
121 
122                 sent.add(subscribedUserId);
123             }
124 
125             User user = null;
126 
127             try {
128                 user = UserLocalServiceUtil.getUserById(
129                     subscription.getUserId());
130             }
131             catch (NoSuchUserException nsue) {
132                 if (_log.isInfoEnabled()) {
133                     _log.info(
134                         "Subscription " + subscription.getSubscriptionId() +
135                             " is stale and will be deleted");
136                 }
137 
138                 SubscriptionLocalServiceUtil.deleteSubscription(
139                     subscription.getSubscriptionId());
140 
141                 continue;
142             }
143 
144             if (!user.isActive()) {
145                 continue;
146             }
147 
148             try {
149                 InternetAddress from = new InternetAddress(
150                     fromAddress, fromName);
151 
152                 InternetAddress to = new InternetAddress(
153                     user.getEmailAddress(), user.getFullName());
154 
155                 String curSubject = StringUtil.replace(
156                     subject,
157                     new String[] {
158                         "[$TO_ADDRESS$]",
159                         "[$TO_NAME$]"
160                     },
161                     new String[] {
162                         user.getFullName(),
163                         user.getEmailAddress()
164                     });
165 
166                 String curBody = StringUtil.replace(
167                     body,
168                     new String[] {
169                         "[$TO_ADDRESS$]",
170                         "[$TO_NAME$]"
171                     },
172                     new String[] {
173                         user.getFullName(),
174                         user.getEmailAddress()
175                     });
176 
177                 InternetAddress replyTo = new InternetAddress(
178                     replyToAddress, replyToAddress);
179 
180                 MailMessage message = new MailMessage(
181                     from, to, curSubject, curBody, htmlFormat);
182 
183                 message.setReplyTo(new InternetAddress[] {replyTo});
184                 message.setMessageId(mailId);
185 
186                 MailServiceUtil.sendEmail(message);
187             }
188             catch (Exception e) {
189                 _log.error(e);
190             }
191         }
192     }
193 
194     private static Log _log = LogFactoryUtil.getLog(BlogsMessageListener.class);
195 
196 }