import Config from "./config.js"; /** * @param {string} url * @returns {Promise} */ async function fetchJson(url) { const response = await fetch(url); return response.json(); } /** * @param {number} days * @returns {Promise} */ function fetchCalendar(days = 28) { let url = `${Config.calenderUrl}?o=json`; if (days) { url += `&r=${days}`; } return fetchJson(url); } /** * @returns {Promise} */ function fetchSpaceApi() { return fetchJson(Config.spaceApiUrl); } async function fetchNewData() { try { const result = await Promise.allSettled([fetchCalendar(), fetchSpaceApi()]); const calendarJson = result[0].value; const spaceApiJson = result[1].value; if (spaceApiJson) { const now = new Date(); const eventActive = calendarJson?.some((event) => ( new Date(event.begin) <= now && now <= new Date(event.end) )) ?? false; const badgeText = browser.i18n.getMessage(spaceApiJson.state.open ? 'badgeOpen' : eventActive ? 'badgeEvent' : 'badgeClosed'); const badgeBgColor = spaceApiJson.state.open ? Config.openColor : eventActive ? Config.eventColor : Config.closedColor; await browser.browserAction.setBadgeText({text: badgeText}); await browser.browserAction.setBadgeBackgroundColor({color: badgeBgColor}); if (window.spaceApi && window.spaceApi.state.open !== spaceApiJson.state.open) { const state = browser.i18n.getMessage(spaceApiJson.state.open ? 'open' : 'closed'); await browser.notifications.create('status-change', { type: 'basic', title: browser.i18n.getMessage('stateNotificationTitle'), message: browser.i18n.getMessage('stateNotificationMessage', state), iconUrl: browser.runtime.getURL('icons/favicon.svg') }); } } window.calendar = calendarJson; window.spaceApi = spaceApiJson; } catch (error) { console.error(error); } } let intervalHandler = null; function stopFetching() { if (intervalHandler !== null) { clearInterval(intervalHandler); intervalHandler = null; } } function startFetching() { fetchNewData(); if (intervalHandler === null) { intervalHandler = setInterval(() => { fetchNewData(); }, Config.refreshTimeout); } } window.addEventListener('offline', () => { stopFetching(); }); window.addEventListener('online', () => { startFetching(); }); if (window.navigator.onLine) { startFetching(); }