Beispiel #1
0
        public async void Run(object state)
        {
            var response = await _client.GetAsync(_options.Value.UpstreamICalUrl);

            response.EnsureSuccessStatusCode();

            var stream = await response.Content.ReadAsStreamAsync();

            var calendars = CalendarCollection.Load(stream);
            var calendar  = calendars.FirstOrDefault();

            if (calendar is null)
            {
                _logger.LogWarning("Calendar is empty. Skipping sync");
                return;
            }

            // Add or update events
            var upstreamCalendarEvents = calendar.Events.OrderBy(x => x.Start).ToList();

            foreach (var calendarEvent in upstreamCalendarEvents)
            {
                var entry = _mapper.Map <CalendarEventEntity>(calendarEvent);
                entry.Source = _options.Value.UpstreamICalUrl;

                await _calendarService.AddOrUpdateCalendarEntryAsync(entry);
            }

            // Purge obsolete events
            var events           = (await _calendarService.GetAllEventsAsync()).ToList();
            var obsoleteEventIds = events.Where(x => x.Source == _options.Value.UpstreamICalUrl)
                                   .Select(x => x.Id)
                                   .Except(upstreamCalendarEvents
                                           .Select(x => x.Uid));

            // TODO: Add tests
            foreach (var obsoleteEventId in obsoleteEventIds)
            {
                await _calendarService.RemoveEventAsync(obsoleteEventId);
            }

            _logger.LogInformation("Synchronized calendar from upstream source ({UpstreamSourceUrl})",
                                   _options.Value.UpstreamICalUrl);
        }