예제 #1
0
        public async Task <List <Models.CalendarEntry> > GetEvents(DateTime startDate, DateTime endDate, ILogger logger = null, bool isPrimary = false, bool isSecondary = false)
        {
            List <Models.CalendarEntry> eventResults = new List <Models.CalendarEntry>();

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List(CalendarId);
            request.TimeMin      = startDate;
            request.TimeMax      = endDate;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.TimeZone     = this.TimeZone;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = await request.ExecuteAsync();

            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    eventResults.AddRange(CreateCalendarEntries(eventItem, isPrimary, isSecondary));
                }
            }

            return(eventResults);
        }
        /// <summary>
        /// Get list of Events from Calendar
        /// </summary>
        /// <param name="service">Calendar service</param>
        /// <returns>list of Events</returns>
        public static async Task <IEnumerable <Event> > GetMyEvents()
        {
            CalendarService service = await InitializeCalendar();

            string calendarId = @"*****@*****.**";

            EventsResource.ListRequest listRequest = service.Events.List(calendarId);
            listRequest.TimeMin      = DateTime.Now;
            listRequest.ShowDeleted  = false;
            listRequest.SingleEvents = true;
            listRequest.MaxResults   = 10;
            listRequest.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
            Events events = await listRequest.ExecuteAsync();

            List <Event> eventList = new List <Event>();

            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    eventList.Add(eventItem);
                }
            }
            return(eventList);
        }
예제 #3
0
        public async Task <List <Models.CalendarEntry> > GetEventsSample()
        {
            List <Models.CalendarEntry> eventResults = new List <Models.CalendarEntry>();

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List(CalendarId);
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 10;
            request.TimeZone     = this.TimeZone;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = await request.ExecuteAsync();

            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    eventResults.AddRange(CreateCalendarEntries(eventItem));
                }
            }

            return(eventResults);
        }
예제 #4
0
        public async Task <IEnumerable <Event> > GetEvents()
        {
            // Define parameters of request.
            CalendarListResource.ListRequest calendarRequest = service.CalendarList.List();
            var calendars = await calendarRequest.ExecuteAsync();

            List <Event> allEvents = new List <Event>();

            foreach (var calendar in calendars.Items.Where(item => item.Selected ?? false))
            {
                EventsResource.ListRequest request = service.Events.List(calendar.Id);
                request.TimeMin      = DateTime.Now.Date;
                request.TimeMax      = DateTime.Now.Date.AddDays(1);
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
                Events events = await request.ExecuteAsync();

                if (events.Items != null)
                {
                    allEvents.AddRange(events.Items);
                }
            }
            return(allEvents);
        }
예제 #5
0
        private async Task <GoogleCalendarAppointment> FindAppointmentInternalAsync(string uniqueId)
        {
            EventsResource.ListRequest request = _service.Events.List(CalendarId);
            request.ShowDeleted = true;
            request.ICalUID     = uniqueId;
            var events = await request.ExecuteAsync().ConfigureAwait(false);

            Event ev = events.Items.SingleOrDefault(e => e.RecurringEventId == null);

            return(ev != null ? new GoogleCalendarAppointment(ev) : null);
        }
예제 #6
0
        public async Task <IActionResult> GetDuplicateEvents()
        {
            try
            {
                var startTimeInDayConfig = configuration["Settings:StartTimeInDay"];
                var endTimeInDayConfig   = configuration["Settings:EndTimeInDay"];
                startTimeInDay = TimeSpan.TryParse(startTimeInDayConfig, out startTimeInDay) ? startTimeInDay : new TimeSpan(7, 0, 0);
                endTimeInDay   = TimeSpan.TryParse(endTimeInDayConfig, out endTimeInDay) ? endTimeInDay : new TimeSpan(20, 0, 0);
                var service         = new CalendarService(BaseClientServiceCreator.Create(context, clientInfo, dataStore));
                var results         = new List <EventErrorResult>();
                var usableCalendars = context.FtmCalendarInfo.Where(x => x.IsUseable).ToArray();
                var timeMin         = DateTime.Now;
                var timeMax         = int.TryParse(configuration["CheckDuplicateInDay"], out int day) ? DateTime.Now.AddDays(day) : DateTime.Now.AddDays(30);

                foreach (var calendar in usableCalendars)
                {
                    EventsResource.ListRequest request = service.Events.List(calendar.CalendarId);
                    request.TimeMin      = timeMin;
                    request.TimeMax      = timeMax;
                    request.ShowDeleted  = false;
                    request.SingleEvents = true;
                    request.MaxResults   = 999;
                    request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
                    Events events = await request.ExecuteAsync();

                    if (!events.Items.Any())
                    {
                        continue;
                    }
                    var itemDic = events.Items.GroupBy(x => x.Start.DateTime.Value.Date, x => x).ToDictionary(x => x.Key, x => x.ToList());

                    foreach (var key in itemDic.Keys)
                    {
                        var listEventByDay = itemDic[key];

                        for (var index = 0; index < listEventByDay.Count(); index++)
                        {
                            if (CheckViolateEvent(index, listEventByDay, out Event error))
                            {
                                results.Add(error.CreateErrorResult());
                            }
                        }
                    }
                }

                return(Ok(results));
            }
            catch (Exception ex)
            {
                return(NotFound(ex.Message));
            }
        }
예제 #7
0
        public async Task <IEnumerable <Domain.Entities.Calendar.Event> > GetCalendarEvents(DateTime?minDate, DateTime?maxDate)
        {
            string credentials = Configuration.GetConfigurationFile("calendar_credentials");

            if (!File.Exists(credentials))
            {
                throw new UnconfiguredException("Please download the credentials. See the Readme.");
            }

            UserCredential credential = null;

            using (var stream = new FileStream(credentials, FileMode.Open, FileAccess.Read))
            {
                string token = Configuration.GetConfigurationFile("calendar_token");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(token, true)).Result;
            }

            if (credential is null)
            {
                throw new UnauthorizedException("Failed to login to Google Calendar");
            }

            // Create Google Calendar API service.
            var service = new GoogleCalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            var now = DateTime.Now;

            request.TimeMin = minDate;
            request.TimeMax = maxDate;
            request.ShowHiddenInvitations = false;
            request.ShowDeleted           = false;
            request.SingleEvents          = true;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = await request.ExecuteAsync();

            return(events.Items.Select(e => new Domain.Entities.Calendar.Event {
                Start = e.Start.DateTime, End = e.End.DateTime, Summary = e.Summary
            }));
        }
예제 #8
0
        public static async Task <List <Event> > GetEvents(string calendarId)
        {
            UserCredential credential;

            if (string.IsNullOrEmpty(calendarId))
            {
                throw new ArgumentException("calendarId is null or empty");
            }

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            EventsResource.ListRequest request = service.Events.List(calendarId);
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 10;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
            var events = await request.ExecuteAsync();

            Console.WriteLine("Calendar Events");
            if (events.Items != null)
            {
                foreach (var item in events.Items)
                {
                    Console.WriteLine(item.Id);
                }
            }

            return((List <Event>)events.Items);
        }
예제 #9
0
        private Task <Events> QueryCalendarEventsAsync(string calendarId, int n, DateTimeOffset d)
        {
            // Define parameters of request.
            EventsResource.ListRequest request = this._googleService.Events.List(calendarId);
            request.TimeMin      = d.Date;
            request.TimeMax      = new DateTimeOffset(d.Year, d.Month, d.Day, 23, 59, 59, d.Offset).AddDays(n).Date;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 20;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            // async WebRequest
            return(request.ExecuteAsync());
        }
예제 #10
0
        public async Task <Events> GetEvents(DateTime timeMax, string calendar = "primary")
        {
            if (calService == null)
            {
                await Auth(EditScopes);
            }

            EventsResource.ListRequest req = calService.Events.List(calendar);
            req.TimeMin      = DateTime.Now;
            req.TimeMax      = timeMax;
            req.ShowDeleted  = false;
            req.SingleEvents = true;
            req.OrderBy      = EventsResource.ListRequest.OrderByEnum.Updated;
            return(await req.ExecuteAsync());
        }
예제 #11
0
        public static async Task <List <Event> > GetUpcomingCalendarEvents(string serviceAccountEmail, string keyFileName,
                                                                           string calendarId, int maxResults)
        {
            //The values of the Google Service Account will be read from the .json key file, which should be available to the project
            GoogleServiceAccount keyValues;

            using (StreamReader r = new StreamReader(keyFileName))
            {
                string json = r.ReadToEnd();
                keyValues = JsonConvert.DeserializeObject <GoogleServiceAccount>(json);
            }

            CalendarService service = GoogleCalendarAuth.AuthenticateServiceAccountFromKey(serviceAccountEmail, keyValues.private_key);

            // Define parameter values of the Google Calendar request
            EventsResource.ListRequest request = service.Events.List(calendarId);
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = maxResults;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            // Execute the request
            var events = await request.ExecuteAsync();

            //Add the resulting events to a list (split this into a separate method)
            var eventList = new List <Event>();

            if (events.Items != null && events.Items.Count > 0)
            {
                eventList = events.Items.Select(i =>
                                                new Event
                {
                    StartDate        = i.Start?.DateTime ?? DateTime.MinValue,
                    EndDate          = i.End?.DateTime ?? DateTime.MinValue,
                    EventDescription = i.Description,
                    EventSummary     = i.Summary
                }
                                                ).ToList();
            }
            else
            {
                Console.WriteLine("No upcoming events found.");
            }
            return(eventList);
        }
예제 #12
0
        public async Task <Events> GetEvents(string id, bool all = true)
        {
            var service = new CalendarService(new BaseClientService.Initializer
            {
                HttpClientInitializer = ServiceAccount.Instance.Credential,
                ApplicationName       = "Calendar API Sample"
            });

            try
            {
                EventsResource.ListRequest request = service.Events.List(id);
                request.TimeMin = GetCorrectStart();
                if (!all)
                {
                    //get just this weeks
                    request.TimeMax = GetCorrectEndOfWeek();
                }
                else
                {
                    request.TimeMax = DateTime.UtcNow.NextMonth();
                }

                //request.

                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
                request.SingleEvents = true;

                request.MaxResults  = 5;
                request.ShowDeleted = false;


                var result = await request.ExecuteAsync();

                return(result);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(id);
                System.Diagnostics.Debug.WriteLine(exp.Message);
                throw;
            }

            //return ProcessResults(request);
        }
예제 #13
0
        public async Task <string> GetEvents(DateTime eventDate)
        {
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = User,
                ApplicationName       = "BotApp"
            });

            EventsResource.ListRequest request = service.Events.List("primary");
            Events events = await request.ExecuteAsync();

            StringBuilder sb = new StringBuilder();

            foreach (var calendarEvent in events.Items)
            {
                sb.AppendLine($"{calendarEvent.Summary} starting at {calendarEvent.Start.DateTime} and ending at {calendarEvent.End.DateTime}");
            }
            return(sb.ToString());
        }
예제 #14
0
            public async Task <Event[]> GetEventsAsync(Calendar calendar, DateTime startTime, DateTime endTime)
            {
                if (service == null)
                {
                    return(new Event[0]);
                }
                EventsResource.ListRequest request = service.Events.List(calendar.id);
                request.TimeMin      = startTime;
                request.TimeMax      = endTime;
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

                Events src = await request.ExecuteAsync();

                var dst = new Event[src.Items.Count];

                for (int i = 0; i < src.Items.Count; i++)
                {
                    var ev = src.Items[i];
                    dst[i] = new Event()
                    {
                        subject     = ev.Summary,
                        description = ev.Description,
                        uri         = new Uri(ev.HtmlLink),
                        allDay      = !String.IsNullOrEmpty(ev.Start.Date)
                    };
                    if (dst[i].allDay)
                    {
                        var start = new DateTime(int.Parse(ev.Start.Date.Substring(0, 4)), int.Parse(ev.Start.Date.Substring(5, 2)), int.Parse(ev.Start.Date.Substring(8, 2)));
                        var end   = new DateTime(int.Parse(ev.End.Date.Substring(0, 4)), int.Parse(ev.End.Date.Substring(5, 2)), int.Parse(ev.End.Date.Substring(8, 2)));
                        dst[i].startTime = start;
                        dst[i].duration  = end.AddSeconds(-1) - start;
                    }
                    else
                    {
                        dst[i].startTime = ev.Start.DateTime.Value;
                        dst[i].duration  = ev.End.DateTime.Value - ev.Start.DateTime.Value;
                    }
                }
                return(dst);
            }
예제 #15
0
        public async static Task GetEventList()
        {
            try
            {
                // Create Google Calendar API service.
                var service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = GlobalVariable.GoogleCalendarUserCredential,
                    ApplicationName       = ApplicationName,
                });

                // Define parameters of request.
                EventsResource.ListRequest request = service.Events.List("primary");
                request.TimeMin      = DateTime.Now;
                request.ShowDeleted  = false;
                request.SingleEvents = true;
                request.MaxResults   = 2;
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

                // List events.
                Events events = await request.ExecuteAsync();

                if (events.Items != null && events.Items.Count > 0)
                {
                    foreach (var eventItem in events.Items)
                    {
                        string when = eventItem.Start.DateTime.ToString();
                        if (String.IsNullOrEmpty(when))
                        {
                            when = eventItem.Start.Date;
                        }
                    }
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
            }
        }
예제 #16
0
        /// <summary>
        /// Read the Google events.
        /// </summary>
        internal override async Task ReadEventsAsync()
        {
            Events.Clear();

            using (CalendarService client = await GetClient())
            {
                EventsResource.ListRequest request = client.Events.List(await GetCalendarId());
                request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
                request.SingleEvents = true;
                request.ShowDeleted  = false;
                request.TimeMin      = StartDate;
                request.TimeMax      = EndDate;
                request.Q            = Subject;

                Events events = await request.ExecuteAsync();

                foreach (Event @event in events.Items
                         .Where(entry => entry.Summary == Subject))
                {
                    Events.Add(@event);
                }
            }
        }
예제 #17
0
 public IAsyncEnumerable <ILoadedAppointment> LoadAllAppointments()
 {
     using (Logger.Scope($"GoogleCalendar.LoadAllAppointments()"))
     {
         return(new AsyncEnumerable <ILoadedAppointment>(async yield =>
         {
             string pageToken = null;
             do
             {
                 EventsResource.ListRequest request = _service.Events.List(CalendarId);
                 request.PageToken = pageToken;
                 Events events = await request.ExecuteAsync(yield.CancellationToken).ConfigureAwait(false);
                 pageToken = events.NextPageToken;
                 foreach (Event ev in events.Items)
                 {
                     if (ev.RecurringEventId == null)
                     {
                         await yield.ReturnAsync(new GoogleCalendarAppointment(ev)).ConfigureAwait(false);
                     }
                 }
             } while (pageToken != null);
         }));
     }
 }
예제 #18
0
 public Task <Events> GetEvents(EventsResource.ListRequest listRequest)
 {
     return(listRequest.ExecuteAsync());
 }
예제 #19
0
        /// <summary>
        /// Get all freetime in all calendar
        /// </summary>
        /// <param name="service"></param>
        /// <param name="calendars"></param>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        private async Task <IEnumerable <GetEventResultModel> > GetFreeTimes(CalendarService service, FtmCalendarInfo[] calendars, DateTime startDateTime, DateTime endDateTime, double time)
        {
            try
            {
                var inTime    = time.DoubleToTimeSpam();
                var resultDic = GetDateRangeRequest <List <GetEventResultModel> >(startDateTime, endDateTime);

                #region Get time work in config

                var startTimeInDayConfig = configuration["Settings:StartTimeInDay"];
                var endTimeInDayConfig   = configuration["Settings:EndTimeInDay"];
                startTimeInDay = TimeSpan.TryParse(startTimeInDayConfig, out startTimeInDay) ? startTimeInDay : new TimeSpan(7, 0, 0);
                endTimeInDay   = TimeSpan.TryParse(endTimeInDayConfig, out endTimeInDay) ? endTimeInDay : new TimeSpan(20, 0, 0);

                #endregion Get time work in config

                foreach (var calendar in calendars)
                {
                    EventsResource.ListRequest request = service.Events.List(calendar.CalendarId);
                    request.TimeMin      = startDateTime;
                    request.TimeMax      = endDateTime;
                    request.ShowDeleted  = false;
                    request.SingleEvents = true;
                    request.MaxResults   = 999;
                    request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;
                    Events events = await request.ExecuteAsync();

                    var itemDic = events.Items.GroupBy(x => x.Start.DateTime.Value.Date, x => x).ToDictionary(x => x.Key, x => x.ToList());

                    #region Check day hasn't any event

                    var dateDic = GetDateRangeRequest <List <Event> >(startDateTime, endDateTime);
                    foreach (var key in itemDic.Keys)
                    {
                        dateDic[key] = itemDic[key];
                    }

                    foreach (var dateKey in dateDic.Keys)
                    {
                        if (dateDic[dateKey].Count == 0)
                        {
                            resultDic[dateKey].Add(new GetEventResultModel()
                            {
                                CalendarId   = calendar.CalendarId,
                                CalendarName = itemDic.Any() ? events.Items.FirstOrDefault()?.Organizer?.DisplayName : calendar.CalendarName,
                                StartTime    = dateKey.CreateTime(startTimeInDay),
                                EndTime      = dateKey.CreateTime(endTimeInDay),
                                HtmlLink     = $"{baseLink}{dateKey.CreateLinkParam()}"
                            });
                        }
                    }

                    #endregion Check day hasn't any event

                    foreach (var key in itemDic.Keys)
                    {
                        var listEventByDay = itemDic[key];

                        for (var index = 0; index < listEventByDay.Count(); index++)
                        {
                            if (CheckEvent(index, listEventByDay, out List <GetEventResultModel> result))
                            {
                                if (resultDic.TryGetValue(key, out List <GetEventResultModel> dicResult))
                                {
                                    dicResult.AddRange(result.Where(x => (x.EndTime - x.StartTime) >= inTime).ToArray());
                                }
                            }
                        }
                    }
                }

                return(resultDic.Values.SelectMany(x => x));
            }
            catch
            {
                throw;
            }
        }