blob: e5aa05dc618520ebdcd9b291a84f3d56c44271fd [file] [log] [blame]
Marc Kupietz9ae184c2023-11-04 18:21:54 +01001async function getCalendar(icalUrl) {
2 const response = await fetch(icalUrl);
3 const data = await response.text();
4 return data;
5}
6
7function getDateFromjCal(jCal, event, name) {
8 const date = event.getFirstPropertyValue(name);
9 const vtimezone = jCal.getFirstSubcomponent('vtimezone');
10 if (vtimezone && moment(date.toJSDate()).utcOffset()) {
11 date.zone = new ICAL.Timezone(vtimezone);
12 }
13 var locale = window.navigator.userLanguage || window.navigator.language;
14 moment.locale(locale);
15 return moment.parseZone(date.toJSDate()).utcOffset(date.utcOffset() / 60)
16};
17
Marc Kupietz4df55332024-04-05 09:55:56 +020018function insertCalendarEvents(dlElement, icalUrl, maxAgeDays = 100) {
Marc Kupietz9ae184c2023-11-04 18:21:54 +010019
20 if (!icalUrl) {
21 return;
22 }
23
24 getCalendar(icalUrl).then(data => {
25 // console.log(data);
26 var jcalData = ICAL.parse(data);
27 var vcalendar = new ICAL.Component(jcalData);
28 ICAL.helpers.updateTimezones(vcalendar, ICAL.TimezoneService);
29 const element = dlElement;
30
31 var events = vcalendar.getAllSubcomponents('vevent');
32 var eventArray = [];
33 var eventKeys = [];
34 var now = moment();
35 events.forEach(event => {
36 var start = getDateFromjCal(vcalendar, event, 'dtstart');
37 if (now.diff(start, 'days') <= maxAgeDays) {
38 var key = event.getFirstPropertyValue("dtstart") + "-" + event.getFirstPropertyValue("dtend");
39 eventArray[key] = event;
40 eventKeys.push(key);
41 }
42 });
43 dlElement.replaceChildren();
44 if (eventKeys.length == 0) {
45 const dd = document.createElement('dd');
46 dd.appendChild(document.createTextNode("–"));
47 element.appendChild(dd);
48 return;
49 }
50 eventKeys.sort().reverse().forEach(key => {
51 var event = eventArray[key];
52 var summary = event.getFirstPropertyValue('summary');
53 var start = getDateFromjCal(vcalendar, event, 'dtstart');
54 var end = getDateFromjCal(vcalendar, event, 'dtend');
55 const dt = document.createElement('dt');
56 const time = document.createElement('time');
57 dt.setAttribute('class', 'maintenance');
58 const node = document.createTextNode(start.format('dddd, LL'));
59 time.appendChild(node);
60 time.setAttribute('datetime', start.format('YYYY-MM-DD'));
61 dt.appendChild(time);
62 element.appendChild(dt);
63 const dd = document.createElement('dd');
Marc Kupietz6c4f1372024-04-05 10:59:35 +020064 dd.innerHTML = start.format("HH:mm") + "-" + end.format("HH:mm") + ` ${summary}`;
Marc Kupietz9ae184c2023-11-04 18:21:54 +010065 element.appendChild(dd);
66 });
67 }
68 ).catch(error => {
69 console.log(error);
70 });
71}