1   /**
2    * Copyright (c) 2000-2008 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.wiki.messaging;
24  
25  import com.liferay.mail.service.MailServiceUtil;
26  import com.liferay.portal.NoSuchUserException;
27  import com.liferay.portal.kernel.json.JSONFactoryUtil;
28  import com.liferay.portal.kernel.json.JSONObject;
29  import com.liferay.portal.kernel.mail.MailMessage;
30  import com.liferay.portal.kernel.messaging.MessageListener;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.model.Subscription;
33  import com.liferay.portal.model.User;
34  import com.liferay.portal.service.SubscriptionLocalServiceUtil;
35  import com.liferay.portal.service.UserLocalServiceUtil;
36  import com.liferay.portlet.wiki.model.WikiNode;
37  import com.liferay.portlet.wiki.model.WikiPage;
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  import org.apache.commons.logging.Log;
46  import org.apache.commons.logging.LogFactory;
47  
48  /**
49   * <a href="WikiMessageListener.java.html"><b><i>View Source</i></b></a>
50   *
51   * @author Brian Wing Shun Chan
52   *
53   */
54  public class WikiMessageListener implements MessageListener {
55  
56      public void receive(Object message) {
57          throw new UnsupportedOperationException();
58      }
59  
60      public void receive(String message) {
61          try {
62              doReceive(message);
63          }
64          catch (Exception e) {
65              _log.error("Unable to process message " + message, e);
66          }
67      }
68  
69      public void doReceive(String message) throws Exception {
70          JSONObject jsonObj = JSONFactoryUtil.createJSONObject(message);
71  
72          long companyId = jsonObj.getLong("companyId");
73          long userId = jsonObj.getLong("userId");
74          long nodeId = jsonObj.getLong("nodeId");
75          long pageResourcePrimKey = jsonObj.getLong("pageResourcePrimKey");
76          String fromName = jsonObj.getString("fromName");
77          String fromAddress = jsonObj.getString("fromAddress");
78          String subject = jsonObj.getString("subject");
79          String body = jsonObj.getString("body");
80          String replyToAddress = jsonObj.getString("replyToAddress");
81          String mailId = jsonObj.getString("mailId");
82  
83          Set<Long> sent = new HashSet<Long>();
84  
85          if (_log.isInfoEnabled()) {
86              _log.info(
87                  "Sending notifications for {mailId=" + mailId +
88                      ", pageResourcePrimKey=" + pageResourcePrimKey +
89                          ", nodeId=" + nodeId + "}");
90          }
91  
92          // Pages
93  
94          List<Subscription> subscriptions =
95              SubscriptionLocalServiceUtil.getSubscriptions(
96                  companyId, WikiPage.class.getName(), pageResourcePrimKey);
97  
98          sendEmail(
99              userId, fromName, fromAddress, subject, body, subscriptions, sent,
100             replyToAddress, mailId);
101 
102         // Nodes
103 
104         subscriptions = SubscriptionLocalServiceUtil.getSubscriptions(
105             companyId, WikiNode.class.getName(), nodeId);
106 
107         sendEmail(
108             userId, fromName, fromAddress, subject, body, subscriptions, sent,
109             replyToAddress, mailId);
110 
111         if (_log.isInfoEnabled()) {
112             _log.info("Finished sending notifications");
113         }
114     }
115 
116     protected void sendEmail(
117             long userId, String fromName, String fromAddress, String subject,
118             String body, List<Subscription> subscriptions, Set<Long> sent,
119             String replyToAddress, String mailId)
120         throws Exception {
121 
122         for (Subscription subscription : subscriptions) {
123             long subscribedUserId = subscription.getUserId();
124 
125             if (sent.contains(subscribedUserId)) {
126                 if (_log.isDebugEnabled()) {
127                     _log.debug(
128                         "Do not send a duplicate email to user " +
129                             subscribedUserId);
130                 }
131 
132                 continue;
133             }
134             else {
135                 if (_log.isDebugEnabled()) {
136                     _log.debug(
137                         "Add user " + subscribedUserId +
138                             " to the list of users who have received an email");
139                 }
140 
141                 sent.add(subscribedUserId);
142             }
143 
144             User user = null;
145 
146             try {
147                 user = UserLocalServiceUtil.getUserById(
148                     subscription.getUserId());
149             }
150             catch (NoSuchUserException nsue) {
151                 if (_log.isInfoEnabled()) {
152                     _log.info(
153                         "Subscription " + subscription.getSubscriptionId() +
154                             " is stale and will be deleted");
155                 }
156 
157                 SubscriptionLocalServiceUtil.deleteSubscription(
158                     subscription.getSubscriptionId());
159 
160                 continue;
161             }
162 
163             try {
164                 InternetAddress from = new InternetAddress(
165                     fromAddress, fromName);
166 
167                 InternetAddress to = new InternetAddress(
168                     user.getEmailAddress(), user.getFullName());
169 
170                 String curSubject = StringUtil.replace(
171                     subject,
172                     new String[] {
173                         "[$TO_ADDRESS$]",
174                         "[$TO_NAME$]"
175                     },
176                     new String[] {
177                         user.getFullName(),
178                         user.getEmailAddress()
179                     });
180 
181                 String curBody = StringUtil.replace(
182                     body,
183                     new String[] {
184                         "[$TO_ADDRESS$]",
185                         "[$TO_NAME$]"
186                     },
187                     new String[] {
188                         user.getFullName(),
189                         user.getEmailAddress()
190                     });
191 
192                 InternetAddress replyTo = new InternetAddress(
193                     replyToAddress, replyToAddress);
194 
195                 MailMessage message = new MailMessage(
196                     from, to, curSubject, curBody, false);
197 
198                 message.setReplyTo(new InternetAddress[] {replyTo});
199                 message.setMessageId(mailId);
200 
201                 MailServiceUtil.sendEmail(message);
202             }
203             catch (Exception e) {
204                 _log.error(e);
205             }
206         }
207     }
208 
209     private static Log _log = LogFactory.getLog(WikiMessageListener.class);
210 
211 }