001/*
002 *  Copyright 2013 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.web.repository.page.actions;
017
018import java.util.HashMap;
019import java.util.HashSet;
020import java.util.List;
021import java.util.Map;
022import java.util.Set;
023import java.util.stream.Collectors;
024
025import javax.mail.MessagingException;
026
027import org.apache.avalon.framework.parameters.Parameters;
028import org.apache.avalon.framework.service.ServiceException;
029import org.apache.avalon.framework.service.ServiceManager;
030import org.apache.cocoon.acting.ServiceableAction;
031import org.apache.cocoon.environment.ObjectModelHelper;
032import org.apache.cocoon.environment.Redirector;
033import org.apache.cocoon.environment.SourceResolver;
034
035import org.ametys.core.group.Group;
036import org.ametys.core.group.GroupIdentity;
037import org.ametys.core.group.GroupManager;
038import org.ametys.core.user.CurrentUserProvider;
039import org.ametys.core.user.User;
040import org.ametys.core.user.UserIdentity;
041import org.ametys.core.user.UserManager;
042import org.ametys.core.util.I18nUtils;
043import org.ametys.core.util.mail.SendMailHelper;
044import org.ametys.plugins.core.user.UserHelper;
045import org.ametys.plugins.repository.AmetysObjectResolver;
046import org.ametys.runtime.config.Config;
047import org.ametys.runtime.i18n.I18nizableText;
048import org.ametys.web.repository.page.Page;
049import org.ametys.web.repository.site.Site;
050
051/**
052 * This actions send a email to notify the publication of a page.
053 *
054 */
055public class SendOnlineNotificationAction extends ServiceableAction
056{
057    private UserManager _userManager;
058    private GroupManager _groupManager;
059    private AmetysObjectResolver _resolver;
060    private I18nUtils _i18nUtils;
061    private CurrentUserProvider _userProvider;
062    private UserHelper _userHelper;
063    
064    
065    @Override
066    public void service(ServiceManager smanager) throws ServiceException
067    {
068        super.service(smanager);
069        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
070        _userProvider = (CurrentUserProvider) smanager.lookup(CurrentUserProvider.ROLE);
071        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
072        _groupManager = (GroupManager) smanager.lookup(GroupManager.ROLE);
073        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
074        _userHelper = (UserHelper) smanager.lookup(UserHelper.ROLE);
075    }
076    
077    
078    @Override
079    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
080    {
081        @SuppressWarnings("unchecked")
082        Map<String, Object> jsParameters = (Map<String, Object>) objectModel.get(ObjectModelHelper.PARENT_CONTEXT);
083        
084        String pageId = (String) jsParameters.get("id");
085        Page page = _resolver.resolveById(pageId);
086        
087        UserIdentity userIdentity = _userProvider.getUser();
088        User notifier = _userManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
089        
090        String from = _getSender(notifier, page);
091        String subject = _getSubject (notifier, page);
092        
093        @SuppressWarnings("unchecked")
094        List<Map<String, String>> jsUsers = (List<Map<String, String>>) jsParameters.get("users");
095        List<UserIdentity> userIdentities = jsUsers.stream()
096                .map(_userHelper::json2userIdentity)
097                .collect(Collectors.toList());
098        
099        @SuppressWarnings("unchecked")
100        List<Map<String, String>> jsGroups = (List<Map<String, String>>) jsParameters.get("groups");
101        List<GroupIdentity> groupIdentities = jsGroups.stream()
102                .map(jsGroup -> new GroupIdentity(jsGroup.get("id"), jsGroup.get("groupDirectory")))
103                .collect(Collectors.toList());
104        
105        Set<User> users = _getDistinctUsers(userIdentities, groupIdentities);
106        for (User user : users)
107        {
108            if (user.getEmail() != null)
109            {
110                try
111                {
112                    String body = _getBody(notifier, user, page);
113                    SendMailHelper.sendMail(subject, null, body, user.getEmail(), from);
114                }
115                catch (MessagingException e) 
116                {
117                    getLogger().error("Unable to send mail to user " + user.getEmail(), e);
118                }
119            }
120        }
121        
122        return EMPTY_MAP;
123    }
124    
125    /**
126     * Get the email sender
127     * @param sender The user responsible for the action
128     * @param page The published page
129     * @return The sender
130     */
131    protected String _getSender (User sender, Page page)
132    {
133        if (sender != null && sender.getEmail() != null)
134        {
135            return sender.getFullName() + " <" + sender.getEmail() + ">";
136        }
137
138        Site site = page.getSite();
139        String defaultFromValue = Config.getInstance().getValue("smtp.mail.from");
140        return site.getValue("site-mail-from", false, defaultFromValue);
141    }
142    
143    /**
144     * Get the email subject
145     * @param sender The user responsible for the notification
146     * @param page The published page
147     * @return The email subject
148     */
149    protected String _getSubject (User sender, Page page)
150    {
151        Site site = page.getSite();
152        
153        Map<String, I18nizableText> subjectI18nParameters = new HashMap<>();
154        subjectI18nParameters.put("user", new I18nizableText(sender.getFullName()));
155        subjectI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
156        subjectI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
157        
158        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_SUBJECT", subjectI18nParameters);
159        
160        return _i18nUtils.translate(msg, page.getSitemapName());
161    }
162    
163    /**
164     * Get the email body
165     * @param sender The user responsible for the notification
166     * @param user The recipient of the notification
167     * @param page The published page
168     * @return The email body
169     */
170    protected String _getBody (User sender, User user, Page page)
171    {
172        Site site = page.getSite();
173        
174        Map<String, I18nizableText> bodyI18nParameters = new HashMap<>();
175        bodyI18nParameters.put("sender", new I18nizableText(sender.getFullName()));
176        bodyI18nParameters.put("user", new I18nizableText(user.getFullName()));
177        bodyI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
178        bodyI18nParameters.put("siteUrl", new I18nizableText(site.getUrl()));
179        bodyI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
180        bodyI18nParameters.put("pageUrl", new I18nizableText(site.getUrl() + "/" + page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html"));
181        
182        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY", bodyI18nParameters);
183        
184        return _i18nUtils.translate(msg, page.getSitemapName());
185    }
186    
187    private Set<User> _getDistinctUsers (List<UserIdentity> userIdentities, List<GroupIdentity> groupIdentities)
188    {
189        Set<User> users = new HashSet<>();
190        
191        for (UserIdentity userIdentity : userIdentities)
192        {
193            User user = _userManager.getUser(userIdentity);
194            if (user != null)
195            {
196                users.add(user);
197            }
198        }
199        
200        for (GroupIdentity groupIdentity : groupIdentities)
201        {
202            Group group = _groupManager.getGroup(groupIdentity);
203            if (group != null)
204            {
205                Set<UserIdentity> userGroupIdentities = group.getUsers();
206                for (UserIdentity userGroupIdentity : userGroupIdentities)
207                {
208                    User user = _userManager.getUser(userGroupIdentity);
209                    if (user != null)
210                    {
211                        users.add(user);
212                    }
213                }
214            }
215        }
216        
217        return users;
218    }
219}