metis/src/calendar.js

100 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-02-20 19:16:33 +01:00
import ICAL from 'ical.js';
2022-02-20 22:29:15 +01:00
const calendars = {
"5WrcagPPARQ3BD87": {
name: "Club réseau",
color: null
},
"TFEAKjAgNFQZpNjo": {
name: "hackENS",
color: null
}
};
export const calendarTree = {
"COF": [
"Club réseau",
"hackENS"
]
};
const calendarIds = Object.keys(calendars);
2022-02-20 19:16:33 +01:00
function mkCalendarUrl(id) {
return `/cal/${id}/?export&accept=jcal`;
}
function fetchCalendar(id) {
return fetch(mkCalendarUrl(id), { credentials: 'omit' }).then(resp => resp.json()).catch(err => console.error(err));
}
class Calendar {
2022-02-20 22:29:15 +01:00
constructor (id, calendar) {
const metadata = calendars[id];
this.name = metadata.name;
this.color = metadata.color || calendar[1][4][3];
2022-02-20 19:16:33 +01:00
this.events = calendar[2].filter(item => item[0] === 'vevent').map(item => this._parse_vevent(item[1]));
}
_parse_vevent(vevent) {
const event = {};
vevent.forEach(elt => {
event[elt[0]] = elt[3];
});
return event;
}
}
2022-02-20 22:29:15 +01:00
function fcEventFromjCalEvent(cal) {
return function (evt) {
const start = new Date(evt.dtstart);
const end = new Date(evt.dtend);
const fcEvent = {
title: `${cal.name}: ${evt.summary}`,
start,
color: cal.color,
duration: end - start // in ms
};
if (evt.description) {
fcEvent.description = evt.description;
}
if (evt.rrule) {
const { freq, byday } = evt.rrule;
fcEvent.rrule = {
freq,
byweekday: byday,
dtstart: evt.dtstart,
};
}
return fcEvent;
}
}
2022-02-20 19:16:33 +01:00
function mkEventsFromCalendar(id) {
return fetchCalendar(id).then(calendar => {
if (calendar[0] !== 'vcalendar') return;
2022-02-20 22:29:15 +01:00
const cal = new Calendar(id, calendar)
return cal.events.map(fcEventFromjCalEvent(cal))
2022-02-20 19:16:33 +01:00
});
}
export function mkEvent(title, start, duration, ...rest) {
start = new Date(start)
const end = new Date(start)
end.setMinutes(start.getMinutes() + duration)
return {
title,
start,
end,
...rest
}
}
2022-02-20 22:29:15 +01:00
// TODO: move to FullCalendar custom fetcher to control start&end.
export function refreshEvents(selectedCalendars) {
return Promise.all(calendarIds.filter(id => selectedCalendars ? selectedCalendars.includes(id) : true).map(mkEventsFromCalendar))
2022-02-20 19:16:33 +01:00
}