usrspace-browser-addon/background/index.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-12-27 10:37:31 +01:00
const fetchJson = (url) => {
return fetch(url).then((response) => (response.json()));
};
const fetchCalendar = (days = null) => {
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});
}
badgeText.then(() => {
}).catch((error) => {
console.error(error);
});
badgeColor.then(() => {
}).catch((error) => {
console.error(error);
});
};
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);
});
};
fetchNewData();
setInterval(() => {
fetchNewData();
2018-12-27 15:16:18 +01:00
}, Config.refreshTimeout);