improve code

This commit is contained in:
Thomas Rupprecht 2022-12-24 15:21:06 +01:00
parent d898b1ea2a
commit 2f5e6ecdb1
1 changed files with 18 additions and 40 deletions

View File

@ -11,7 +11,7 @@ async function fetchJson(url) {
/**
* @param {number} days
* @returns {Promise<any>}
* @returns {Promise<object>}
*/
function fetchCalendar(days = 28) {
let url = `${Config.calenderUrl}?o=json`;
@ -22,58 +22,36 @@ function fetchCalendar(days = 28) {
}
/**
* @returns {Promise<any>}
* @returns {Promise<object>}
*/
function fetchSpaceApi() {
return fetchJson(Config.spaceApiUrl);
}
/**
* @param {boolean} open
*/
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);
}
}
/**
* @param {boolean} open
*/
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;
const calendarJson = await fetchCalendar();
window.calendar = calendarJson;
} catch (error) {
console.error(error);
}
try {
const json = await fetchSpaceApi();
if (window.spaceApi && window.spaceApi.state.open !== json.state.open) {
sendNotification(json.state.open)
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) {
await browser.notifications.create('status-change', {
type: 'basic',
title: 'Space Status',
message: `Space ist jetzt ${spaceApiJson.state.open ? 'offen' : 'geschlossen'}.`,
iconUrl: browser.runtime.getURL('src/icons/favicon.svg')
});
}
window.spaceApi = json;
updateBadge(window.spaceApi.state.open);
window.spaceApi = spaceApiJson;
} catch (error) {
console.error(error);
}