001/*
002 *  Copyright 2023 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.plugins.pagesubscription.page.notifier;
017
018import java.io.IOException;
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023import java.util.Set;
024
025import org.apache.avalon.framework.service.ServiceException;
026import org.apache.avalon.framework.service.ServiceManager;
027import org.apache.avalon.framework.service.Serviceable;
028import org.apache.commons.lang.StringUtils;
029
030import org.ametys.core.user.User;
031import org.ametys.core.user.UserIdentity;
032import org.ametys.core.user.UserManager;
033import org.ametys.core.util.I18nUtils;
034import org.ametys.core.util.language.UserLanguagesManager;
035import org.ametys.plugins.pagesubscription.page.PageSubscriptionDAO;
036import org.ametys.plugins.repository.AmetysObjectResolver;
037import org.ametys.plugins.repository.activities.Activity;
038import org.ametys.plugins.repository.activities.ActivityType;
039import org.ametys.runtime.i18n.I18nizableText;
040import org.ametys.runtime.plugin.component.AbstractLogEnabled;
041import org.ametys.web.activities.AbstractPageActivityType;
042import org.ametys.web.activities.notify.ActivityNotifier;
043import org.ametys.web.repository.page.Page;
044import org.ametys.web.repository.page.jcr.DefaultPage;
045import org.ametys.web.repository.site.Site;
046
047/**
048 * Abstract notifier for page activity
049 */
050public abstract class AbstractPageSubscriptionNotifier extends AbstractLogEnabled implements ActivityNotifier, Serviceable
051{
052    /** The ametys object resolver */
053    protected AmetysObjectResolver _resolver;
054    
055    /** The i18n utils */
056    protected I18nUtils _i18nUtils;
057
058    /** The user manager */
059    protected UserManager _userManager;
060    
061    /** The subscription dao */
062    protected PageSubscriptionDAO _subscriptionDAO;
063    
064    /** The user languages manager */
065    protected UserLanguagesManager _userLanguagesManager;
066    
067    public void service(ServiceManager manager) throws ServiceException
068    {
069        _resolver = (AmetysObjectResolver) manager.lookup(AmetysObjectResolver.ROLE);
070        _i18nUtils = (I18nUtils) manager.lookup(I18nUtils.ROLE);
071        _userManager = (UserManager) manager.lookup(UserManager.ROLE);
072        _subscriptionDAO = (PageSubscriptionDAO) manager.lookup(PageSubscriptionDAO.ROLE);
073        _userLanguagesManager = (UserLanguagesManager) manager.lookup(UserLanguagesManager.ROLE);
074    }
075    
076    @Override
077    public Map<String, List<String>> getUsersToNotifyByLanguage(Activity activity)
078    {
079        Map<String, List<String>> result = new HashMap<>();
080        ActivityType activityType = activity.getActivityType();
081        if (activityType instanceof AbstractPageActivityType)
082        {
083            User user = _userManager.getUser(activity.getAuthor());
084            String activityAuthorEmail = user != null ? user.getEmail() : null;
085            String pageId = activity.getValue(AbstractPageActivityType.PAGE_ID);
086            Page page = _resolver.resolveById(pageId);
087        
088            if (page instanceof DefaultPage && isNotificationEnabled(page))
089            {
090                List<String> emails = new ArrayList<>();
091                Set<String> subscribers = _subscriptionDAO.getSubscribers(page);
092        
093                for (String subscriber : subscribers)
094                {
095                    if (StringUtils.isNotBlank(subscriber) && !subscriber.equals(activityAuthorEmail))
096                    {
097                        emails.add(subscriber);
098                    }
099                }
100                
101                result.put(_userLanguagesManager.getDefaultLanguage(), emails);
102            }
103        }
104        
105        return result;
106    }
107    
108    /**
109     * Determines if the notification is currently enabled
110     * @param page The page
111     * @return true if the notification is enabled
112     */
113    protected boolean isNotificationEnabled(Page page)
114    {
115        Site site = page.getSite();
116        return site.getValue(getSiteParameterId(), true, false);
117    }
118    
119    /**
120     * Id of the site parameter to enable/disable the notification
121     * @return The id of site
122     */
123    protected abstract String getSiteParameterId();
124    
125    @Override
126    public String getMailSubject(Activity activity, String language)
127    {
128        String pageId = activity.getValue(AbstractPageActivityType.PAGE_ID);
129        Page page = _resolver.resolveById(pageId);
130        
131        I18nizableText i18nSubject = _getMailSubject(activity, page);
132        
133        return _i18nUtils.translate(i18nSubject, language);
134    }
135    
136    /**
137     * Get the mail subject
138     * @param activity the activity
139     * @param page the page from activity
140     * @return the mail subject
141     */
142    protected abstract I18nizableText _getMailSubject(Activity activity, Page page);
143
144    @Override
145    public String getMailTextBody(Activity activity, String language)
146    {
147        // No text body
148        return null;
149    }
150    
151    @Override
152    public String getMailHtmlBody(Activity activity, String language)
153    {
154        String pageId = activity.getValue(AbstractPageActivityType.PAGE_ID);
155        Page page = _resolver.resolveById(pageId);
156      
157        UserIdentity author = activity.getAuthor();
158        User user = _userManager.getUser(author);
159        
160        if (user != null)
161        {
162            try
163            {
164                return _getMailHtmlBody(activity, language, page, user);
165            }
166            catch (Exception e)
167            {
168                getLogger().error("Can't get mail body for activity from event '{}' and type '{}'", activity.getEventType(), activity.getActivityType().getId(), e);
169            }
170        }
171        return null;
172    }
173    
174    /**
175     * Get the mail body
176     * @param activity the activity
177     * @param language The language
178     * @param page the page from activity
179     * @param author the author of the activity
180     * @return the mail body
181     * @throws IOException if an error occurred
182     */
183    protected abstract String _getMailHtmlBody(Activity activity, String language, Page page, User author) throws IOException;
184
185    /**
186     * Get the absolute URL of a page
187     * @param page The page to retrieve the url
188     * @return The absolute url of the page
189     */
190    protected String _getAbsolutePageUrl(Page page)
191    {
192        return new StringBuilder().append(page.getSite().getUrl())
193                .append("/").append(page.getSitemapName())
194                .append("/").append(page.getPathInSitemap())
195                .append(".html").toString();
196    }
197    
198}