usrspace-browser-addon/background/index.js

86 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-12-27 10:37:31 +01:00
const fetchJson = (url) => {
return fetch(url).then((response) => (response.json()));
};
2020-04-20 19:29:10 +02:00
const fetchCalendar = (days = 28) => {
2018-12-27 15:16:18 +01:00
let url = Config.calenderUrl + '?o=json';
2018-12-27 10:37:31 +01:00
if (days) {
url += '&r=' + days;
}
return fetchJson(url);
};
const fetchSpaceApi = () => {
2018-12-27 15:16:18 +01:00
return fetchJson(Config.spaceApiUrl);
2018-12-27 10:37:31 +01:00
};
const updateBadge = (open) => {
let badgeText, badgeColor;
if (open) {
badgeText = browser.browserAction.setBadgeText({text: 'open'});
2018-12-27 15:16:18 +01:00
badgeColor = browser.browserAction.setBadgeBackgroundColor({color: Config.openColor});
2018-12-27 10:37:31 +01:00
} else {
badgeText = browser.browserAction.setBadgeText({text: ''});
badgeColor = browser.browserAction.setBadgeBackgroundColor({color: null});
}
2019-08-28 21:50:01 +02:00
Promise.all([badgeText, badgeColor])
.then()
.catch((error) => {
console.error(error);
});
2018-12-27 10:37:31 +01:00
};
2018-12-27 20:34:05 +01:00
const sendNotification = (open) => {
browser.notifications.create('notification-id', {
type: 'basic',
iconUrl: browser.runtime.getURL('icons/logo.svg'),
title: 'Space Status',
message: 'Space ist jetzt ' + (open ? 'offen' : 'geschlossen') + '.'
});
};
2018-12-27 10:37:31 +01:00
const fetchNewData = () => {
fetchCalendar().then((json) => {
window.calendar = json;
}).catch((error) => {
console.error(error);
});
fetchSpaceApi().then((json) => {
2018-12-27 20:36:43 +01:00
if (window.spaceApi && window.spaceApi.state.open !== json.state.open) {
2018-12-27 20:34:05 +01:00
sendNotification(json.state.open)
}
2018-12-27 10:37:31 +01:00
window.spaceApi = json;
updateBadge(window.spaceApi.state.open);
}).catch((error) => {
console.error(error);
});
};
let intervalHandler = null;
const stopFetching = () => {
if (intervalHandler !== null) {
clearInterval(intervalHandler);
intervalHandler = null;
}
};
const startFetching = () => {
2018-12-27 10:37:31 +01:00
fetchNewData();
if (intervalHandler === null) {
intervalHandler = setInterval(() => {
fetchNewData();
}, Config.refreshTimeout);
}
};
window.addEventListener('offline', () => {
stopFetching();
});
window.addEventListener('online', () => {
startFetching();
});
if (window.navigator.onLine) {
startFetching();
}