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