import { useEffect, useState, useRef } from 'preact/hooks' import axios from 'axios' import ICAL from 'ical.js' import config from '../data/config' export const useEventStream = () => { const [data, setData] = useState([]) const [loading, setLoading] = useState(true) async function fetchData() { setLoading(true) const { data: responseData } = await axios.get( `https://cloud.undersco.re/remote.php/dav/public-calendars/${config.calendarId}/?export` ) const jCalData = ICAL.parse(responseData) const comp = new ICAL.Component(jCalData) const vevents = comp.getAllSubcomponents('vevent') const calEvents = vevents .filter( vevent => vevent.getFirstPropertyValue('status') === null || (vevent.getFirstPropertyValue('status') && vevent.getFirstPropertyValue('status').toUpperCase() === 'CONFIRMED') ) .map(vevent => { const event = new ICAL.Event(vevent) return event }) .sort((a, b) => a.startDate.toJSDate() - b.startDate.toJSDate()) await Promise.all( calEvents.map(async calItem => { const url = calItem.component.getAllProperties('url')[0] if (url) { const id = url .getFirstValue() .split('/') .pop() const { data: { account, category, channel, embedPath, language, state, previewPath, views, duration, }, } = await axios.get(`https://tv.undersco.re/api/v1/videos/${id}`) const item = { title: calItem.summary, account, category, channel, description: calItem.description, embedPath, language, state, previewPath, views, start: calItem.startDate.toJSDate(), end: calItem.endDate.toJSDate(), id, duration, videoUrl: url.getFirstValue(), } setData(arr => [...arr, item]) } else { const item = { title: calItem.summary, description: calItem.description, start: calItem.startDate.toJSDate(), end: calItem.endDate.toJSDate(), } setData(arr => [...arr, item]) } }) ) setLoading(false) } useEffect(() => { fetchData() }, []) return { loading, data } }