001/*
002 *  Copyright 2014 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;
017
018import java.io.IOException;
019import java.util.HashSet;
020import java.util.Set;
021import java.util.regex.Pattern;
022
023import javax.jcr.Node;
024import javax.jcr.RepositoryException;
025import javax.jcr.Value;
026
027import org.apache.avalon.framework.service.ServiceException;
028import org.apache.avalon.framework.service.ServiceManager;
029import org.apache.cocoon.ProcessingException;
030import org.apache.cocoon.environment.ObjectModelHelper;
031import org.apache.cocoon.environment.Request;
032import org.apache.cocoon.generation.ServiceableGenerator;
033import org.apache.cocoon.xml.AttributesImpl;
034import org.apache.cocoon.xml.XMLUtils;
035import org.xml.sax.SAXException;
036
037import org.ametys.core.user.CurrentUserProvider;
038import org.ametys.core.user.User;
039import org.ametys.core.user.UserIdentity;
040import org.ametys.core.user.UserManager;
041import org.ametys.core.util.mail.SendMailHelper;
042import org.ametys.plugins.repository.AmetysObjectResolver;
043import org.ametys.plugins.repository.RepositoryConstants;
044import org.ametys.plugins.repository.jcr.JCRAmetysObject;
045import org.ametys.web.repository.page.Page;
046
047/**
048 * Generate user info about a page
049 */
050public class InfoSubscriberGenerator extends ServiceableGenerator
051{
052    /** Constant for the attachment node name. */
053    public static final String SUBSCRIBERS_PROPERTY_NAME = RepositoryConstants.NAMESPACE_PREFIX_INTERNAL + ":subscriberMails";
054    
055    /** The pattern to check emails */
056    protected static final Pattern EMAIL_VALIDATOR = SendMailHelper.EMAIL_VALIDATION;
057    
058    /** The pattern to check text input */
059    protected static final Pattern TEXT_VALIDATOR = Pattern.compile("^\\s*$");
060    
061    /** Repository content */
062    protected AmetysObjectResolver _resolver;
063    
064    /** FO user manager */
065    protected UserManager _foUserManager;
066    
067    /** The current user provider */
068    protected CurrentUserProvider _currentUserProvider;
069    
070    @Override
071    public void service(ServiceManager smanager) throws ServiceException
072    {
073        super.service(smanager);
074        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
075        _foUserManager = (UserManager) smanager.lookup(UserManager.ROLE);
076        _currentUserProvider = (CurrentUserProvider) smanager.lookup(CurrentUserProvider.ROLE);
077    }
078
079    public void generate() throws IOException, SAXException, ProcessingException
080    {
081        Request request = ObjectModelHelper.getRequest(objectModel);
082        
083        UserIdentity userIdentity = _currentUserProvider.getUser();
084        User user = _foUserManager.getUser(userIdentity.getPopulationId(), userIdentity.getLogin());
085        
086        contentHandler.startDocument();
087        AttributesImpl attr = new AttributesImpl();
088        if (user == null)
089        {
090            attr.addCDATAAttribute("isLogged", "false");
091            XMLUtils.createElement(contentHandler, "user", attr);
092        }
093        else
094        {
095            attr.addCDATAAttribute("isLogged", "true");
096            String email = user.getEmail();
097          
098            String pageId = request.getParameter("page-id");
099            if (pageId == null) 
100            {
101                throw new IllegalArgumentException("Unable to subscribe or unsubscribe to the page: cannot determine the current page");
102            }
103            else
104            {
105                Page page = _resolver.resolveById(pageId);
106                if (page instanceof JCRAmetysObject)
107                {
108                    Set<String> subscribers = _getSubscribers((JCRAmetysObject) page);
109                    attr.addCDATAAttribute("isRegistered", Boolean.toString(subscribers.contains(email)));
110                }
111                else
112                {
113                    throw new ProcessingException("Unable to subscribe or unsubscribe to the page: the page is not subscribable");
114                }
115            }
116            XMLUtils.createElement(contentHandler, "user", attr, email);    
117        }
118        contentHandler.endDocument();
119    }
120
121    private Set<String> _getSubscribers (JCRAmetysObject page)
122    {
123        Set<String> subscriberMails = new HashSet<>();
124        
125        try
126        {
127            Node node = page.getNode();
128            if (node.hasProperty(SUBSCRIBERS_PROPERTY_NAME))
129            {
130                Value[] values = node.getProperty(SUBSCRIBERS_PROPERTY_NAME).getValues();
131                for (Value value : values)
132                {
133                    subscriberMails.add(value.getString());
134                }
135            }
136        }
137        catch (RepositoryException e)
138        {
139            getLogger().error("Unable to retrieve subscribers for page of id'" + page.getId() + "'", e);
140        }
141        
142        return subscriberMails;
143    }
144
145}