const http = require('http') const ical = require('ical') function createEventEntry (event) { const content = document.createElement('p') const entry = document.createElement('div') const formatDate = Intl.DateTimeFormat('fr', { dateStyle: 'long', timeStyle: 'short' }).format const header = document.createElement('h3') content.innerHTML = event.location header.textContent = formatDate(event.date) + ' | ' + event.summary entry.className = 'event-entry' entry.setAttribute('entry-time', event.date.getTime()) entry.appendChild(header) entry.appendChild(content) return entry } function createLoader (target) { const message = document.createElement('p') const spinner = document.createElement('div') const wrapper = document.createElement('div') wrapper.className = 'loader-wrapper' message.innerHTML = 'Chargement du calendrier...' wrapper.appendChild(spinner) wrapper.appendChild(message) target.insertBefore(wrapper, target.firstChild) } function sortEvents (events) { const sorted = [] /* First extract the events. */ Object.values(events).forEach(event => { if (event.type === 'VEVENT') { sorted.push({ date: event.start, location: event.location, summary: event.summary }) } }) /* Then sort them out. */ // TODO: Useless here. Should be done on callbacks below return sorted.sort((a, b) => { return a.date < b.date }) } function loadEvents (cb) { http.request({ host: 'www.ti-nuage.fr', path: '/donnees/calendrier.php' }, function (response) { let str = '' response.on('data', function (chunk) { str += chunk }) response.on('end', function () { const events = sortEvents(ical.parseICS(str)) cb(events) }) }).end() } module.exports = { fill: function (target) { loadEvents(events => { events.forEach(event => { target.appendChild(createEventEntry(event)) }) }) }, mergeWithNews: function (target) { const blogElements = target.getElementsByClassName('blog-entry') const entries = {} const accumulate = function (index, item) { if (!entries.hasOwnProperty(index)) { entries[index] = [] } entries[index].push(item) } for (let i = 0; i < blogElements.length; ++i) { const item = blogElements.item(i) accumulate(item.getAttribute('entry-time'), item) } createLoader(target) loadEvents(events => { const now = Date.now() const limitTime = now + (30 * 24 * 60 * 60 * 1000) target.innerHTML = '' /* Build calendar entries, keeping only the ones for the next 30 days */ events.forEach(event => { const eventTime = event.date.getTime() console.log(event) if (eventTime >= now && eventTime < limitTime) { accumulate(eventTime, createEventEntry(event)) } }) Object.keys(entries).sort(function (a, b) { return a < b }).forEach(time => { entries[time].forEach(entry => { target.appendChild(entry) }) }) }) } }