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;
034import org.apache.commons.lang.StringUtils;
035
036import org.ametys.core.group.Group;
037import org.ametys.core.group.GroupIdentity;
038import org.ametys.core.group.GroupManager;
039import org.ametys.core.user.CurrentUserProvider;
040import org.ametys.core.user.User;
041import org.ametys.core.user.UserIdentity;
042import org.ametys.core.user.UserManager;
043import org.ametys.core.util.I18nUtils;
044import org.ametys.core.util.mail.SendMailHelper;
045import org.ametys.plugins.core.user.UserHelper;
046import org.ametys.plugins.repository.AmetysObjectResolver;
047import org.ametys.runtime.config.Config;
048import org.ametys.runtime.i18n.I18nizableText;
049import org.ametys.web.repository.page.Page;
050import org.ametys.web.repository.site.Site;
051import org.ametys.web.site.SiteConfigurationExtensionPoint;
052
053/**
054 * This actions send a email to notify the publication of a page.
055 *
056 */
057public class SendOnlineNotificationAction extends ServiceableAction
058{
059    private UserManager _userManager;
060    private GroupManager _groupManager;
061    private SiteConfigurationExtensionPoint _siteConfiguration;
062    private AmetysObjectResolver _resolver;
063    private I18nUtils _i18nUtils;
064    private CurrentUserProvider _userProvider;
065    private UserHelper _userHelper;
066    
067    
068    @Override
069    public void service(ServiceManager smanager) throws ServiceException
070    {
071        super.service(smanager);
072        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
073        _userProvider = (CurrentUserProvider) smanager.lookup(CurrentUserProvider.ROLE);
074        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
075        _groupManager = (GroupManager) smanager.lookup(GroupManager.ROLE);
076        _siteConfiguration = (SiteConfigurationExtensionPoint) smanager.lookup(SiteConfigurationExtensionPoint.ROLE);
077        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
078        _userHelper = (UserHelper) smanager.lookup(UserHelper.ROLE);
079    }
080    
081    
082    @Override
083    public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters parameters) throws Exception
084    {
085        @SuppressWarnings("unchecked")
086        Map<String, Object> jsParameters = (Map<String, Object>) objectModel.get(ObjectModelHelper.PARENT_CONTEXT);
087        
088        String pageId = (String) jsParameters.get("id");
089        Page page = _resolver.resolveById(pageId);
090        
091        UserIdentity userIdentity = _userProvider.getUser();
092        User notifier = _userManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
093        
094        String from = _getSender(notifier, page);
095        String subject = _getSubject (notifier, page);
096        
097        @SuppressWarnings("unchecked")
098        List<Map<String, String>> jsUsers = (List<Map<String, String>>) jsParameters.get("users");
099        List<UserIdentity> userIdentities = jsUsers.stream()
100                .map(_userHelper::json2userIdentity)
101                .collect(Collectors.toList());
102        
103        @SuppressWarnings("unchecked")
104        List<Map<String, String>> jsGroups = (List<Map<String, String>>) jsParameters.get("groups");
105        List<GroupIdentity> groupIdentities = jsGroups.stream()
106                .map(jsGroup -> new GroupIdentity(jsGroup.get("id"), jsGroup.get("groupDirectory")))
107                .collect(Collectors.toList());
108        
109        Set<User> users = _getDistinctUsers(userIdentities, groupIdentities);
110        for (User user : users)
111        {
112            if (user.getEmail() != null)
113            {
114                try
115                {
116                    String body = _getBody(notifier, user, page);
117                    SendMailHelper.sendMail(subject, null, body, user.getEmail(), from);
118                }
119                catch (MessagingException e) 
120                {
121                    getLogger().error("Unable to send mail to user " + user.getEmail(), e);
122                }
123            }
124        }
125        
126        return EMPTY_MAP;
127    }
128    
129    /**
130     * Get the email sender
131     * @param sender The user responsible for the action
132     * @param page The published page
133     * @return The sender
134     */
135    protected String _getSender (User sender, Page page)
136    {
137        if (sender != null && sender.getEmail() != null)
138        {
139            return sender.getFullName() + " <" + sender.getEmail() + ">";
140        }
141        
142        String from = _siteConfiguration.getValueAsString(page.getSiteName(), "site-mail-from");
143        if (StringUtils.isBlank(from))
144        {
145            from = Config.getInstance().getValueAsString("smtp.mail.from");
146        }
147        return from;
148    }
149    
150    /**
151     * Get the email subject
152     * @param sender The user responsible for the notification
153     * @param page The published page
154     * @return The email subject
155     */
156    protected String _getSubject (User sender, Page page)
157    {
158        Site site = page.getSite();
159        
160        Map<String, I18nizableText> subjectI18nParameters = new HashMap<>();
161        subjectI18nParameters.put("user", new I18nizableText(sender.getFullName()));
162        subjectI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
163        subjectI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
164        
165        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_SUBJECT", subjectI18nParameters);
166        
167        return _i18nUtils.translate(msg, page.getSitemapName());
168    }
169    
170    /**
171     * Get the email body
172     * @param sender The user responsible for the notification
173     * @param user The recipient of the notification
174     * @param page The published page
175     * @return The email body
176     */
177    protected String _getBody (User sender, User user, Page page)
178    {
179        Site site = page.getSite();
180        
181        Map<String, I18nizableText> bodyI18nParameters = new HashMap<>();
182        bodyI18nParameters.put("sender", new I18nizableText(sender.getFullName()));
183        bodyI18nParameters.put("user", new I18nizableText(user.getFullName()));
184        bodyI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
185        bodyI18nParameters.put("siteUrl", new I18nizableText(site.getUrl()));
186        bodyI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
187        bodyI18nParameters.put("pageUrl", new I18nizableText(site.getUrl() + "/" + page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html"));
188        
189        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY", bodyI18nParameters);
190        
191        return _i18nUtils.translate(msg, page.getSitemapName());
192    }
193    
194    private Set<User> _getDistinctUsers (List<UserIdentity> userIdentities, List<GroupIdentity> groupIdentities)
195    {
196        Set<User> users = new HashSet<>();
197        
198        for (UserIdentity userIdentity : userIdentities)
199        {
200            User user = _userManager.getUser(userIdentity);
201            if (user != null)
202            {
203                users.add(user);
204            }
205        }
206        
207        for (GroupIdentity groupIdentity : groupIdentities)
208        {
209            Group group = _groupManager.getGroup(groupIdentity);
210            if (group != null)
211            {
212                Set<UserIdentity> userGroupIdentities = group.getUsers();
213                for (UserIdentity userGroupIdentity : userGroupIdentities)
214                {
215                    User user = _userManager.getUser(userGroupIdentity);
216                    if (user != null)
217                    {
218                        users.add(user);
219                    }
220                }
221            }
222        }
223        
224        return users;
225    }
226}