2019-12-02 15:53:24 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# Import all events from a given remote RFC 5545 iCalendar
|
|
|
|
class ICalendarImportService
|
|
|
|
def import(i_calendar_id)
|
|
|
|
require 'net/http'
|
|
|
|
require 'uri'
|
|
|
|
require 'icalendar'
|
|
|
|
|
2019-12-03 12:16:07 +01:00
|
|
|
uids = []
|
2019-12-02 15:53:24 +01:00
|
|
|
|
|
|
|
i_cal = ICalendar.find(i_calendar_id)
|
|
|
|
ics = Net::HTTP.get(URI.parse(i_cal.url))
|
|
|
|
cals = Icalendar::Calendar.parse(ics)
|
|
|
|
|
2019-12-03 12:16:07 +01:00
|
|
|
# create new events and update existings
|
2019-12-02 15:53:24 +01:00
|
|
|
cals.each do |cal|
|
|
|
|
cal.events.each do |evt|
|
2019-12-03 12:16:07 +01:00
|
|
|
uids.push(evt.uid.to_s)
|
|
|
|
ICalendarEvent.update_or_create_by(
|
|
|
|
{ uid: evt.uid.to_s },
|
|
|
|
{
|
|
|
|
dtstart: evt.dtstart,
|
|
|
|
dtend: evt.dtend,
|
|
|
|
summary: evt.summary,
|
|
|
|
description: evt.description,
|
|
|
|
i_calendar_id: i_calendar_id
|
|
|
|
}
|
2019-12-02 15:53:24 +01:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
2019-12-03 12:16:07 +01:00
|
|
|
# remove deleted events
|
|
|
|
ICalendarEvent.where(i_calendar_id: i_calendar_id).where.not(uid: uids).destroy_all
|
2019-12-02 15:53:24 +01:00
|
|
|
end
|
|
|
|
end
|