001/*
002 *  Copyright 2015 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.clientsideelement;
017
018import java.io.IOException;
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.HashSet;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025
026import org.apache.avalon.framework.service.ServiceException;
027import org.apache.avalon.framework.service.ServiceManager;
028import org.apache.commons.lang.StringUtils;
029
030import org.ametys.core.group.Group;
031import org.ametys.core.group.GroupIdentity;
032import org.ametys.core.group.GroupManager;
033import org.ametys.core.ui.Callable;
034import org.ametys.core.ui.ClientSideElement;
035import org.ametys.core.ui.mail.StandardMailBodyHelper;
036import org.ametys.core.ui.mail.StandardMailBodyHelper.MailBodyBuilder;
037import org.ametys.core.user.User;
038import org.ametys.core.user.UserIdentity;
039import org.ametys.core.user.UserManager;
040import org.ametys.core.util.I18nUtils;
041import org.ametys.core.util.mail.SendMailHelper;
042import org.ametys.plugins.core.user.UserHelper;
043import org.ametys.runtime.config.Config;
044import org.ametys.runtime.i18n.I18nizableText;
045import org.ametys.runtime.i18n.I18nizableTextParameter;
046import org.ametys.web.repository.page.Page;
047import org.ametys.web.repository.site.Site;
048
049import jakarta.mail.MessagingException;
050
051/**
052 * This {@link ClientSideElement} creates a button that will be enabled if page and its hierarchy is valid.
053 *
054 */
055public class LivePageClientSideElement extends AbstractPageClientSideElement
056{
057    /** The {@link UserManager} */
058    private UserManager _userManager;
059    
060    /** The {@link UserManager} for front-end users */
061    private UserManager _foUsersManager;
062    
063    /** The {@link GroupManager} for front-end groups */
064    private GroupManager _foGroupsManager;
065    
066    /** The {@link I18nUtils} */
067    private I18nUtils _i18nUtils;
068    
069    private UserHelper _userHelper;
070    
071    @Override
072    public void service(ServiceManager smanager) throws ServiceException
073    {
074        super.service(smanager);
075        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
076        _foUsersManager = (UserManager) smanager.lookup(UserManager.ROLE);
077        _foGroupsManager = (GroupManager) smanager.lookup(GroupManager.ROLE);
078        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
079        _userHelper = (UserHelper) smanager.lookup(UserHelper.ROLE);
080    }
081    
082    /**
083     * Send a notification for online pages.
084     * @param pageIds the ids of the pages
085     * @param users the users that will be notified
086     * @param groups the groups that will be notified
087     * @param comment the comment of the notifier 
088     * @return the result 
089     */
090    @Callable (rights = Callable.SKIP_BUILTIN_CHECK)
091    public Map<String, Object> sendOnlineNotification(List<String> pageIds, List<Map<String, String>> users, List<Map<String, String>> groups, String comment)
092    { 
093        List<String> allRightIds = new ArrayList<>();
094        List<Map<String, Object>> noRightPages = new ArrayList<>();
095        
096        UserIdentity userIdentity = _currentUserProvider.getUser();
097        User notifier = _userManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
098        
099        List<UserIdentity> userIdentities = new ArrayList<>();
100        for (Map<String, String> user : users)
101        {
102            UserIdentity ui = _userHelper.json2userIdentity(user);
103            if (ui != null)
104            {
105                userIdentities.add(ui);
106            }
107        }
108        List<GroupIdentity> groupIdentities = new ArrayList<>();
109        for (Map<String, String> group : groups)
110        {
111            String id = group.get("groupId");
112            String groupDirectory = group.get("groupDirectory");
113            groupIdentities.add(new GroupIdentity(id, groupDirectory));
114        }
115        Set<User> distinctUsers = _getDistinctUsers (userIdentities, groupIdentities);
116        
117        for (String pageId : pageIds)
118        {
119            Page page = _resolver.resolveById(pageId);
120            
121            if (!hasRight(page))
122            {
123                noRightPages.add(Map.of("id", pageId, "title", page.getTitle()));
124            }
125            else
126            {
127                allRightIds.add(pageId);
128                
129                String from = _getSender(notifier, page);
130                String subject = _getSubject (notifier, page);
131                
132                for (User user : distinctUsers)
133                {
134                    if (StringUtils.isNotEmpty(user.getEmail()))
135                    {
136                        try
137                        {
138                            String body = _getBody(notifier, user, page, comment);
139                            
140                            SendMailHelper.newMail()
141                                          .withSubject(subject)
142                                          .withHTMLBody(body)
143                                          .withSender(from)
144                                          .withRecipient(user.getEmail())
145                                          .sendMail();
146                        }
147                        catch (MessagingException | IOException e) 
148                        {
149                            getLogger().error("Unable to send mail to user " + user.getEmail(), e);
150                        }
151                    }
152                }
153            }
154        }
155        
156        return Map.of("allright-pages", allRightIds, "noright-pages", noRightPages);
157    }
158
159    /**
160     * Get the email sender
161     * @param sender The user responsible for the action
162     * @param page The published page
163     * @return The sender
164     */
165    private String _getSender (User sender, Page page)
166    {
167        if (sender != null && sender.getEmail() != null)
168        {
169            return sender.getFullName() + " <" + sender.getEmail() + ">";
170        }
171        
172        Site site = page.getSite();
173        String defaultFromValue = Config.getInstance().getValue("smtp.mail.from");
174        return site.getValue("site-mail-from", false, defaultFromValue);
175    }
176    
177    /**
178     * Get the email subject
179     * @param sender The user responsible for the notification
180     * @param page The published page
181     * @return The email subject
182     */
183    private String _getSubject (User sender, Page page)
184    {
185        Site site = page.getSite();
186        
187        Map<String, I18nizableTextParameter> subjectI18nParameters = new HashMap<>();
188        subjectI18nParameters.put("user", new I18nizableText(sender.getFullName()));
189        subjectI18nParameters.put("siteTitle", new I18nizableText(site.getTitle()));
190        subjectI18nParameters.put("pageTitle", new I18nizableText(page.getTitle()));
191        
192        I18nizableText msg = new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_SUBJECT", subjectI18nParameters);
193        
194        return _i18nUtils.translate(msg, page.getSitemapName());
195    }
196    
197    /**
198     * Get the email body
199     * @param sender The user responsible for the notification
200     * @param user The recipient of the notification
201     * @param page The published page
202     * @param comment The user's comment. Can be empty or null.
203     * @return The email body
204     * @throws IOException if faile dto build HTML mail body
205     */
206    private String _getBody (User sender, User user, Page page, String comment) throws IOException
207    {
208        Site site = page.getSite();
209        String pageUrl = site.getUrl() + "/" + page.getSitemap().getName() + "/" + page.getPathInSitemap() + ".html";
210        
211        Map<String, I18nizableTextParameter> i18nParams = new HashMap<>();
212        i18nParams.put("sender", new I18nizableText(sender.getFullName()));
213        i18nParams.put("user", new I18nizableText(user.getFullName()));
214        i18nParams.put("siteTitle", new I18nizableText(site.getTitle()));
215        i18nParams.put("siteUrl", new I18nizableText(site.getUrl()));
216        i18nParams.put("pageTitle", new I18nizableText(page.getTitle()));
217        i18nParams.put("pageUrl", new I18nizableText(pageUrl));
218        
219        MailBodyBuilder bodyBuilder = StandardMailBodyHelper.newHTMLBody()
220            .withTitle(new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_TITLE", i18nParams))
221            .addMessage(new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY", i18nParams))
222            .addMessage(new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_LINK_TEXT", i18nParams))
223            .withLink(pageUrl, new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_LINK_BUTTON"));
224        
225        if (StringUtils.isNotEmpty(comment))
226        {
227            bodyBuilder.withDetails(new I18nizableText("plugin.web", "PLUGINS_WEB_PAGE_NOTIFY_ONLINE_PUBLICATION_MAIL_BODY_COMMENT"), comment, false);
228        }
229        
230        return bodyBuilder.build();
231    }
232    
233    private Set<User> _getDistinctUsers (List<UserIdentity> userIdentities, List<GroupIdentity> groupIdentities)
234    {
235        Set<User> users = new HashSet<>();
236        
237        for (UserIdentity userIdentity : userIdentities)
238        {
239            if (userIdentity != null && StringUtils.isNotEmpty(userIdentity.getLogin()) && StringUtils.isNotEmpty(userIdentity.getPopulationId()))
240            {
241                User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
242                if (user != null)
243                {
244                    users.add(user);
245                }
246            }
247        }
248        
249        for (GroupIdentity groupIdentity : groupIdentities)
250        {
251            if (groupIdentity != null && StringUtils.isNotEmpty(groupIdentity.getId()) && StringUtils.isNotEmpty(groupIdentity.getDirectoryId()))
252            {
253                Group group = _foGroupsManager.getGroup(groupIdentity.getDirectoryId(), groupIdentity.getId());
254                if (group != null)
255                {
256                    Set<UserIdentity> groupUsers = group.getUsers();
257                    for (UserIdentity userIdentity : groupUsers)
258                    {
259                        User user = _foUsersManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
260                        if (user != null)
261                        {
262                            users.add(user);
263                        }
264                    }
265                }
266            }
267        }
268        
269        return users;
270    }
271}