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 calendarJson = await fetchCalendar(); window.calendar = calendarJson; } catch (error) { console.error(error); } try { const spaceApiJson = await fetchSpaceApi(); await browser.browserAction.setBadgeBackgroundColor({color: Config.openColor}); await browser.browserAction.setBadgeText({text: spaceApiJson.state.open ? 'open' : ''}); 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('src/icons/favicon.svg') }); } 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(); }