001/*
002 *  Copyright 2020 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.exchange;
017
018import java.time.LocalDateTime;
019import java.time.ZoneId;
020import java.time.ZoneOffset;
021import java.time.ZonedDateTime;
022import java.time.format.DateTimeFormatter;
023import java.time.temporal.ChronoUnit;
024import java.util.ArrayList;
025import java.util.Date;
026import java.util.List;
027import java.util.Map;
028import java.util.TreeMap;
029import java.util.stream.Collectors;
030
031import org.apache.avalon.framework.service.ServiceException;
032import org.apache.avalon.framework.service.ServiceManager;
033
034import org.ametys.core.user.UserIdentity;
035import org.ametys.core.util.DateUtils;
036import org.ametys.plugins.extrausermgt.users.aad.GraphClientProvider;
037import org.ametys.plugins.extrausermgt.users.aad.GraphClientProvider.GraphClientException;
038import org.ametys.plugins.messagingconnector.AbstractMessagingConnector;
039import org.ametys.plugins.messagingconnector.CalendarEvent;
040import org.ametys.plugins.messagingconnector.EmailMessage;
041import org.ametys.plugins.messagingconnector.MessagingConnectorException;
042import org.ametys.plugins.messagingconnector.MessagingConnectorException.ExceptionType;
043
044import com.microsoft.graph.models.Event;
045import com.microsoft.graph.models.Message;
046import com.microsoft.graph.options.QueryOption;
047import com.microsoft.graph.requests.MessageCollectionPage;
048import com.microsoft.graph.requests.UserRequestBuilder;
049
050/**
051 * The connector used by the messaging connector plugin when connecting to Exchange Online.<br>
052 * Implemented through the Microsoft Graph API.
053 */
054public class GraphConnector extends AbstractMessagingConnector
055{
056    /** The avalon role */
057    public static final String INNER_ROLE = GraphConnector.class.getName();
058    
059    /** The Graph client provider */
060    protected GraphClientProvider _graphClientProvider;
061    
062    @Override
063    public void service(ServiceManager manager) throws ServiceException
064    {
065        super.service(manager);
066        _graphClientProvider = (GraphClientProvider) manager.lookup(GraphClientProvider.ROLE);
067    }
068    
069    private List<Event> _getEvents(UserIdentity userIdentity, int maxDays)
070    {
071        try
072        {
073            UserRequestBuilder userRequestBuilder = _graphClientProvider.getUserRequestBuilder(userIdentity);
074            
075            ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS);
076            
077            String start = now.format(DateTimeFormatter.ISO_DATE_TIME);
078            String end = now.plusDays(maxDays).format(DateTimeFormatter.ISO_DATE_TIME);
079            
080            return userRequestBuilder.calendar()
081                    .calendarView()
082                    .buildRequest(new QueryOption("startDateTime", start),
083                            new QueryOption("endDateTime", end),
084                            new QueryOption("$orderby", "start/datetime"))
085                    .select("subject,start,end,location")
086                    .get().getCurrentPage();
087        }
088        catch (GraphClientException e)
089        {
090            throw new MessagingConnectorException("Failed to retrieve a Graph client for user " + userIdentity + ". "
091                    + "The user could not be linked to a Entra user", ExceptionType.UNAUTHORIZED);
092        }
093    }
094    
095    @Override
096    protected List<CalendarEvent> internalGetEvents(UserIdentity userIdentity, int maxDays, int maxEvents) throws MessagingConnectorException
097    {
098        List<Event> events = _getEvents(userIdentity, maxDays);
099        
100        Map<Long, CalendarEvent> calendarEvents = new TreeMap<>();
101        for (Event event : events)
102        {
103            LocalDateTime ldt = LocalDateTime.parse(event.start.dateTime, DateTimeFormatter.ISO_DATE_TIME);
104            ZonedDateTime zdt = ldt.atZone(ZoneId.of(event.start.timeZone));
105            zdt = zdt.withZoneSameInstant(ZoneId.systemDefault());
106            
107            long longStart = zdt.toEpochSecond();
108            Date startDate = DateUtils.asDate(zdt);
109            
110            ldt = LocalDateTime.parse(event.end.dateTime, DateTimeFormatter.ISO_DATE_TIME);
111            zdt = ldt.atZone(ZoneId.of(event.end.timeZone));
112            zdt = zdt.withZoneSameInstant(ZoneId.systemDefault());
113            
114            Date endDate = DateUtils.asDate(zdt);
115            
116            CalendarEvent newEvent = new CalendarEvent();
117            newEvent.setStartDate(startDate);
118            newEvent.setEndDate(endDate);
119            newEvent.setSubject(event.subject);
120            newEvent.setLocation(event.location.displayName);
121            calendarEvents.put(longStart, newEvent);
122        }
123        
124        return calendarEvents.entrySet().stream().limit(maxEvents).map(e -> e.getValue()).collect(Collectors.toList());
125    }
126
127    @Override
128    protected int internalGetEventsCount(UserIdentity userIdentity, int maxDays) throws MessagingConnectorException
129    {
130        return _getEvents(userIdentity, maxDays).size();
131    }
132
133    @Override
134    protected List<EmailMessage> internalGetEmails(UserIdentity userIdentity, int maxEmails) throws MessagingConnectorException
135    {
136        try
137        {
138            UserRequestBuilder userRequestBuilder = _graphClientProvider.getUserRequestBuilder(userIdentity);
139            
140            MessageCollectionPage messageCollectionPage = userRequestBuilder.mailFolders("inbox").messages().buildRequest()
141                    .top(maxEmails)
142                    .select("sender,subject,bodyPreview")
143                    .filter("isRead eq false")
144                    .get();
145            
146            List<EmailMessage> result = new ArrayList<>();
147            for (Message message : messageCollectionPage.getCurrentPage())
148            {
149                result.add(new EmailMessage(message.subject, message.sender.emailAddress.address, message.bodyPreview));
150            }
151            
152            return result;
153        }
154        catch (GraphClientException e)
155        {
156            throw new MessagingConnectorException("Failed to retrieve a Graph client for user " + userIdentity + ". "
157                    + "The user could not be linked to a Entra user", ExceptionType.UNAUTHORIZED);
158        }
159    }
160
161    @Override
162    protected int internalGetEmailsCount(UserIdentity userIdentity) throws MessagingConnectorException
163    {
164        try
165        {
166            UserRequestBuilder userRequestBuilder = _graphClientProvider.getUserRequestBuilder(userIdentity);
167            
168            return userRequestBuilder.mailFolders("inbox").buildRequest().get().unreadItemCount;
169        }
170        catch (GraphClientException e)
171        {
172            throw new MessagingConnectorException("Failed to retrieve a Graph client for user " + userIdentity + ". "
173                    + "The user could not be linked to a Entra user", ExceptionType.UNAUTHORIZED);
174        }
175    }
176}