usrspace-browser-addon/background/index.js

88 lines
1.9 KiB
JavaScript
Raw Normal View History

function fetchJson(url) {
2021-09-22 21:04:32 +02:00
return fetch(url).then((response) => (response.json()));
}
2018-12-27 10:37:31 +01:00
function fetchCalendar(days = 28) {
2021-09-22 21:36:54 +02:00
let url = `${Config.calenderUrl}?o=json`;
2021-09-22 21:04:32 +02:00
if (days) {
2021-09-22 21:36:54 +02:00
url += `&r=${days}`;
2021-09-22 21:04:32 +02:00
}
return fetchJson(url);
}
2018-12-27 10:37:31 +01:00
function fetchSpaceApi() {
2021-09-22 21:04:32 +02:00
return fetchJson(Config.spaceApiUrl);
}
2018-12-27 10:37:31 +01:00
async function updateBadge(open) {
2021-09-22 21:04:32 +02:00
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);
}
}
2018-12-27 10:37:31 +01:00
function sendNotification(open) {
2021-09-23 02:28:20 +02:00
browser.notifications.create('status-change', {
2021-09-22 21:04:32 +02:00
type: 'basic',
title: 'Space Status',
2021-09-23 02:28:20 +02:00
message: `Space ist jetzt ${open ? 'offen' : 'geschlossen'}.`,
iconUrl: browser.runtime.getURL('icons/favicon.svg')
2021-09-22 21:04:32 +02:00
});
}
2018-12-27 20:34:05 +01:00
async function fetchNewData() {
try {
const json = await fetchCalendar();
2021-09-22 21:04:32 +02:00
window.calendar = json;
} catch (error) {
2021-09-22 21:04:32 +02:00
console.error(error);
}
2018-12-27 10:37:31 +01:00
try {
const json = await fetchSpaceApi();
2021-09-22 21:04:32 +02:00
if (window.spaceApi && window.spaceApi.state.open !== json.state.open) {
sendNotification(json.state.open)
}
window.spaceApi = json;
updateBadge(window.spaceApi.state.open);
} catch (error) {
2021-09-22 21:04:32 +02:00
console.error(error);
}
}
2018-12-27 10:37:31 +01:00
let intervalHandler = null;
function stopFetching() {
2021-09-22 21:04:32 +02:00
if (intervalHandler !== null) {
clearInterval(intervalHandler);
intervalHandler = null;
}
}
function startFetching() {
2021-09-22 21:04:32 +02:00
fetchNewData();
if (intervalHandler === null) {
intervalHandler = setInterval(() => {
fetchNewData();
}, Config.refreshTimeout);
}
}
window.addEventListener('offline', () => {
2021-09-22 21:04:32 +02:00
stopFetching();
});
window.addEventListener('online', () => {
2021-09-22 21:04:32 +02:00
startFetching();
});
if (window.navigator.onLine) {
2021-09-22 21:04:32 +02:00
startFetching();
}