Marc Kupietz | 9ae184c | 2023-11-04 18:21:54 +0100 | [diff] [blame] | 1 | async function getCalendar(icalUrl) { |
| 2 | const response = await fetch(icalUrl); |
| 3 | const data = await response.text(); |
| 4 | return data; |
| 5 | } |
| 6 | |
| 7 | function 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 | |
| 18 | function insertCalendarEvents(dlElement, icalUrl, maxAgeDays = 1) { |
| 19 | |
| 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'); |
| 64 | const description = document.createTextNode(start.format("HH:mm") + "-" + end.format("HH:mm") + ` ${summary}`); |
| 65 | dd.appendChild(description); |
| 66 | element.appendChild(dd); |
| 67 | }); |
| 68 | } |
| 69 | ).catch(error => { |
| 70 | console.log(error); |
| 71 | }); |
| 72 | } |