function fetchJson(url) { return fetch(url).then((response) => (response.json())); } function fetchCalendar(days = 28) { let url = `${Config.calenderUrl}?o=json`; if (days) { url += `&r=${days}`; } return fetchJson(url); } function fetchSpaceApi() { return fetchJson(Config.spaceApiUrl); } async function updateBadge(open) { let badgeText, badgeColor; if (open) { badgeText = browser.browserAction.setBadgeText({text: 'open'}); badgeColor = browser.browserAction.setBadgeBackgroundColor({color: Config.openColor}); } else { badgeText = browser.browserAction.setBadgeText({text: ''}); badgeColor = browser.browserAction.setBadgeBackgroundColor({color: null}); } try { await Promise.all([badgeText, badgeColor]); } catch (error) { console.error(error); } } function sendNotification(open) { browser.notifications.create('status-change', { type: 'basic', title: 'Space Status', message: `Space ist jetzt ${open ? 'offen' : 'geschlossen'}.`, iconUrl: browser.runtime.getURL('icons/favicon.svg') }); } async function fetchNewData() { try { const json = await fetchCalendar(); window.calendar = json; } catch (error) { console.error(error); } try { const json = await fetchSpaceApi(); if (window.spaceApi && window.spaceApi.state.open !== json.state.open) { sendNotification(json.state.open) } window.spaceApi = json; updateBadge(window.spaceApi.state.open); } 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(); }