mirror of
https://github.com/MichMich/MagicMirror.git
synced 2025-08-21 04:45:17 +00:00
Release 2.26.0 (#3319)
## [2.26.0] - 01-01-2024 Thanks to: @bnitkin, @bugsounet, @dependabot, @jkriegshauser, @kaennchenstruggle, @KristjanESPERANTO and @Ybbet. Special thanks to @khassel, @rejas and @sdetweil for taking over most (if not all) of the work on this release as project collaborators. This version would not be there without their effort. Thank you guys! You are awesome! This release also marks the latest release by Michael Teeuw. For more info, please read the following post: [A New Chapter for MagicMirror: The Community Takes the Lead](https://forum.magicmirror.builders/topic/18329/a-new-chapter-for-magicmirror-the-community-takes-the-lead). ### Added - Added update notification updater (for 3rd party modules) - Added node 21 to the test matrix - Added transform object to calendar:customEvents - Added ESLint rules for jest (including jest/expect-expect and jest/no-done-callback) ### Removed - Removed Codecov workflow (not working anymore, other workflow required) (#3107) - Removed titleReplace from calendar, replaced + extended by customEvents (backward compatibility included) (#3249) - Removed failing unit test (#3254) - Removed some unused variables ### Updated - Update electron to v27 and update other dependencies as well as github actions - Update newsfeed: Use `html-to-text` instead of regex for transform description - Review ESLint config (#3269) - Updated dependencies - Clock module: optionally display current moon phase in addition to rise/set times - electron is now per default started without gpu, if needed it must be enabled with new env var `ELECTRON_ENABLE_GPU=1` on startup (#3226) - Replace prettier by stylistic in ESLint config to lint JavaScript (and disable some rules for `config/config.js*` files) - Update node-ical to v0.17.1 and fix tests ### Fixed - Avoid fade out/in on updateDom when many calendars are used - Fix the option eventClass on customEvents. - Fix yr API version in locationforecast and sunrise call (#3227) - Fix cloneObject() function to respect RegExp (#3237) - Fix newsfeed module for feeds using "a10:updated" tag (#3238) - Fix issue template (#3167) - Fix #3256 filter out bad results from rrule.between - Fix calendar events sometimes not respecting deleted events (#3250) - Fix electron loadurl locally on Windows when address "0.0.0.0" (#2550) - Fix updatanotification (update_helper.js): catch error if reponse is not an JSON format (check PM2) - Fix missing typeof in calendar module - Fix style issues after prettier update - Fix calendar test (#3291) by moving "Exdate check" from e2e to electron to run on a Thursday - Fix calendar config params `fetchInterval` and `excludedEvents` were never used from single calendar config (#3297) - Fix MM_PORT variable not used in electron and allow full path for MM_CONFIG_FILE variable (#3302) --------- Signed-off-by: naveen <172697+naveensrinivasan@users.noreply.github.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Karsten Hassel <hassel@gmx.de> Co-authored-by: Malte Hallström <46646495+SkySails@users.noreply.github.com> Co-authored-by: Veeck <github@veeck.de> Co-authored-by: veeck <michael@veeck.de> Co-authored-by: dWoolridge <dwoolridge@charter.net> Co-authored-by: Johan <jojjepersson@yahoo.se> Co-authored-by: Dario Mratovich <dario_mratovich@hotmail.com> Co-authored-by: Dario Mratovich <dario.mratovich@outlook.com> Co-authored-by: Magnus <34011212+MagMar94@users.noreply.github.com> Co-authored-by: Naveen <172697+naveensrinivasan@users.noreply.github.com> Co-authored-by: buxxi <buxxi@omfilm.net> Co-authored-by: Thomas Hirschberger <47733292+Tom-Hirschberger@users.noreply.github.com> Co-authored-by: Kristjan ESPERANTO <35647502+KristjanESPERANTO@users.noreply.github.com> Co-authored-by: Andrés Vanegas Jiménez <142350+angeldeejay@users.noreply.github.com> Co-authored-by: Dave Child <dave@addedbytes.com> Co-authored-by: grenagit <46225780+grenagit@users.noreply.github.com> Co-authored-by: Grena <grena@grenabox.fr> Co-authored-by: Magnus Marthinsen <magmar@online.no> Co-authored-by: Patrick <psieg@users.noreply.github.com> Co-authored-by: Piotr Rajnisz <56397164+rajniszp@users.noreply.github.com> Co-authored-by: Suthep Yonphimai <tomzt@users.noreply.github.com> Co-authored-by: CarJem Generations (Carter Wallace) <cwallacecs@gmail.com> Co-authored-by: Nicholas Fogal <nfogal.misc@gmail.com> Co-authored-by: JakeBinney <126349119+JakeBinney@users.noreply.github.com> Co-authored-by: OWL4C <124401812+OWL4C@users.noreply.github.com> Co-authored-by: Oscar Björkman <17575446+oscarb@users.noreply.github.com> Co-authored-by: Ismar Slomic <ismar@slomic.no> Co-authored-by: Jørgen Veum-Wahlberg <jorgen.wahlberg@amedia.no> Co-authored-by: Eddie Hung <6740044+eddiehung@users.noreply.github.com> Co-authored-by: Bugsounet - Cédric <github@bugsounet.fr> Co-authored-by: bugsounet <bugsounet@bugsounet.fr> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Knapoc <Knapoc@users.noreply.github.com> Co-authored-by: sam detweiler <sdetweil@gmail.com> Co-authored-by: veeck <michael.veeck@nebenan.de> Co-authored-by: Paranoid93 <6515818+Paranoid93@users.noreply.github.com> Co-authored-by: NolanKingdon <27908974+NolanKingdon@users.noreply.github.com> Co-authored-by: J. Kenzal Hunter <kenzal.hunter@gmail.com> Co-authored-by: Teddy <teddy.payet@gmail.com> Co-authored-by: TeddyStarinvest <teddy.payet@starinvest.com> Co-authored-by: martingron <61826403+martingron@users.noreply.github.com> Co-authored-by: dgoth <132394363+dgoth@users.noreply.github.com> Co-authored-by: kaennchenstruggle <54073894+kaennchenstruggle@users.noreply.github.com> Co-authored-by: jkriegshauser <jkriegshauser@gmail.com> Co-authored-by: Ben Nitkin <ben@nitkin.net>
This commit is contained in:
@@ -17,15 +17,15 @@ Module.register("alert", {
|
||||
welcome_message: false // shown at startup
|
||||
},
|
||||
|
||||
getScripts() {
|
||||
getScripts () {
|
||||
return ["notificationFx.js"];
|
||||
},
|
||||
|
||||
getStyles() {
|
||||
return ["font-awesome.css", this.file(`./styles/notificationFx.css`), this.file(`./styles/${this.config.position}.css`)];
|
||||
getStyles () {
|
||||
return ["font-awesome.css", this.file("./styles/notificationFx.css"), this.file(`./styles/${this.config.position}.css`)];
|
||||
},
|
||||
|
||||
getTranslations() {
|
||||
getTranslations () {
|
||||
return {
|
||||
bg: "translations/bg.json",
|
||||
da: "translations/da.json",
|
||||
@@ -40,11 +40,11 @@ Module.register("alert", {
|
||||
};
|
||||
},
|
||||
|
||||
getTemplate(type) {
|
||||
getTemplate (type) {
|
||||
return `templates/${type}.njk`;
|
||||
},
|
||||
|
||||
async start() {
|
||||
async start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
|
||||
if (this.config.effect === "slide") {
|
||||
@@ -57,7 +57,7 @@ Module.register("alert", {
|
||||
}
|
||||
},
|
||||
|
||||
notificationReceived(notification, payload, sender) {
|
||||
notificationReceived (notification, payload, sender) {
|
||||
if (notification === "SHOW_ALERT") {
|
||||
if (payload.type === "notification") {
|
||||
this.showNotification(payload);
|
||||
@@ -69,7 +69,7 @@ Module.register("alert", {
|
||||
}
|
||||
},
|
||||
|
||||
async showNotification(notification) {
|
||||
async showNotification (notification) {
|
||||
const message = await this.renderMessage(notification.templateName || "notification", notification);
|
||||
|
||||
new NotificationFx({
|
||||
@@ -80,7 +80,7 @@ Module.register("alert", {
|
||||
}).show();
|
||||
},
|
||||
|
||||
async showAlert(alert, sender) {
|
||||
async showAlert (alert, sender) {
|
||||
// If module already has an open alert close it
|
||||
if (this.alerts[sender.name]) {
|
||||
this.hideAlert(sender, false);
|
||||
@@ -113,7 +113,7 @@ Module.register("alert", {
|
||||
}
|
||||
},
|
||||
|
||||
hideAlert(sender, close = true) {
|
||||
hideAlert (sender, close = true) {
|
||||
// Dismiss alert and remove from this.alerts
|
||||
if (this.alerts[sender.name]) {
|
||||
this.alerts[sender.name].dismiss(close);
|
||||
@@ -125,7 +125,7 @@ Module.register("alert", {
|
||||
}
|
||||
},
|
||||
|
||||
renderMessage(type, data) {
|
||||
renderMessage (type, data) {
|
||||
return new Promise((resolve) => {
|
||||
this.nunjucksEnvironment().render(this.getTemplate(type), data, function (err, res) {
|
||||
if (err) {
|
||||
@@ -137,7 +137,7 @@ Module.register("alert", {
|
||||
});
|
||||
},
|
||||
|
||||
toggleBlur(add = false) {
|
||||
toggleBlur (add = false) {
|
||||
const method = add ? "add" : "remove";
|
||||
const modules = document.querySelectorAll(".module");
|
||||
for (const module of modules) {
|
||||
|
@@ -12,13 +12,14 @@
|
||||
* @param {object} window The window object
|
||||
*/
|
||||
(function (window) {
|
||||
|
||||
/**
|
||||
* Extend one object with another one
|
||||
* @param {object} a The object to extend
|
||||
* @param {object} b The object which extends the other, overwrites existing keys
|
||||
* @returns {object} The merged object
|
||||
*/
|
||||
function extend(a, b) {
|
||||
function extend (a, b) {
|
||||
for (let key in b) {
|
||||
if (b.hasOwnProperty(key)) {
|
||||
a[key] = b[key];
|
||||
@@ -32,7 +33,7 @@
|
||||
* @param {object} options The configuration options
|
||||
* @class
|
||||
*/
|
||||
function NotificationFx(options) {
|
||||
function NotificationFx (options) {
|
||||
this.options = extend({}, this.options);
|
||||
extend(this.options, options);
|
||||
this._init();
|
||||
@@ -63,10 +64,10 @@
|
||||
ttl: 6000,
|
||||
al_no: "ns-box",
|
||||
// callbacks
|
||||
onClose: function () {
|
||||
onClose () {
|
||||
return false;
|
||||
},
|
||||
onOpen: function () {
|
||||
onOpen () {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -78,7 +79,7 @@
|
||||
// create HTML structure
|
||||
this.ntf = document.createElement("div");
|
||||
this.ntf.className = `${this.options.al_no} ns-${this.options.layout} ns-effect-${this.options.effect} ns-type-${this.options.type}`;
|
||||
let strinner = '<div class="ns-box-inner">';
|
||||
let strinner = "<div class=\"ns-box-inner\">";
|
||||
strinner += this.options.message;
|
||||
strinner += "</div>";
|
||||
this.ntf.innerHTML = strinner;
|
||||
@@ -153,4 +154,4 @@
|
||||
* Add to global namespace
|
||||
*/
|
||||
window.NotificationFx = NotificationFx;
|
||||
})(window);
|
||||
}(window));
|
||||
|
@@ -1,4 +1,4 @@
|
||||
/* global CalendarUtils, cloneObject */
|
||||
/* global CalendarUtils */
|
||||
|
||||
/* MagicMirror²
|
||||
* Module: Calendar
|
||||
@@ -28,6 +28,7 @@ Module.register("calendar", {
|
||||
fetchInterval: 60 * 60 * 1000, // Update every hour
|
||||
animationSpeed: 2000,
|
||||
fade: true,
|
||||
fadePoint: 0.25, // Start on 1/4th of the list.
|
||||
urgency: 7,
|
||||
timeFormat: "relative",
|
||||
dateFormat: "MMM Do",
|
||||
@@ -35,14 +36,12 @@ Module.register("calendar", {
|
||||
fullDayEventDateFormat: "MMM Do",
|
||||
showEnd: false,
|
||||
getRelative: 6,
|
||||
fadePoint: 0.25, // Start on 1/4th of the list.
|
||||
hidePrivate: false,
|
||||
hideOngoing: false,
|
||||
hideTime: false,
|
||||
hideDuplicates: true,
|
||||
showTimeToday: false,
|
||||
colored: false,
|
||||
customEvents: [], // Array of {keyword: "", symbol: "", color: "", eventClass: ""} where Keyword is a regexp and symbol/color/eventClass are to be applied for matched
|
||||
tableClass: "small",
|
||||
calendars: [
|
||||
{
|
||||
@@ -50,10 +49,11 @@ Module.register("calendar", {
|
||||
url: "https://www.calendarlabs.com/templates/ical/US-Holidays.ics"
|
||||
}
|
||||
],
|
||||
titleReplace: {
|
||||
"De verjaardag van ": "",
|
||||
"'s birthday": ""
|
||||
},
|
||||
customEvents: [
|
||||
// Array of {keyword: "", symbol: "", color: "", eventClass: ""} where Keyword is a regexp and symbol/color/eventClass are to be applied for matched
|
||||
{ keyword: ".*", transform: { search: "De verjaardag van ", replace: "" } },
|
||||
{ keyword: ".*", transform: { search: "'s birthday", replace: "" } }
|
||||
],
|
||||
locationTitleReplace: {
|
||||
"street ": ""
|
||||
},
|
||||
@@ -68,23 +68,24 @@ Module.register("calendar", {
|
||||
coloredSymbol: false,
|
||||
coloredBackground: false,
|
||||
limitDaysNeverSkip: false,
|
||||
flipDateHeaderTitle: false
|
||||
flipDateHeaderTitle: false,
|
||||
updateOnFetch: true
|
||||
},
|
||||
|
||||
requiresVersion: "2.1.0",
|
||||
|
||||
// Define required scripts.
|
||||
getStyles: function () {
|
||||
getStyles () {
|
||||
return ["calendar.css", "font-awesome.css"];
|
||||
},
|
||||
|
||||
// Define required scripts.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["calendarutils.js", "moment.js"];
|
||||
},
|
||||
|
||||
// Define required translations.
|
||||
getTranslations: function () {
|
||||
getTranslations () {
|
||||
// The translations for the default modules are defined in the core translation files.
|
||||
// Therefore we can just return false. Otherwise we should have returned a dictionary.
|
||||
// If you're trying to build your own module including translations, check out the documentation.
|
||||
@@ -92,9 +93,7 @@ Module.register("calendar", {
|
||||
},
|
||||
|
||||
// Override start method.
|
||||
start: function () {
|
||||
const ONE_MINUTE = 60 * 1000;
|
||||
|
||||
start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
|
||||
if (this.config.colored) {
|
||||
@@ -117,6 +116,9 @@ Module.register("calendar", {
|
||||
// indicate no data available yet
|
||||
this.loaded = false;
|
||||
|
||||
// data holder of calendar url. Avoid fade out/in on updateDom (one for each calendar update)
|
||||
this.calendarDisplayer = {};
|
||||
|
||||
this.config.calendars.forEach((calendar) => {
|
||||
calendar.url = calendar.url.replace("webcal://", "http://");
|
||||
|
||||
@@ -125,23 +127,25 @@ Module.register("calendar", {
|
||||
maximumNumberOfDays: calendar.maximumNumberOfDays,
|
||||
pastDaysCount: calendar.pastDaysCount,
|
||||
broadcastPastEvents: calendar.broadcastPastEvents,
|
||||
selfSignedCert: calendar.selfSignedCert
|
||||
selfSignedCert: calendar.selfSignedCert,
|
||||
excludedEvents: calendar.excludedEvents,
|
||||
fetchInterval: calendar.fetchInterval
|
||||
};
|
||||
|
||||
if (calendar.symbolClass === "undefined" || calendar.symbolClass === null) {
|
||||
if (typeof calendar.symbolClass === "undefined" || calendar.symbolClass === null) {
|
||||
calendarConfig.symbolClass = "";
|
||||
}
|
||||
if (calendar.titleClass === "undefined" || calendar.titleClass === null) {
|
||||
if (typeof calendar.titleClass === "undefined" || calendar.titleClass === null) {
|
||||
calendarConfig.titleClass = "";
|
||||
}
|
||||
if (calendar.timeClass === "undefined" || calendar.timeClass === null) {
|
||||
if (typeof calendar.timeClass === "undefined" || calendar.timeClass === null) {
|
||||
calendarConfig.timeClass = "";
|
||||
}
|
||||
|
||||
// we check user and password here for backwards compatibility with old configs
|
||||
if (calendar.user && calendar.pass) {
|
||||
Log.warn("Deprecation warning: Please update your calendar authentication configuration.");
|
||||
Log.warn("https://github.com/MichMich/MagicMirror/tree/v2.1.2/modules/default/calendar#calendar-authentication-options");
|
||||
Log.warn("https://docs.magicmirror.builders/modules/calendar.html#configuration-options");
|
||||
calendar.auth = {
|
||||
user: calendar.user,
|
||||
pass: calendar.pass
|
||||
@@ -153,20 +157,19 @@ Module.register("calendar", {
|
||||
this.addCalendar(calendar.url, calendar.auth, calendarConfig);
|
||||
});
|
||||
|
||||
// Refresh the DOM every minute if needed: When using relative date format for events that start
|
||||
// or end in less than an hour, the date shows minute granularity and we want to keep that accurate.
|
||||
setTimeout(
|
||||
() => {
|
||||
setInterval(() => {
|
||||
this.updateDom(1);
|
||||
}, ONE_MINUTE);
|
||||
},
|
||||
ONE_MINUTE - (new Date() % ONE_MINUTE)
|
||||
);
|
||||
// for backward compatibility titleReplace
|
||||
if (typeof this.config.titleReplace !== "undefined") {
|
||||
Log.warn("Deprecation warning: Please consider upgrading your calendar titleReplace configuration to customEvents.");
|
||||
for (const [titlesearchstr, titlereplacestr] of Object.entries(this.config.titleReplace)) {
|
||||
this.config.customEvents.push({ keyword: ".*", transform: { search: titlesearchstr, replace: titlereplacestr } });
|
||||
}
|
||||
}
|
||||
|
||||
this.selfUpdate();
|
||||
},
|
||||
|
||||
// Override socket notification handler.
|
||||
socketNotificationReceived: function (notification, payload) {
|
||||
socketNotificationReceived (notification, payload) {
|
||||
if (notification === "FETCH_CALENDAR") {
|
||||
this.sendSocketNotification(notification, { url: payload.url, id: this.identifier });
|
||||
}
|
||||
@@ -184,6 +187,18 @@ Module.register("calendar", {
|
||||
if (this.config.broadcastEvents) {
|
||||
this.broadcastEvents();
|
||||
}
|
||||
|
||||
if (!this.config.updateOnFetch) {
|
||||
if (this.calendarDisplayer[payload.url] === undefined) {
|
||||
// calendar will never displayed, so display it
|
||||
this.updateDom(this.config.animationSpeed);
|
||||
// set this calendar as displayed
|
||||
this.calendarDisplayer[payload.url] = true;
|
||||
} else {
|
||||
Log.debug("[Calendar] DOM not updated waiting self update()");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (notification === "CALENDAR_ERROR") {
|
||||
let error_message = this.translate(payload.error_type);
|
||||
@@ -195,7 +210,7 @@ Module.register("calendar", {
|
||||
},
|
||||
|
||||
// Override dom generator.
|
||||
getDom: function () {
|
||||
getDom () {
|
||||
const ONE_SECOND = 1000; // 1,000 milliseconds
|
||||
const ONE_MINUTE = ONE_SECOND * 60;
|
||||
const ONE_HOUR = ONE_MINUTE * 60;
|
||||
@@ -321,11 +336,16 @@ Module.register("calendar", {
|
||||
}
|
||||
}
|
||||
|
||||
// Color events if custom color or eventClass are specified
|
||||
var transformedTitle = event.title;
|
||||
|
||||
// Color events if custom color or eventClass are specified, transform title if required
|
||||
if (this.config.customEvents.length > 0) {
|
||||
for (let ev in this.config.customEvents) {
|
||||
let needle = new RegExp(this.config.customEvents[ev].keyword, "gi");
|
||||
if (needle.test(event.title)) {
|
||||
if (typeof this.config.customEvents[ev].transform === "object") {
|
||||
transformedTitle = CalendarUtils.titleTransform(transformedTitle, [this.config.customEvents[ev].transform]);
|
||||
}
|
||||
if (typeof this.config.customEvents[ev].color !== "undefined" && this.config.customEvents[ev].color !== "") {
|
||||
// Respect parameter ColoredSymbolOnly also for custom events
|
||||
if (this.config.coloredText) {
|
||||
@@ -335,7 +355,6 @@ Module.register("calendar", {
|
||||
if (this.config.displaySymbol && this.config.coloredSymbol) {
|
||||
symbolWrapper.style.cssText = `color:${this.config.customEvents[ev].color}`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (typeof this.config.customEvents[ev].eventClass !== "undefined" && this.config.customEvents[ev].eventClass !== "") {
|
||||
eventWrapper.className += ` ${this.config.customEvents[ev].eventClass}`;
|
||||
@@ -344,7 +363,6 @@ Module.register("calendar", {
|
||||
}
|
||||
}
|
||||
|
||||
const transformedTitle = CalendarUtils.titleTransform(event.title, this.config.titleReplace);
|
||||
titleWrapper.innerHTML = CalendarUtils.shorten(transformedTitle, this.config.maxTitleLength, this.config.wrapEvents, this.config.maxTitleLines) + repeatingCountTitle;
|
||||
|
||||
const titleClass = this.titleClassForUrl(event.url);
|
||||
@@ -534,7 +552,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {boolean} True if the calendar config contains the url, False otherwise
|
||||
*/
|
||||
hasCalendarURL: function (url) {
|
||||
hasCalendarURL (url) {
|
||||
for (const calendar of this.config.calendars) {
|
||||
if (calendar.url === url) {
|
||||
return true;
|
||||
@@ -549,7 +567,7 @@ Module.register("calendar", {
|
||||
* @param {boolean} limitNumberOfEntries Whether to filter returned events for display.
|
||||
* @returns {object[]} Array with events.
|
||||
*/
|
||||
createEventList: function (limitNumberOfEntries) {
|
||||
createEventList (limitNumberOfEntries) {
|
||||
const ONE_SECOND = 1000; // 1,000 milliseconds
|
||||
const ONE_MINUTE = ONE_SECOND * 60;
|
||||
const ONE_HOUR = ONE_MINUTE * 60;
|
||||
@@ -599,7 +617,12 @@ Module.register("calendar", {
|
||||
const maxCount = Math.ceil((event.endDate - 1 - moment(event.startDate, "x").endOf("day").format("x")) / ONE_DAY) + 1;
|
||||
if (this.config.sliceMultiDayEvents && maxCount > 1) {
|
||||
const splitEvents = [];
|
||||
let midnight = moment(event.startDate, "x").clone().startOf("day").add(1, "day").format("x");
|
||||
let midnight
|
||||
= moment(event.startDate, "x")
|
||||
.clone()
|
||||
.startOf("day")
|
||||
.add(1, "day")
|
||||
.format("x");
|
||||
let count = 1;
|
||||
while (event.endDate > midnight) {
|
||||
const thisEvent = JSON.parse(JSON.stringify(event)); // clone object
|
||||
@@ -668,7 +691,7 @@ Module.register("calendar", {
|
||||
return events.slice(0, this.config.maximumEntries);
|
||||
},
|
||||
|
||||
listContainsEvent: function (eventList, event) {
|
||||
listContainsEvent (eventList, event) {
|
||||
for (const evt of eventList) {
|
||||
if (evt.title === event.title && parseInt(evt.startDate) === parseInt(event.startDate) && parseInt(evt.endDate) === parseInt(event.endDate)) {
|
||||
return true;
|
||||
@@ -683,7 +706,7 @@ Module.register("calendar", {
|
||||
* @param {object} auth The authentication method and credentials
|
||||
* @param {object} calendarConfig The config of the specific calendar
|
||||
*/
|
||||
addCalendar: function (url, auth, calendarConfig) {
|
||||
addCalendar (url, auth, calendarConfig) {
|
||||
this.sendSocketNotification("ADD_CALENDAR", {
|
||||
id: this.identifier,
|
||||
url: url,
|
||||
@@ -706,7 +729,7 @@ Module.register("calendar", {
|
||||
* @param {object} event Event to look for.
|
||||
* @returns {string[]} The symbols
|
||||
*/
|
||||
symbolsForEvent: function (event) {
|
||||
symbolsForEvent (event) {
|
||||
let symbols = this.getCalendarPropertyAsArray(event.url, "symbol", this.config.defaultSymbol);
|
||||
|
||||
if (event.recurringEvent === true && this.hasCalendarProperty(event.url, "recurringSymbol")) {
|
||||
@@ -733,7 +756,7 @@ Module.register("calendar", {
|
||||
return symbols;
|
||||
},
|
||||
|
||||
mergeUnique: function (arr1, arr2) {
|
||||
mergeUnique (arr1, arr2) {
|
||||
return arr1.concat(
|
||||
arr2.filter(function (item) {
|
||||
return arr1.indexOf(item) === -1;
|
||||
@@ -746,7 +769,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {string} The class to be used for the symbols of the calendar
|
||||
*/
|
||||
symbolClassForUrl: function (url) {
|
||||
symbolClassForUrl (url) {
|
||||
return this.getCalendarProperty(url, "symbolClass", "");
|
||||
},
|
||||
|
||||
@@ -755,7 +778,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {string} The class to be used for the title of the calendar
|
||||
*/
|
||||
titleClassForUrl: function (url) {
|
||||
titleClassForUrl (url) {
|
||||
return this.getCalendarProperty(url, "titleClass", "");
|
||||
},
|
||||
|
||||
@@ -764,7 +787,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {string} The class to be used for the time of the calendar
|
||||
*/
|
||||
timeClassForUrl: function (url) {
|
||||
timeClassForUrl (url) {
|
||||
return this.getCalendarProperty(url, "timeClass", "");
|
||||
},
|
||||
|
||||
@@ -773,7 +796,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {string} The name of the calendar
|
||||
*/
|
||||
calendarNameForUrl: function (url) {
|
||||
calendarNameForUrl (url) {
|
||||
return this.getCalendarProperty(url, "name", "");
|
||||
},
|
||||
|
||||
@@ -783,7 +806,7 @@ Module.register("calendar", {
|
||||
* @param {boolean} isBg Determines if we fetch the bgColor or not
|
||||
* @returns {string} The color
|
||||
*/
|
||||
colorForUrl: function (url, isBg) {
|
||||
colorForUrl (url, isBg) {
|
||||
return this.getCalendarProperty(url, isBg ? "bgColor" : "color", "#fff");
|
||||
},
|
||||
|
||||
@@ -792,7 +815,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {string} The title
|
||||
*/
|
||||
countTitleForUrl: function (url) {
|
||||
countTitleForUrl (url) {
|
||||
return this.getCalendarProperty(url, "repeatingCountTitle", this.config.defaultRepeatingCountTitle);
|
||||
},
|
||||
|
||||
@@ -801,7 +824,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {number} The maximum entry count
|
||||
*/
|
||||
maximumEntriesForUrl: function (url) {
|
||||
maximumEntriesForUrl (url) {
|
||||
return this.getCalendarProperty(url, "maximumEntries", this.config.maximumEntries);
|
||||
},
|
||||
|
||||
@@ -810,7 +833,7 @@ Module.register("calendar", {
|
||||
* @param {string} url The calendar url
|
||||
* @returns {number} The maximum past days count
|
||||
*/
|
||||
maximumPastDaysForUrl: function (url) {
|
||||
maximumPastDaysForUrl (url) {
|
||||
return this.getCalendarProperty(url, "pastDaysCount", this.config.pastDaysCount);
|
||||
},
|
||||
|
||||
@@ -821,7 +844,7 @@ Module.register("calendar", {
|
||||
* @param {string} defaultValue The value if the property is not found
|
||||
* @returns {*} The property
|
||||
*/
|
||||
getCalendarProperty: function (url, property, defaultValue) {
|
||||
getCalendarProperty (url, property, defaultValue) {
|
||||
for (const calendar of this.config.calendars) {
|
||||
if (calendar.url === url && calendar.hasOwnProperty(property)) {
|
||||
return calendar[property];
|
||||
@@ -831,7 +854,7 @@ Module.register("calendar", {
|
||||
return defaultValue;
|
||||
},
|
||||
|
||||
getCalendarPropertyAsArray: function (url, property, defaultValue) {
|
||||
getCalendarPropertyAsArray (url, property, defaultValue) {
|
||||
let p = this.getCalendarProperty(url, property, defaultValue);
|
||||
if (property === "symbol" || property === "recurringSymbol" || property === "fullDaySymbol") {
|
||||
const className = this.getCalendarProperty(url, "symbolClassName", this.config.defaultSymbolClassName);
|
||||
@@ -842,7 +865,7 @@ Module.register("calendar", {
|
||||
return p;
|
||||
},
|
||||
|
||||
hasCalendarProperty: function (url, property) {
|
||||
hasCalendarProperty (url, property) {
|
||||
return !!this.getCalendarProperty(url, property, undefined);
|
||||
},
|
||||
|
||||
@@ -850,7 +873,7 @@ Module.register("calendar", {
|
||||
* Broadcasts the events to all other modules for reuse.
|
||||
* The all events available in one array, sorted on startdate.
|
||||
*/
|
||||
broadcastEvents: function () {
|
||||
broadcastEvents () {
|
||||
const eventList = this.createEventList(false);
|
||||
for (const event of eventList) {
|
||||
event.symbol = this.symbolsForEvent(event);
|
||||
@@ -860,5 +883,30 @@ Module.register("calendar", {
|
||||
}
|
||||
|
||||
this.sendNotification("CALENDAR_EVENTS", eventList);
|
||||
},
|
||||
|
||||
/**
|
||||
* Refresh the DOM every minute if needed: When using relative date format for events that start
|
||||
* or end in less than an hour, the date shows minute granularity and we want to keep that accurate.
|
||||
* --
|
||||
* When updateOnFetch is not set, it will Avoid fade out/in on updateDom when many calendars are used
|
||||
* and it's allow to refresh The DOM every minute with animation speed too
|
||||
* (because updateDom is not set in CALENDAR_EVENTS for this case)
|
||||
*/
|
||||
selfUpdate () {
|
||||
const ONE_MINUTE = 60 * 1000;
|
||||
setTimeout(
|
||||
() => {
|
||||
setInterval(() => {
|
||||
Log.debug("[Calendar] self update");
|
||||
if (this.config.updateOnFetch) {
|
||||
this.updateDom(1);
|
||||
} else {
|
||||
this.updateDom(this.config.animationSpeed);
|
||||
}
|
||||
}, ONE_MINUTE);
|
||||
},
|
||||
ONE_MINUTE - (new Date() % ONE_MINUTE)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
@@ -10,10 +10,12 @@
|
||||
*/
|
||||
const path = require("path");
|
||||
const moment = require("moment");
|
||||
|
||||
const zoneTable = require(path.join(__dirname, "windowsZones.json"));
|
||||
const Log = require("../../../js/logger");
|
||||
|
||||
const CalendarFetcherUtils = {
|
||||
|
||||
/**
|
||||
* Calculate the time correction, either dst/std or full day in cases where
|
||||
* utc time is day before plus offset
|
||||
@@ -21,7 +23,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {Date} date the date on which this event happens
|
||||
* @returns {number} the necessary adjustment in hours
|
||||
*/
|
||||
calculateTimezoneAdjustment: function (event, date) {
|
||||
calculateTimezoneAdjustment (event, date) {
|
||||
let adjustHours = 0;
|
||||
// if a timezone was specified
|
||||
if (!event.start.tz) {
|
||||
@@ -122,7 +124,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {object} config The configuration object
|
||||
* @returns {string[]} the filtered events
|
||||
*/
|
||||
filterEvents: function (data, config) {
|
||||
filterEvents (data, config) {
|
||||
const newEvents = [];
|
||||
|
||||
// limitFunction doesn't do much limiting, see comment re: the dates
|
||||
@@ -141,7 +143,12 @@ const CalendarFetcherUtils = {
|
||||
Log.debug("Processing entry...");
|
||||
const now = new Date();
|
||||
const today = moment().startOf("day").toDate();
|
||||
const future = moment().startOf("day").add(config.maximumNumberOfDays, "days").subtract(1, "seconds").toDate(); // Subtract 1 second so that events that start on the middle of the night will not repeat.
|
||||
const future
|
||||
= moment()
|
||||
.startOf("day")
|
||||
.add(config.maximumNumberOfDays, "days")
|
||||
.subtract(1, "seconds") // Subtract 1 second so that events that start on the middle of the night will not repeat.
|
||||
.toDate();
|
||||
let past = today;
|
||||
|
||||
if (config.includePastEvents) {
|
||||
@@ -247,7 +254,6 @@ const CalendarFetcherUtils = {
|
||||
|
||||
if (typeof event.rrule !== "undefined" && event.rrule !== null && !isFacebookBirthday) {
|
||||
const rule = event.rrule;
|
||||
let addedEvents = 0;
|
||||
|
||||
const pastMoment = moment(past);
|
||||
const futureMoment = moment(future);
|
||||
@@ -283,8 +289,12 @@ const CalendarFetcherUtils = {
|
||||
futureLocal = futureMoment.toDate(); // future
|
||||
}
|
||||
Log.debug(`Search for recurring events between: ${pastLocal} and ${futureLocal}`);
|
||||
const dates = rule.between(pastLocal, futureLocal, true, limitFunction);
|
||||
let dates = rule.between(pastLocal, futureLocal, true, limitFunction);
|
||||
Log.debug(`Title: ${event.summary}, with dates: ${JSON.stringify(dates)}`);
|
||||
dates = dates.filter((d) => {
|
||||
if (JSON.stringify(d) === "null") return false;
|
||||
else return true;
|
||||
});
|
||||
// The "dates" array contains the set of dates within our desired date range range that are valid
|
||||
// for the recurrence rule. *However*, it's possible for us to have a specific recurrence that
|
||||
// had its date changed from outside the range to inside the range. For the time being,
|
||||
@@ -305,11 +315,6 @@ const CalendarFetcherUtils = {
|
||||
// Loop through the set of date entries to see which recurrences should be added to our event list.
|
||||
for (let d in dates) {
|
||||
let date = dates[d];
|
||||
// Remove the time information of each date by using its substring, using the following method:
|
||||
// .toISOString().substring(0,10).
|
||||
// since the date is given as ISOString with YYYY-MM-DDTHH:MM:SS.SSSZ
|
||||
// (see https://momentjs.com/docs/#/displaying/as-iso-string/).
|
||||
const dateKey = date.toISOString().substring(0, 10);
|
||||
let curEvent = event;
|
||||
let showRecurrence = true;
|
||||
|
||||
@@ -402,6 +407,13 @@ const CalendarFetcherUtils = {
|
||||
|
||||
let adjustDays = CalendarFetcherUtils.calculateTimezoneAdjustment(event, date);
|
||||
|
||||
// Remove the time information of each date by using its substring, using the following method:
|
||||
// .toISOString().substring(0,10).
|
||||
// since the date is given as ISOString with YYYY-MM-DDTHH:MM:SS.SSSZ
|
||||
// (see https://momentjs.com/docs/#/displaying/as-iso-string/).
|
||||
// This must be done after `date` is adjusted
|
||||
const dateKey = date.toISOString().substring(0, 10);
|
||||
|
||||
// For each date that we're checking, it's possible that there is a recurrence override for that one day.
|
||||
if (curEvent.recurrences !== undefined && curEvent.recurrences[dateKey] !== undefined) {
|
||||
// We found an override, so for this recurrence, use a potentially different title, start date, and duration.
|
||||
@@ -435,7 +447,6 @@ const CalendarFetcherUtils = {
|
||||
|
||||
if (showRecurrence === true) {
|
||||
Log.debug(`saving event: ${description}`);
|
||||
addedEvents++;
|
||||
newEvents.push({
|
||||
title: recurrenceTitle,
|
||||
startDate: (adjustDays ? (adjustDays > 0 ? startDate.add(adjustDays, "hours") : startDate.subtract(Math.abs(adjustDays), "hours")) : startDate).format("x"),
|
||||
@@ -516,7 +527,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {string} msTZName the timezone name to lookup
|
||||
* @returns {string|null} the iana name or null of none is found
|
||||
*/
|
||||
getIanaTZFromMS: function (msTZName) {
|
||||
getIanaTZFromMS (msTZName) {
|
||||
// Get hash entry
|
||||
const he = zoneTable[msTZName];
|
||||
// If found return iana name, else null
|
||||
@@ -528,7 +539,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {object} event The event object to check.
|
||||
* @returns {string} The title of the event, or "Event" if no title is found.
|
||||
*/
|
||||
getTitleFromEvent: function (event) {
|
||||
getTitleFromEvent (event) {
|
||||
let title = "Event";
|
||||
if (event.summary) {
|
||||
title = typeof event.summary.val !== "undefined" ? event.summary.val : event.summary;
|
||||
@@ -544,7 +555,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {object} event The event object to check.
|
||||
* @returns {boolean} True if the event is a fullday event, false otherwise
|
||||
*/
|
||||
isFullDayEvent: function (event) {
|
||||
isFullDayEvent (event) {
|
||||
if (event.start.length === 8 || event.start.dateOnly || event.datetype === "date") {
|
||||
return true;
|
||||
}
|
||||
@@ -567,7 +578,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {string} filter The time to subtract from the end date to determine if an event should be shown
|
||||
* @returns {boolean} True if the event should be filtered out, false otherwise
|
||||
*/
|
||||
timeFilterApplies: function (now, endDate, filter) {
|
||||
timeFilterApplies (now, endDate, filter) {
|
||||
if (filter) {
|
||||
const until = filter.split(" "),
|
||||
value = parseInt(until[0]),
|
||||
@@ -588,7 +599,7 @@ const CalendarFetcherUtils = {
|
||||
* @param {string} regexFlags flags that should be applied to the regex
|
||||
* @returns {boolean} True if the title should be filtered out, false otherwise
|
||||
*/
|
||||
titleFilterApplies: function (title, filter, useRegex, regexFlags) {
|
||||
titleFilterApplies (title, filter, useRegex, regexFlags) {
|
||||
if (useRegex) {
|
||||
let regexFilter = filter;
|
||||
// Assume if leading slash, there is also trailing slash
|
||||
|
@@ -5,12 +5,13 @@
|
||||
* MIT Licensed.
|
||||
*/
|
||||
const CalendarUtils = {
|
||||
|
||||
/**
|
||||
* Capitalize the first letter of a string
|
||||
* @param {string} string The string to capitalize
|
||||
* @returns {string} The capitalized string
|
||||
*/
|
||||
capFirst: function (string) {
|
||||
capFirst (string) {
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
},
|
||||
|
||||
@@ -21,7 +22,7 @@ const CalendarUtils = {
|
||||
* @param {number} timeFormat Specifies either 12 or 24-hour time format
|
||||
* @returns {moment.LocaleSpecification} formatted time
|
||||
*/
|
||||
getLocaleSpecification: function (timeFormat) {
|
||||
getLocaleSpecification (timeFormat) {
|
||||
switch (timeFormat) {
|
||||
case 12: {
|
||||
return { longDateFormat: { LT: "h:mm A" } };
|
||||
@@ -43,7 +44,7 @@ const CalendarUtils = {
|
||||
* @param {number} maxTitleLines The max number of vertical lines before cutting event title
|
||||
* @returns {string} The shortened string
|
||||
*/
|
||||
shorten: function (string, maxLength, wrapEvents, maxTitleLines) {
|
||||
shorten (string, maxLength, wrapEvents, maxTitleLines) {
|
||||
if (typeof string !== "string") {
|
||||
return "";
|
||||
}
|
||||
@@ -90,23 +91,39 @@ const CalendarUtils = {
|
||||
/**
|
||||
* Transforms the title of an event for usage.
|
||||
* Replaces parts of the text as defined in config.titleReplace.
|
||||
* Shortens title based on config.maxTitleLength and config.wrapEvents
|
||||
* @param {string} title The title to transform.
|
||||
* @param {object} titleReplace Pairs of strings to be replaced in the title
|
||||
* @param {object} titleReplace object definition of parts to be replaced in the title
|
||||
* object definition:
|
||||
* search: {string,required} RegEx in format //x or simple string to be searched. For (birthday) year calcluation, the element matching the year must be in a RegEx group
|
||||
* replace: {string,required} Replacement string, may contain match group references (latter is required for year calculation)
|
||||
* yearmatchgroup: {number,optional} match group for year element
|
||||
* @returns {string} The transformed title.
|
||||
*/
|
||||
titleTransform: function (title, titleReplace) {
|
||||
titleTransform (title, titleReplace) {
|
||||
let transformedTitle = title;
|
||||
for (let needle in titleReplace) {
|
||||
const replacement = titleReplace[needle];
|
||||
for (let tr in titleReplace) {
|
||||
let transform = titleReplace[tr];
|
||||
if (typeof transform === "object") {
|
||||
if (typeof transform.search !== "undefined" && transform.search !== "" && typeof transform.replace !== "undefined") {
|
||||
let regParts = transform.search.match(/^\/(.+)\/([gim]*)$/);
|
||||
let needle = new RegExp(transform.search, "g");
|
||||
if (regParts) {
|
||||
// the parsed pattern is a regexp with flags.
|
||||
needle = new RegExp(regParts[1], regParts[2]);
|
||||
}
|
||||
|
||||
const regParts = needle.match(/^\/(.+)\/([gim]*)$/);
|
||||
if (regParts) {
|
||||
// the parsed pattern is a regexp.
|
||||
needle = new RegExp(regParts[1], regParts[2]);
|
||||
let replacement = transform.replace;
|
||||
if (typeof transform.yearmatchgroup !== "undefined" && transform.yearmatchgroup !== "") {
|
||||
const yearmatch = [...title.matchAll(needle)];
|
||||
if (yearmatch[0].length >= transform.yearmatchgroup + 1 && yearmatch[0][transform.yearmatchgroup] * 1 >= 1900) {
|
||||
let calcage = new Date().getFullYear() - yearmatch[0][transform.yearmatchgroup] * 1;
|
||||
let searchstr = `$${transform.yearmatchgroup}`;
|
||||
replacement = replacement.replace(searchstr, calcage);
|
||||
}
|
||||
}
|
||||
transformedTitle = transformedTitle.replace(needle, replacement);
|
||||
}
|
||||
}
|
||||
|
||||
transformedTitle = transformedTitle.replace(needle, replacement);
|
||||
}
|
||||
return transformedTitle;
|
||||
}
|
||||
|
@@ -10,13 +10,13 @@ const CalendarFetcher = require("./calendarfetcher");
|
||||
|
||||
module.exports = NodeHelper.create({
|
||||
// Override start method.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.log(`Starting node helper for: ${this.name}`);
|
||||
this.fetchers = [];
|
||||
},
|
||||
|
||||
// Override socketNotificationReceived method.
|
||||
socketNotificationReceived: function (notification, payload) {
|
||||
socketNotificationReceived (notification, payload) {
|
||||
if (notification === "ADD_CALENDAR") {
|
||||
this.createFetcher(payload.url, payload.fetchInterval, payload.excludedEvents, payload.maximumEntries, payload.maximumNumberOfDays, payload.auth, payload.broadcastPastEvents, payload.selfSignedCert, payload.id);
|
||||
} else if (notification === "FETCH_CALENDAR") {
|
||||
@@ -43,7 +43,7 @@ module.exports = NodeHelper.create({
|
||||
* @param {boolean} selfSignedCert If true, the server certificate is not verified against the list of supplied CAs.
|
||||
* @param {string} identifier ID of the module
|
||||
*/
|
||||
createFetcher: function (url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert, identifier) {
|
||||
createFetcher (url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth, broadcastPastEvents, selfSignedCert, identifier) {
|
||||
try {
|
||||
new URL(url);
|
||||
} catch (error) {
|
||||
@@ -85,7 +85,7 @@ module.exports = NodeHelper.create({
|
||||
* @param {object} fetcher the fetcher associated with the calendar
|
||||
* @param {string} identifier the identifier of the calendar
|
||||
*/
|
||||
broadcastEvents: function (fetcher, identifier) {
|
||||
broadcastEvents (fetcher, identifier) {
|
||||
this.sendSocketNotification("CALENDAR_EVENTS", {
|
||||
id: identifier,
|
||||
url: fetcher.url(),
|
||||
|
@@ -32,20 +32,20 @@ Module.register("clock", {
|
||||
secondsColor: "#888888",
|
||||
|
||||
showSunTimes: false,
|
||||
showMoonTimes: false,
|
||||
showMoonTimes: false, // options: false, 'times' (rise/set), 'percent' (lit percent), 'phase' (current phase), or 'both' (percent & phase)
|
||||
lat: 47.630539,
|
||||
lon: -122.344147
|
||||
},
|
||||
// Define required scripts.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["moment.js", "moment-timezone.js", "suncalc.js"];
|
||||
},
|
||||
// Define styles.
|
||||
getStyles: function () {
|
||||
getStyles () {
|
||||
return ["clock_styles.css"];
|
||||
},
|
||||
// Define start sequence.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
|
||||
// Schedule update interval.
|
||||
@@ -94,7 +94,7 @@ Module.register("clock", {
|
||||
moment.locale(config.language);
|
||||
},
|
||||
// Override dom generator.
|
||||
getDom: function () {
|
||||
getDom () {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.classList.add("clock-grid");
|
||||
|
||||
@@ -186,10 +186,10 @@ Module.register("clock", {
|
||||
}
|
||||
const untilNextEvent = moment.duration(moment(nextEvent).diff(now));
|
||||
const untilNextEventString = `${untilNextEvent.hours()}h ${untilNextEvent.minutes()}m`;
|
||||
sunWrapper.innerHTML =
|
||||
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-sun" aria-hidden="true"></i> ${untilNextEventString}</span>` +
|
||||
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunrise)}</span>` +
|
||||
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunset)}</span>`;
|
||||
sunWrapper.innerHTML
|
||||
= `<span class="${isVisible ? "bright" : ""}"><i class="fas fa-sun" aria-hidden="true"></i> ${untilNextEventString}</span>`
|
||||
+ `<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunrise)}</span>`
|
||||
+ `<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${formatTime(this.config, sunTimes.sunset)}</span>`;
|
||||
digitalWrapper.appendChild(sunWrapper);
|
||||
}
|
||||
|
||||
@@ -208,11 +208,15 @@ Module.register("clock", {
|
||||
moonSet = nextMoonTimes.set;
|
||||
}
|
||||
const isVisible = now.isBetween(moonRise, moonSet) || moonTimes.alwaysUp === true;
|
||||
const showFraction = ["both", "percent"].includes(this.config.showMoonTimes);
|
||||
const showUnicode = ["both", "phase"].includes(this.config.showMoonTimes);
|
||||
const illuminatedFractionString = `${Math.round(moonIllumination.fraction * 100)}%`;
|
||||
moonWrapper.innerHTML =
|
||||
`<span class="${isVisible ? "bright" : ""}"><i class="fas fa-moon" aria-hidden="true"></i> ${illuminatedFractionString}</span>` +
|
||||
`<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${moonRise ? formatTime(this.config, moonRise) : "..."}</span>` +
|
||||
`<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${moonSet ? formatTime(this.config, moonSet) : "..."}</span>`;
|
||||
const image = showUnicode ? [..."🌑🌒🌓🌔🌕🌖🌗🌘"][Math.floor(moonIllumination.phase * 8)] : "<i class=\"fas fa-moon\" aria-hidden=\"true\"></i>";
|
||||
|
||||
moonWrapper.innerHTML
|
||||
= `<span class="${isVisible ? "bright" : ""}">${image} ${showFraction ? illuminatedFractionString : ""}</span>`
|
||||
+ `<span><i class="fas fa-arrow-up" aria-hidden="true"></i> ${moonRise ? formatTime(this.config, moonRise) : "..."}</span>`
|
||||
+ `<span><i class="fas fa-arrow-down" aria-hidden="true"></i> ${moonSet ? formatTime(this.config, moonSet) : "..."}</span>`;
|
||||
digitalWrapper.appendChild(moonWrapper);
|
||||
}
|
||||
|
||||
|
@@ -28,12 +28,12 @@ Module.register("compliments", {
|
||||
currentWeatherType: "",
|
||||
|
||||
// Define required scripts.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["moment.js"];
|
||||
},
|
||||
|
||||
// Define start sequence.
|
||||
start: async function () {
|
||||
async start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
|
||||
this.lastComplimentIndex = -1;
|
||||
@@ -55,7 +55,7 @@ Module.register("compliments", {
|
||||
* @param {string[]} compliments Array with compliments.
|
||||
* @returns {number} a random index of given array
|
||||
*/
|
||||
randomIndex: function (compliments) {
|
||||
randomIndex (compliments) {
|
||||
if (compliments.length === 1) {
|
||||
return 0;
|
||||
}
|
||||
@@ -79,7 +79,7 @@ Module.register("compliments", {
|
||||
* Retrieve an array of compliments for the time of the day.
|
||||
* @returns {string[]} array with compliments for the time of the day.
|
||||
*/
|
||||
complimentArray: function () {
|
||||
complimentArray () {
|
||||
const hour = moment().hour();
|
||||
const date = moment().format("YYYY-MM-DD");
|
||||
let compliments = [];
|
||||
@@ -115,7 +115,7 @@ Module.register("compliments", {
|
||||
* Retrieve a file from the local filesystem
|
||||
* @returns {Promise} Resolved when the file is loaded
|
||||
*/
|
||||
loadComplimentFile: async function () {
|
||||
async loadComplimentFile () {
|
||||
const isRemote = this.config.remoteFile.indexOf("http://") === 0 || this.config.remoteFile.indexOf("https://") === 0,
|
||||
url = isRemote ? this.config.remoteFile : this.file(this.config.remoteFile);
|
||||
const response = await fetch(url);
|
||||
@@ -126,7 +126,7 @@ Module.register("compliments", {
|
||||
* Retrieve a random compliment.
|
||||
* @returns {string} a compliment
|
||||
*/
|
||||
getRandomCompliment: function () {
|
||||
getRandomCompliment () {
|
||||
// get the current time of day compliments list
|
||||
const compliments = this.complimentArray();
|
||||
// variable for index to next message to display
|
||||
@@ -145,7 +145,7 @@ Module.register("compliments", {
|
||||
},
|
||||
|
||||
// Override dom generator.
|
||||
getDom: function () {
|
||||
getDom () {
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = this.config.classes ? this.config.classes : "thin xlarge bright pre-line";
|
||||
// get the compliment text
|
||||
@@ -173,7 +173,7 @@ Module.register("compliments", {
|
||||
},
|
||||
|
||||
// Override notification handler.
|
||||
notificationReceived: function (notification, payload, sender) {
|
||||
notificationReceived (notification, payload, sender) {
|
||||
if (notification === "CURRENTWEATHER_TYPE") {
|
||||
this.currentWeatherType = payload.type;
|
||||
}
|
||||
|
@@ -10,11 +10,11 @@ Module.register("helloworld", {
|
||||
text: "Hello World!"
|
||||
},
|
||||
|
||||
getTemplate: function () {
|
||||
getTemplate () {
|
||||
return "helloworld.njk";
|
||||
},
|
||||
|
||||
getTemplateData: function () {
|
||||
getTemplateData () {
|
||||
return this.config;
|
||||
}
|
||||
});
|
||||
|
@@ -42,7 +42,7 @@ Module.register("newsfeed", {
|
||||
dangerouslyDisableAutoEscaping: false
|
||||
},
|
||||
|
||||
getUrlPrefix: function (item) {
|
||||
getUrlPrefix (item) {
|
||||
if (item.useCorsProxy) {
|
||||
return `${location.protocol}//${location.host}/cors?url=`;
|
||||
} else {
|
||||
@@ -51,17 +51,17 @@ Module.register("newsfeed", {
|
||||
},
|
||||
|
||||
// Define required scripts.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["moment.js"];
|
||||
},
|
||||
|
||||
//Define required styles.
|
||||
getStyles: function () {
|
||||
getStyles () {
|
||||
return ["newsfeed.css"];
|
||||
},
|
||||
|
||||
// Define required translations.
|
||||
getTranslations: function () {
|
||||
getTranslations () {
|
||||
// The translations for the default modules are defined in the core translation files.
|
||||
// Therefor we can just return false. Otherwise we should have returned a dictionary.
|
||||
// If you're trying to build your own module including translations, check out the documentation.
|
||||
@@ -69,7 +69,7 @@ Module.register("newsfeed", {
|
||||
},
|
||||
|
||||
// Define start sequence.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
|
||||
// Set locale.
|
||||
@@ -87,7 +87,7 @@ Module.register("newsfeed", {
|
||||
},
|
||||
|
||||
// Override socket notification handler.
|
||||
socketNotificationReceived: function (notification, payload) {
|
||||
socketNotificationReceived (notification, payload) {
|
||||
if (notification === "NEWS_ITEMS") {
|
||||
this.generateFeed(payload);
|
||||
|
||||
@@ -107,7 +107,7 @@ Module.register("newsfeed", {
|
||||
},
|
||||
|
||||
//Override fetching of template name
|
||||
getTemplate: function () {
|
||||
getTemplate () {
|
||||
if (this.config.feedUrl) {
|
||||
return "oldconfig.njk";
|
||||
} else if (this.config.showFullArticle) {
|
||||
@@ -117,7 +117,7 @@ Module.register("newsfeed", {
|
||||
},
|
||||
|
||||
//Override template data and return whats used for the current template
|
||||
getTemplateData: function () {
|
||||
getTemplateData () {
|
||||
// this.config.showFullArticle is a run-time configuration, triggered by optional notifications
|
||||
if (this.config.showFullArticle) {
|
||||
return {
|
||||
@@ -156,7 +156,7 @@ Module.register("newsfeed", {
|
||||
};
|
||||
},
|
||||
|
||||
getActiveItemURL: function () {
|
||||
getActiveItemURL () {
|
||||
const item = this.newsItems[this.activeItem];
|
||||
if (item) {
|
||||
return typeof item.url === "string" ? this.getUrlPrefix(item) + item.url : this.getUrlPrefix(item) + item.url.href;
|
||||
@@ -168,7 +168,7 @@ Module.register("newsfeed", {
|
||||
/**
|
||||
* Registers the feeds to be used by the backend.
|
||||
*/
|
||||
registerFeeds: function () {
|
||||
registerFeeds () {
|
||||
for (let feed of this.config.feeds) {
|
||||
this.sendSocketNotification("ADD_FEED", {
|
||||
feed: feed,
|
||||
@@ -181,7 +181,7 @@ Module.register("newsfeed", {
|
||||
* Generate an ordered list of items for this configured module.
|
||||
* @param {object} feeds An object with feeds returned by the node helper.
|
||||
*/
|
||||
generateFeed: function (feeds) {
|
||||
generateFeed (feeds) {
|
||||
let newsItems = [];
|
||||
for (let feed in feeds) {
|
||||
const feedItems = feeds[feed];
|
||||
@@ -274,7 +274,7 @@ Module.register("newsfeed", {
|
||||
* @param {string} feedUrl Url of the feed to check.
|
||||
* @returns {boolean} True if it is subscribed, false otherwise
|
||||
*/
|
||||
subscribedToFeed: function (feedUrl) {
|
||||
subscribedToFeed (feedUrl) {
|
||||
for (let feed of this.config.feeds) {
|
||||
if (feed.url === feedUrl) {
|
||||
return true;
|
||||
@@ -288,7 +288,7 @@ Module.register("newsfeed", {
|
||||
* @param {string} feedUrl Url of the feed
|
||||
* @returns {string} The title of the feed
|
||||
*/
|
||||
titleForFeed: function (feedUrl) {
|
||||
titleForFeed (feedUrl) {
|
||||
for (let feed of this.config.feeds) {
|
||||
if (feed.url === feedUrl) {
|
||||
return feed.title || "";
|
||||
@@ -300,7 +300,7 @@ Module.register("newsfeed", {
|
||||
/**
|
||||
* Schedule visual update.
|
||||
*/
|
||||
scheduleUpdateInterval: function () {
|
||||
scheduleUpdateInterval () {
|
||||
this.updateDom(this.config.animationSpeed);
|
||||
|
||||
// Broadcast NewsFeed if needed
|
||||
@@ -322,7 +322,7 @@ Module.register("newsfeed", {
|
||||
}, this.config.updateInterval);
|
||||
},
|
||||
|
||||
resetDescrOrFullArticleAndTimer: function () {
|
||||
resetDescrOrFullArticleAndTimer () {
|
||||
this.isShowingDescription = this.config.showDescription;
|
||||
this.config.showFullArticle = false;
|
||||
this.scrollPosition = 0;
|
||||
@@ -333,7 +333,7 @@ Module.register("newsfeed", {
|
||||
}
|
||||
},
|
||||
|
||||
notificationReceived: function (notification, payload, sender) {
|
||||
notificationReceived (notification, payload, sender) {
|
||||
const before = this.activeItem;
|
||||
if (notification === "MODULE_DOM_CREATED" && this.config.hideLoading) {
|
||||
this.hide();
|
||||
@@ -394,7 +394,7 @@ Module.register("newsfeed", {
|
||||
}
|
||||
},
|
||||
|
||||
showFullArticle: function () {
|
||||
showFullArticle () {
|
||||
this.isShowingDescription = !this.isShowingDescription;
|
||||
this.config.showFullArticle = !this.isShowingDescription;
|
||||
// make bottom bar align to top to allow scrolling
|
||||
|
@@ -48,14 +48,19 @@ const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings
|
||||
parser.on("item", (item) => {
|
||||
const title = item.title;
|
||||
let description = item.description || item.summary || item.content || "";
|
||||
const pubdate = item.pubdate || item.published || item.updated || item["dc:date"];
|
||||
const pubdate = item.pubdate || item.published || item.updated || item["dc:date"] || item["a10:updated"];
|
||||
const url = item.url || item.link || "";
|
||||
|
||||
if (title && pubdate) {
|
||||
const regex = /(<([^>]+)>)/gi;
|
||||
description = description.toString().replace(regex, "");
|
||||
// Convert HTML entities, codes and tag
|
||||
description = htmlToText(description, { wordwrap: false });
|
||||
description = htmlToText(description, {
|
||||
wordwrap: false,
|
||||
selectors: [
|
||||
{ selector: "a", options: { ignoreHref: true, noAnchorUrl: true } },
|
||||
{ selector: "br", format: "inlineSurround", options: { prefix: " " } },
|
||||
{ selector: "img", format: "skip" }
|
||||
]
|
||||
});
|
||||
|
||||
items.push({
|
||||
title: title,
|
||||
|
@@ -11,13 +11,13 @@ const NewsfeedFetcher = require("./newsfeedfetcher");
|
||||
|
||||
module.exports = NodeHelper.create({
|
||||
// Override start method.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.log(`Starting node helper for: ${this.name}`);
|
||||
this.fetchers = [];
|
||||
},
|
||||
|
||||
// Override socketNotificationReceived received.
|
||||
socketNotificationReceived: function (notification, payload) {
|
||||
socketNotificationReceived (notification, payload) {
|
||||
if (notification === "ADD_FEED") {
|
||||
this.createFetcher(payload.feed, payload.config);
|
||||
}
|
||||
@@ -29,7 +29,7 @@ module.exports = NodeHelper.create({
|
||||
* @param {object} feed The feed object
|
||||
* @param {object} config The configuration object
|
||||
*/
|
||||
createFetcher: function (feed, config) {
|
||||
createFetcher (feed, config) {
|
||||
const url = feed.url || "";
|
||||
const encoding = feed.encoding || "UTF-8";
|
||||
const reloadInterval = feed.reloadInterval || config.reloadInterval || 5 * 60 * 1000;
|
||||
@@ -76,7 +76,7 @@ module.exports = NodeHelper.create({
|
||||
* Creates an object with all feed items of the different registered feeds,
|
||||
* and broadcasts these using sendSocketNotification.
|
||||
*/
|
||||
broadcastFeeds: function () {
|
||||
broadcastFeeds () {
|
||||
const feeds = {};
|
||||
for (let f in this.fetchers) {
|
||||
feeds[f] = this.fetchers[f].items();
|
||||
|
@@ -7,22 +7,22 @@ const Log = require("logger");
|
||||
const BASE_DIR = path.normalize(`${__dirname}/../../../`);
|
||||
|
||||
class GitHelper {
|
||||
constructor() {
|
||||
constructor () {
|
||||
this.gitRepos = [];
|
||||
this.gitResultList = [];
|
||||
}
|
||||
|
||||
getRefRegex(branch) {
|
||||
getRefRegex (branch) {
|
||||
return new RegExp(`s*([a-z,0-9]+[.][.][a-z,0-9]+) ${branch}`, "g");
|
||||
}
|
||||
|
||||
async execShell(command) {
|
||||
async execShell (command) {
|
||||
const { stdout = "", stderr = "" } = await exec(command);
|
||||
|
||||
return { stdout, stderr };
|
||||
}
|
||||
|
||||
async isGitRepo(moduleFolder) {
|
||||
async isGitRepo (moduleFolder) {
|
||||
const { stderr } = await this.execShell(`cd ${moduleFolder} && git remote -v`);
|
||||
|
||||
if (stderr) {
|
||||
@@ -34,7 +34,7 @@ class GitHelper {
|
||||
return true;
|
||||
}
|
||||
|
||||
async add(moduleName) {
|
||||
async add (moduleName) {
|
||||
let moduleFolder = BASE_DIR;
|
||||
|
||||
if (moduleName !== "MagicMirror") {
|
||||
@@ -59,7 +59,7 @@ class GitHelper {
|
||||
}
|
||||
}
|
||||
|
||||
async getStatusInfo(repo) {
|
||||
async getStatusInfo (repo) {
|
||||
let gitInfo = {
|
||||
module: repo.module,
|
||||
behind: 0, // commits behind
|
||||
@@ -114,7 +114,7 @@ class GitHelper {
|
||||
return gitInfo;
|
||||
}
|
||||
|
||||
async getRepoInfo(repo) {
|
||||
async getRepoInfo (repo) {
|
||||
const gitInfo = await this.getStatusInfo(repo);
|
||||
|
||||
if (!gitInfo || !gitInfo.current) {
|
||||
@@ -174,7 +174,7 @@ class GitHelper {
|
||||
}
|
||||
}
|
||||
|
||||
async getRepos() {
|
||||
async getRepos () {
|
||||
this.gitResultList = [];
|
||||
|
||||
for (const repo of this.gitRepos) {
|
||||
@@ -192,7 +192,7 @@ class GitHelper {
|
||||
return this.gitResultList;
|
||||
}
|
||||
|
||||
async checkUpdates() {
|
||||
async checkUpdates () {
|
||||
var updates = [];
|
||||
|
||||
const allRepos = await this.gitResultList.map((module) => {
|
||||
|
@@ -1,6 +1,7 @@
|
||||
const NodeHelper = require("node_helper");
|
||||
const defaultModules = require("../defaultmodules");
|
||||
const GitHelper = require("./git_helper");
|
||||
const UpdateHelper = require("./update_helper");
|
||||
|
||||
const ONE_MINUTE = 60 * 1000;
|
||||
|
||||
@@ -11,8 +12,9 @@ module.exports = NodeHelper.create({
|
||||
updateProcessStarted: false,
|
||||
|
||||
gitHelper: new GitHelper(),
|
||||
updateHelper: null,
|
||||
|
||||
async configureModules(modules) {
|
||||
async configureModules (modules) {
|
||||
for (const moduleName of modules) {
|
||||
if (!this.ignoreUpdateChecking(moduleName)) {
|
||||
await this.gitHelper.add(moduleName);
|
||||
@@ -24,10 +26,12 @@ module.exports = NodeHelper.create({
|
||||
}
|
||||
},
|
||||
|
||||
async socketNotificationReceived(notification, payload) {
|
||||
async socketNotificationReceived (notification, payload) {
|
||||
switch (notification) {
|
||||
case "CONFIG":
|
||||
this.config = payload;
|
||||
this.updateHelper = new UpdateHelper(this.config);
|
||||
await this.updateHelper.check_PM2_Process();
|
||||
break;
|
||||
case "MODULES":
|
||||
// if this is the 1st time thru the update check process
|
||||
@@ -47,22 +51,32 @@ module.exports = NodeHelper.create({
|
||||
}
|
||||
},
|
||||
|
||||
async performFetch() {
|
||||
async performFetch () {
|
||||
const repos = await this.gitHelper.getRepos();
|
||||
|
||||
for (const repo of repos) {
|
||||
this.sendSocketNotification("STATUS", repo);
|
||||
this.sendSocketNotification("REPO_STATUS", repo);
|
||||
}
|
||||
|
||||
if (this.config.sendUpdatesNotifications) {
|
||||
const updates = await this.gitHelper.checkUpdates();
|
||||
if (updates.length) this.sendSocketNotification("UPDATES", updates);
|
||||
const updates = await this.gitHelper.checkUpdates();
|
||||
|
||||
if (this.config.sendUpdatesNotifications && updates.length) {
|
||||
this.sendSocketNotification("UPDATES", updates);
|
||||
}
|
||||
|
||||
if (updates.length) {
|
||||
const updateResult = await this.updateHelper.parse(updates);
|
||||
for (const update of updateResult) {
|
||||
if (update.inProgress) {
|
||||
this.sendSocketNotification("UPDATE_STATUS", update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.scheduleNextFetch(this.config.updateInterval);
|
||||
},
|
||||
|
||||
scheduleNextFetch(delay) {
|
||||
scheduleNextFetch (delay) {
|
||||
clearTimeout(this.updateTimer);
|
||||
|
||||
this.updateTimer = setTimeout(
|
||||
@@ -73,7 +87,7 @@ module.exports = NodeHelper.create({
|
||||
);
|
||||
},
|
||||
|
||||
ignoreUpdateChecking(moduleName) {
|
||||
ignoreUpdateChecking (moduleName) {
|
||||
// Should not check for updates for default modules
|
||||
if (defaultModules.includes(moduleName)) {
|
||||
return true;
|
||||
|
230
modules/default/updatenotification/update_helper.js
Normal file
230
modules/default/updatenotification/update_helper.js
Normal file
@@ -0,0 +1,230 @@
|
||||
const Exec = require("child_process").exec;
|
||||
const Spawn = require("child_process").spawn;
|
||||
const commandExists = require("command-exists");
|
||||
const Log = require("logger");
|
||||
|
||||
/* class Updater
|
||||
* Allow to self updating 3rd party modules from command defined in config
|
||||
*
|
||||
* [constructor] read value in config:
|
||||
* updates: [ // array of modules update commands
|
||||
* {
|
||||
* <module name>: <update command>
|
||||
* },
|
||||
* {
|
||||
* ...
|
||||
* }
|
||||
* ],
|
||||
* updateTimeout: 2 * 60 * 1000, // max update duration
|
||||
* updateAutorestart: false // autoRestart MM when update done ?
|
||||
*
|
||||
* [main command]: parse(<Array of modules>):
|
||||
* parse if module update is needed
|
||||
* --> Apply ONLY one update (first of the module list)
|
||||
* --> auto-restart MagicMirror or wait manual restart by user
|
||||
* return array with modules update state information for `updatenotification` module displayer information
|
||||
* [
|
||||
* {
|
||||
* name = <module-name>, // name of the module
|
||||
* updateCommand = <update command>, // update command (if found)
|
||||
* inProgress = <boolean>, // an update if in progress for this module
|
||||
* error = <boolean>, // an error if detected when updating
|
||||
* updated = <boolean>, // updated successfully
|
||||
* needRestart = <boolean> // manual restart of MagicMirror is required by user
|
||||
* },
|
||||
* {
|
||||
* ...
|
||||
* }
|
||||
* ]
|
||||
*/
|
||||
|
||||
class Updater {
|
||||
constructor (config) {
|
||||
this.updates = config.updates;
|
||||
this.timeout = config.updateTimeout;
|
||||
this.autoRestart = config.updateAutorestart;
|
||||
this.moduleList = {};
|
||||
this.updating = false;
|
||||
this.usePM2 = false;
|
||||
this.PM2 = null;
|
||||
this.version = global.version;
|
||||
this.root_path = global.root_path;
|
||||
Log.info("updatenotification: Updater Class Loaded!");
|
||||
}
|
||||
|
||||
// [main command] parse if module update is needed
|
||||
async parse (modules) {
|
||||
var parser = modules.map(async (module) => {
|
||||
if (this.moduleList[module.module] === undefined) {
|
||||
this.moduleList[module.module] = {};
|
||||
this.moduleList[module.module].name = module.module;
|
||||
this.moduleList[module.module].updateCommand = await this.applyCommand(module.module);
|
||||
this.moduleList[module.module].inProgress = false;
|
||||
this.moduleList[module.module].error = null;
|
||||
this.moduleList[module.module].updated = false;
|
||||
this.moduleList[module.module].needRestart = false;
|
||||
}
|
||||
if (!this.moduleList[module.module].inProgress) {
|
||||
if (!this.updating) {
|
||||
if (!this.moduleList[module.module].updateCommand) {
|
||||
this.updating = false;
|
||||
} else {
|
||||
this.updating = true;
|
||||
this.moduleList[module.module].inProgress = true;
|
||||
Object.assign(this.moduleList[module.module], await this.updateProcess(this.moduleList[module.module]));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(parser);
|
||||
let updater = Object.values(this.moduleList);
|
||||
Log.debug("updatenotification Update Result:", updater);
|
||||
return updater;
|
||||
}
|
||||
|
||||
// module updater with his proper command
|
||||
// return object as result
|
||||
//{
|
||||
// error: <boolean>, // if error detected
|
||||
// updated: <boolean>, // if updated successfully
|
||||
// needRestart: <boolean> // if magicmirror restart required
|
||||
//};
|
||||
updateProcess (module) {
|
||||
let Result = {
|
||||
error: false,
|
||||
updated: false,
|
||||
needRestart: false
|
||||
};
|
||||
let Command = null;
|
||||
const Path = `${this.root_path}/modules/`;
|
||||
const modulePath = Path + module.name;
|
||||
|
||||
if (module.updateCommand) {
|
||||
Command = module.updateCommand;
|
||||
} else {
|
||||
Log.warn(`updatenotification: Update of ${module.name} is not supported.`);
|
||||
return Result;
|
||||
}
|
||||
Log.info(`updatenotification: Updating ${module.name}...`);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
Exec(Command, { cwd: modulePath, timeout: this.timeout }, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
Log.error(`updatenotification: exec error: ${error}`);
|
||||
Result.error = true;
|
||||
} else {
|
||||
Log.info(`updatenotification: Update logs of ${module.name}: ${stdout}`);
|
||||
Result.updated = true;
|
||||
if (this.autoRestart) {
|
||||
Log.info("updatenotification: Update done");
|
||||
setTimeout(() => this.restart(), 3000);
|
||||
} else {
|
||||
Log.info("updatenotification: Update done, don't forget to restart MagicMirror!");
|
||||
Result.needRestart = true;
|
||||
}
|
||||
}
|
||||
resolve(Result);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// restart rules (pm2 or npm start)
|
||||
restart () {
|
||||
if (this.usePM2) this.pm2Restart();
|
||||
else this.npmRestart();
|
||||
}
|
||||
|
||||
// restart MagicMiror with "pm2"
|
||||
pm2Restart () {
|
||||
Log.info("updatenotification: PM2 will restarting MagicMirror...");
|
||||
Exec(`pm2 restart ${this.PM2}`, (err, std, sde) => {
|
||||
if (err) {
|
||||
Log.error("updatenotification:[PM2] restart Error", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// restart MagicMiror with "npm start"
|
||||
npmRestart () {
|
||||
Log.info("updatenotification: Restarting MagicMirror...");
|
||||
const out = process.stdout;
|
||||
const err = process.stderr;
|
||||
const subprocess = Spawn("npm start", { cwd: this.root_path, shell: true, detached: true, stdio: ["ignore", out, err] });
|
||||
subprocess.unref();
|
||||
process.exit();
|
||||
}
|
||||
|
||||
// Check using pm2
|
||||
check_PM2_Process () {
|
||||
Log.info("updatenotification: Checking PM2 using...");
|
||||
return new Promise((resolve) => {
|
||||
commandExists("pm2")
|
||||
.then(async () => {
|
||||
var PM2_List = await this.PM2_GetList();
|
||||
if (!PM2_List) {
|
||||
Log.error("updatenotification: [PM2] Can't get process List!");
|
||||
this.usePM2 = false;
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
PM2_List.forEach((pm) => {
|
||||
if (pm.pm2_env.version === this.version && pm.pm2_env.status === "online" && pm.pm2_env.PWD.includes(this.root_path)) {
|
||||
this.PM2 = pm.name;
|
||||
this.usePM2 = true;
|
||||
Log.info("updatenotification: You are using pm2 with", this.PM2);
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
if (!this.PM2) {
|
||||
Log.info("updatenotification: You are not using pm2");
|
||||
this.usePM2 = false;
|
||||
resolve(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
Log.info("updatenotification: You are not using pm2");
|
||||
this.usePM2 = false;
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Get the list of pm2 process
|
||||
PM2_GetList () {
|
||||
return new Promise((resolve) => {
|
||||
Exec("pm2 jlist", (err, std, sde) => {
|
||||
if (err) {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let result = JSON.parse(std);
|
||||
resolve(result);
|
||||
} catch (e) {
|
||||
Log.error("updatenotification: [PM2] can't GetList!");
|
||||
Log.debug("updatenotification: [PM2] GetList is not an JSON format", e);
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// check if module is MagicMirror
|
||||
isMagicMirror (module) {
|
||||
if (module === "MagicMirror") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// search update module command
|
||||
applyCommand (module) {
|
||||
if (this.isMagicMirror(module.module)) return null;
|
||||
let command = null;
|
||||
this.updates.forEach((updater) => {
|
||||
if (updater[module]) command = updater[module];
|
||||
});
|
||||
return command;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Updater;
|
@@ -9,13 +9,18 @@ Module.register("updatenotification", {
|
||||
updateInterval: 10 * 60 * 1000, // every 10 minutes
|
||||
refreshInterval: 24 * 60 * 60 * 1000, // one day
|
||||
ignoreModules: [],
|
||||
sendUpdatesNotifications: false
|
||||
sendUpdatesNotifications: false,
|
||||
updates: [],
|
||||
updateTimeout: 2 * 60 * 1000, // max update duration
|
||||
updateAutorestart: false // autoRestart MM when update done ?
|
||||
},
|
||||
|
||||
suspended: false,
|
||||
moduleList: {},
|
||||
needRestart: false,
|
||||
updates: {},
|
||||
|
||||
start() {
|
||||
start () {
|
||||
Log.info(`Starting module: ${this.name}`);
|
||||
this.addFilters();
|
||||
setInterval(() => {
|
||||
@@ -24,16 +29,16 @@ Module.register("updatenotification", {
|
||||
}, this.config.refreshInterval);
|
||||
},
|
||||
|
||||
suspend() {
|
||||
suspend () {
|
||||
this.suspended = true;
|
||||
},
|
||||
|
||||
resume() {
|
||||
resume () {
|
||||
this.suspended = false;
|
||||
this.updateDom(2);
|
||||
},
|
||||
|
||||
notificationReceived(notification) {
|
||||
notificationReceived (notification) {
|
||||
switch (notification) {
|
||||
case "DOM_OBJECTS_CREATED":
|
||||
this.sendSocketNotification("CONFIG", this.config);
|
||||
@@ -45,30 +50,33 @@ Module.register("updatenotification", {
|
||||
}
|
||||
},
|
||||
|
||||
socketNotificationReceived(notification, payload) {
|
||||
socketNotificationReceived (notification, payload) {
|
||||
switch (notification) {
|
||||
case "STATUS":
|
||||
case "REPO_STATUS":
|
||||
this.updateUI(payload);
|
||||
break;
|
||||
case "UPDATES":
|
||||
this.sendNotification("UPDATES", payload);
|
||||
break;
|
||||
case "UPDATE_STATUS":
|
||||
this.updatesNotifier(payload);
|
||||
break;
|
||||
}
|
||||
},
|
||||
|
||||
getStyles() {
|
||||
getStyles () {
|
||||
return [`${this.name}.css`];
|
||||
},
|
||||
|
||||
getTemplate() {
|
||||
getTemplate () {
|
||||
return `${this.name}.njk`;
|
||||
},
|
||||
|
||||
getTemplateData() {
|
||||
return { moduleList: this.moduleList, suspended: this.suspended };
|
||||
getTemplateData () {
|
||||
return { moduleList: this.moduleList, updatesList: this.updates, suspended: this.suspended, needRestart: this.needRestart };
|
||||
},
|
||||
|
||||
updateUI(payload) {
|
||||
updateUI (payload) {
|
||||
if (payload && payload.behind > 0) {
|
||||
// if we haven't seen info for this module
|
||||
if (this.moduleList[payload.module] === undefined) {
|
||||
@@ -86,7 +94,7 @@ Module.register("updatenotification", {
|
||||
}
|
||||
},
|
||||
|
||||
addFilters() {
|
||||
addFilters () {
|
||||
this.nunjucksEnvironment().addFilter("diffLink", (text, status) => {
|
||||
if (status.module !== "MagicMirror") {
|
||||
return text;
|
||||
@@ -96,5 +104,29 @@ Module.register("updatenotification", {
|
||||
const remoteRef = status.tracking.replace(/.*\//, "");
|
||||
return `<a href="https://github.com/MichMich/MagicMirror/compare/${localRef}...${remoteRef}" class="xsmall dimmed difflink" target="_blank">${text}</a>`;
|
||||
});
|
||||
},
|
||||
|
||||
updatesNotifier (payload, done = true) {
|
||||
if (this.updates[payload.name] === undefined) {
|
||||
this.updates[payload.name] = {
|
||||
name: payload.name,
|
||||
done: done
|
||||
};
|
||||
|
||||
if (payload.error) {
|
||||
this.sendSocketNotification("UPDATE_ERROR", payload.name);
|
||||
this.updates[payload.name].done = false;
|
||||
} else {
|
||||
if (payload.updated) {
|
||||
delete this.moduleList[payload.name];
|
||||
this.updates[payload.name].done = true;
|
||||
}
|
||||
if (payload.needRestart) {
|
||||
this.needRestart = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.updateDom(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
@@ -1,4 +1,13 @@
|
||||
{% if not suspended %}
|
||||
{% if needRestart %}
|
||||
<div class="small bright">
|
||||
<i class="fas fa-rotate"></i>
|
||||
<span>
|
||||
{% set restartTextLabel = "UPDATE_NOTIFICATION_NEED-RESTART" %}
|
||||
{{ restartTextLabel | translate() | safe }}
|
||||
</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% for name, status in moduleList %}
|
||||
<div class="small bright">
|
||||
<i class="fas fa-exclamation-circle"></i>
|
||||
@@ -12,4 +21,21 @@
|
||||
{{ subTextLabel | translate({COMMIT_COUNT: status.behind, BRANCH_NAME: status.current}) | diffLink(status) | safe }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% for name, status in updatesList %}
|
||||
<div class="small bright">
|
||||
{% if status.done %}
|
||||
<i class="fas fa-check" style="color: lightgreen;"></i>
|
||||
<span>
|
||||
{% set updateTextLabel = "UPDATE_NOTIFICATION_DONE" %}
|
||||
{{ updateTextLabel | translate({MODULE_NAME: name}) | safe }}
|
||||
</span>
|
||||
{% else %}
|
||||
<i class="fas fa-xmark" style="color: red;"></i>
|
||||
<span>
|
||||
{% set updateTextLabel = "UPDATE_NOTIFICATION_ERROR" %}
|
||||
{{ updateTextLabel | translate({MODULE_NAME: name}) | safe }}
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
@@ -7,7 +7,7 @@
|
||||
* @param {Array.<string>} expectedResponseHeaders the expected HTTP headers to receive
|
||||
* @returns {Promise} resolved when the fetch is done. The response headers is placed in a headers-property (provided the response does not already contain a headers-property).
|
||||
*/
|
||||
async function performWebRequest(url, type = "json", useCorsProxy = false, requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
async function performWebRequest (url, type = "json", useCorsProxy = false, requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
const request = {};
|
||||
let requestUrl;
|
||||
if (useCorsProxy) {
|
||||
@@ -165,8 +165,7 @@ const formatTime = (config, time) => {
|
||||
return date.format("HH:mm");
|
||||
};
|
||||
|
||||
if (typeof module !== "undefined")
|
||||
module.exports = {
|
||||
performWebRequest,
|
||||
formatTime
|
||||
};
|
||||
if (typeof module !== "undefined") module.exports = {
|
||||
performWebRequest,
|
||||
formatTime
|
||||
};
|
||||
|
@@ -49,7 +49,7 @@ WeatherProvider.register("envcanada", {
|
||||
// Set config values (equates to weather module config values). Also set values pertaining to caching of
|
||||
// Today's temperature forecast (for use in the Forecast functions below)
|
||||
//
|
||||
setConfig: function (config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
|
||||
this.todayTempCacheMin = 0;
|
||||
@@ -61,7 +61,7 @@ WeatherProvider.register("envcanada", {
|
||||
//
|
||||
// Called when the weather provider is started
|
||||
//
|
||||
start: function () {
|
||||
start () {
|
||||
Log.info(`Weather provider: ${this.providerName} started.`);
|
||||
this.setFetchedLocation(this.config.location);
|
||||
},
|
||||
@@ -69,7 +69,7 @@ WeatherProvider.register("envcanada", {
|
||||
//
|
||||
// Override the fetchCurrentWeather method to query EC and construct a Current weather object
|
||||
//
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl(), "xml")
|
||||
.then((data) => {
|
||||
if (!data) {
|
||||
@@ -89,7 +89,7 @@ WeatherProvider.register("envcanada", {
|
||||
//
|
||||
// Override the fetchWeatherForecast method to query EC and construct Forecast weather objects
|
||||
//
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl(), "xml")
|
||||
.then((data) => {
|
||||
if (!data) {
|
||||
@@ -109,7 +109,7 @@ WeatherProvider.register("envcanada", {
|
||||
//
|
||||
// Override the fetchWeatherHourly method to query EC and construct Forecast weather objects
|
||||
//
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.fetchData(this.getUrl(), "xml")
|
||||
.then((data) => {
|
||||
if (!data) {
|
||||
@@ -137,7 +137,7 @@ WeatherProvider.register("envcanada", {
|
||||
// URL defaults to the English version simply because there is no language dependency in the data
|
||||
// being accessed. This is only pertinent when using the EC data elements that contain a textual forecast.
|
||||
//
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return `https://dd.weather.gc.ca/citypage_weather/xml/${this.config.provCode}/${this.config.siteCode}_e.xml`;
|
||||
},
|
||||
|
||||
@@ -145,7 +145,7 @@ WeatherProvider.register("envcanada", {
|
||||
// Generate a WeatherObject based on current EC weather conditions
|
||||
//
|
||||
|
||||
generateWeatherObjectFromCurrentWeather(ECdoc) {
|
||||
generateWeatherObjectFromCurrentWeather (ECdoc) {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
// There are instances where EC will update weather data and current temperature will not be
|
||||
@@ -216,7 +216,7 @@ WeatherProvider.register("envcanada", {
|
||||
// Generate an array of WeatherObjects based on EC weather forecast
|
||||
//
|
||||
|
||||
generateWeatherObjectsFromForecast(ECdoc) {
|
||||
generateWeatherObjectsFromForecast (ECdoc) {
|
||||
// Declare an array to hold each day's forecast object
|
||||
|
||||
const days = [];
|
||||
@@ -360,7 +360,7 @@ WeatherProvider.register("envcanada", {
|
||||
// Generate an array of WeatherObjects based on EC hourly weather forecast
|
||||
//
|
||||
|
||||
generateWeatherObjectsFromHourly(ECdoc) {
|
||||
generateWeatherObjectsFromHourly (ECdoc) {
|
||||
// Declare an array to hold each hour's forecast object
|
||||
|
||||
const hours = [];
|
||||
@@ -416,7 +416,7 @@ WeatherProvider.register("envcanada", {
|
||||
// the next Forecast element should be considered - i.e. look at Today *and* Tonight vs.Tonight-only
|
||||
//
|
||||
|
||||
setMinMaxTemps(weather, foreGroup, today, fullDay, currentTemp) {
|
||||
setMinMaxTemps (weather, foreGroup, today, fullDay, currentTemp) {
|
||||
const todayTemp = foreGroup[today].querySelector("temperatures temperature").textContent;
|
||||
|
||||
const todayClass = foreGroup[today].querySelector("temperatures temperature").getAttribute("class");
|
||||
@@ -498,7 +498,7 @@ WeatherProvider.register("envcanada", {
|
||||
// the nightime forecast after a certain point in that specific scenario.
|
||||
//
|
||||
|
||||
setPrecipitation(weather, foreGroup, today) {
|
||||
setPrecipitation (weather, foreGroup, today) {
|
||||
if (foreGroup[today].querySelector("precipitation accumulation")) {
|
||||
weather.precipitationAmount = foreGroup[today].querySelector("precipitation accumulation amount").textContent * 1.0;
|
||||
weather.precipitationUnits = foreGroup[today].querySelector("precipitation accumulation amount").getAttribute("units");
|
||||
@@ -514,7 +514,7 @@ WeatherProvider.register("envcanada", {
|
||||
//
|
||||
// Convert the icons to a more usable name.
|
||||
//
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
"00": "day-sunny",
|
||||
"01": "day-sunny",
|
||||
|
@@ -140,11 +140,11 @@ WeatherProvider.register("openmeteo", {
|
||||
"et0_fao_evapotranspiration"
|
||||
],
|
||||
|
||||
fetchedLocation: function () {
|
||||
fetchedLocation () {
|
||||
return this.fetchedLocationName || "";
|
||||
},
|
||||
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => this.parseWeatherApiResponse(data))
|
||||
.then((parsedData) => {
|
||||
@@ -162,7 +162,7 @@ WeatherProvider.register("openmeteo", {
|
||||
.finally(() => this.updateAvailable());
|
||||
},
|
||||
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => this.parseWeatherApiResponse(data))
|
||||
.then((parsedData) => {
|
||||
@@ -180,7 +180,7 @@ WeatherProvider.register("openmeteo", {
|
||||
.finally(() => this.updateAvailable());
|
||||
},
|
||||
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => this.parseWeatherApiResponse(data))
|
||||
.then((parsedData) => {
|
||||
@@ -202,7 +202,7 @@ WeatherProvider.register("openmeteo", {
|
||||
* Overrides method for setting config to check if endpoint is correct for hourly
|
||||
* @param {object} config The configuration object
|
||||
*/
|
||||
setConfig(config) {
|
||||
setConfig (config) {
|
||||
this.config = {
|
||||
lang: config.lang ?? "en",
|
||||
...this.defaults,
|
||||
@@ -226,7 +226,7 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Generate valid query params to perform the request
|
||||
getQueryParameters() {
|
||||
getQueryParameters () {
|
||||
let params = {
|
||||
latitude: this.config.lat,
|
||||
longitude: this.config.lon,
|
||||
@@ -278,25 +278,23 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Create a URL from the config and base URL.
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return `${this.config.apiBase}/forecast?${this.getQueryParameters()}`;
|
||||
},
|
||||
|
||||
// Transpose hourly and daily data matrices
|
||||
transposeDataMatrix(data) {
|
||||
return data.time.map((_, index) =>
|
||||
Object.keys(data).reduce((row, key) => {
|
||||
return {
|
||||
...row,
|
||||
// Parse time values as momentjs instances
|
||||
[key]: ["time", "sunrise", "sunset"].includes(key) ? moment.unix(data[key][index]) : data[key][index]
|
||||
};
|
||||
}, {})
|
||||
);
|
||||
transposeDataMatrix (data) {
|
||||
return data.time.map((_, index) => Object.keys(data).reduce((row, key) => {
|
||||
return {
|
||||
...row,
|
||||
// Parse time values as momentjs instances
|
||||
[key]: ["time", "sunrise", "sunset"].includes(key) ? moment.unix(data[key][index]) : data[key][index]
|
||||
};
|
||||
}, {}));
|
||||
},
|
||||
|
||||
// Sanitize and validate API response
|
||||
parseWeatherApiResponse(data) {
|
||||
parseWeatherApiResponse (data) {
|
||||
const validByType = {
|
||||
current: data.current_weather && data.current_weather.time,
|
||||
hourly: data.hourly && data.hourly.time && Array.isArray(data.hourly.time) && data.hourly.time.length > 0,
|
||||
@@ -334,7 +332,7 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Reverse geocoding from latitude and longitude provided
|
||||
fetchLocation() {
|
||||
fetchLocation () {
|
||||
this.fetchData(`${GEOCODE_BASE}?latitude=${this.config.lat}&longitude=${this.config.lon}&localityLanguage=${this.config.lang}`)
|
||||
.then((data) => {
|
||||
if (!data || !data.city) {
|
||||
@@ -349,7 +347,8 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Implement WeatherDay generator.
|
||||
generateWeatherDayFromCurrentWeather(weather) {
|
||||
generateWeatherDayFromCurrentWeather (weather) {
|
||||
|
||||
/**
|
||||
* Since some units comes from API response "splitted" into daily, hourly and current_weather
|
||||
* every time you request it, you have to ensure to get the data from the right place every time.
|
||||
@@ -394,10 +393,10 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Implement WeatherForecast generator.
|
||||
generateWeatherObjectsFromForecast(weathers) {
|
||||
generateWeatherObjectsFromForecast (weathers) {
|
||||
const days = [];
|
||||
|
||||
weathers.daily.forEach((weather, i) => {
|
||||
weathers.daily.forEach((weather) => {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
currentWeather.date = weather.time;
|
||||
@@ -422,7 +421,7 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Implement WeatherHourly generator.
|
||||
generateWeatherObjectsFromHourly(weathers) {
|
||||
generateWeatherObjectsFromHourly (weathers) {
|
||||
const hours = [];
|
||||
const now = moment();
|
||||
|
||||
@@ -457,7 +456,7 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Map icons from Dark Sky to our icons.
|
||||
convertWeatherType(weathercode, isDayTime) {
|
||||
convertWeatherType (weathercode, isDayTime) {
|
||||
const weatherConditions = {
|
||||
0: "clear",
|
||||
1: "mainly-clear",
|
||||
@@ -542,7 +541,7 @@ WeatherProvider.register("openmeteo", {
|
||||
},
|
||||
|
||||
// Define required scripts.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["moment.js"];
|
||||
}
|
||||
});
|
||||
|
@@ -27,7 +27,7 @@ WeatherProvider.register("openweathermap", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchCurrentWeather method.
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
let currentWeather;
|
||||
@@ -46,7 +46,7 @@ WeatherProvider.register("openweathermap", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchWeatherForecast method.
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
let forecast;
|
||||
@@ -68,7 +68,7 @@ WeatherProvider.register("openweathermap", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchWeatherHourly method.
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
if (!data) {
|
||||
@@ -92,7 +92,7 @@ WeatherProvider.register("openweathermap", {
|
||||
* Overrides method for setting config to check if endpoint is correct for hourly
|
||||
* @param {object} config The configuration object
|
||||
*/
|
||||
setConfig(config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
if (!this.config.weatherEndpoint) {
|
||||
switch (this.config.type) {
|
||||
@@ -116,14 +116,14 @@ WeatherProvider.register("openweathermap", {
|
||||
/*
|
||||
* Gets the complete url for the request
|
||||
*/
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return this.config.apiBase + this.config.apiVersion + this.config.weatherEndpoint + this.getParams();
|
||||
},
|
||||
|
||||
/*
|
||||
* Generate a WeatherObject based on currentWeatherInformation
|
||||
*/
|
||||
generateWeatherObjectFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherObjectFromCurrentWeather (currentWeatherData) {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
currentWeather.date = moment.unix(currentWeatherData.dt);
|
||||
@@ -142,7 +142,7 @@ WeatherProvider.register("openweathermap", {
|
||||
/*
|
||||
* Generate WeatherObjects based on forecast information
|
||||
*/
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
if (this.config.weatherEndpoint === "/forecast") {
|
||||
return this.generateForecastHourly(forecasts);
|
||||
} else if (this.config.weatherEndpoint === "/forecast/daily") {
|
||||
@@ -155,7 +155,7 @@ WeatherProvider.register("openweathermap", {
|
||||
/*
|
||||
* Generate WeatherObjects based on One Call forecast information
|
||||
*/
|
||||
generateWeatherObjectsFromOnecall(data) {
|
||||
generateWeatherObjectsFromOnecall (data) {
|
||||
if (this.config.weatherEndpoint === "/onecall") {
|
||||
return this.fetchOnecall(data);
|
||||
}
|
||||
@@ -167,7 +167,7 @@ WeatherProvider.register("openweathermap", {
|
||||
* Generate forecast information for 3-hourly forecast (available for free
|
||||
* subscription).
|
||||
*/
|
||||
generateForecastHourly(forecasts) {
|
||||
generateForecastHourly (forecasts) {
|
||||
// initial variable declaration
|
||||
const days = [];
|
||||
// variables for temperature range and rain
|
||||
@@ -241,7 +241,7 @@ WeatherProvider.register("openweathermap", {
|
||||
* Generate forecast information for daily forecast (available for paid
|
||||
* subscription or old apiKey).
|
||||
*/
|
||||
generateForecastDaily(forecasts) {
|
||||
generateForecastDaily (forecasts) {
|
||||
// initial variable declaration
|
||||
const days = [];
|
||||
|
||||
@@ -281,7 +281,7 @@ WeatherProvider.register("openweathermap", {
|
||||
* Factors in timezone offsets.
|
||||
* Minutely forecasts are excluded for the moment, see getParams().
|
||||
*/
|
||||
fetchOnecall(data) {
|
||||
fetchOnecall (data) {
|
||||
let precip = false;
|
||||
|
||||
// get current weather, if requested
|
||||
@@ -382,7 +382,7 @@ WeatherProvider.register("openweathermap", {
|
||||
/*
|
||||
* Convert the OpenWeatherMap icons to a more usable name.
|
||||
*/
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
"01d": "day-sunny",
|
||||
"02d": "day-cloudy",
|
||||
@@ -412,7 +412,7 @@ WeatherProvider.register("openweathermap", {
|
||||
*
|
||||
* return String - URL params.
|
||||
*/
|
||||
getParams() {
|
||||
getParams () {
|
||||
let params = "?";
|
||||
if (this.config.weatherEndpoint === "/onecall") {
|
||||
params += `lat=${this.config.lat}`;
|
||||
|
@@ -21,7 +21,7 @@ const OverrideWrapper = Class.extend({
|
||||
notificationWeatherObject: null,
|
||||
currentOverrideWeatherObject: null,
|
||||
|
||||
init(baseProvider) {
|
||||
init (baseProvider) {
|
||||
this.baseProvider = baseProvider;
|
||||
|
||||
// Binding the scope of current weather functions so any fetchData calls with
|
||||
@@ -33,43 +33,43 @@ const OverrideWrapper = Class.extend({
|
||||
|
||||
/* Unchanged Api Provider Methods */
|
||||
|
||||
setConfig(config) {
|
||||
setConfig (config) {
|
||||
this.baseProvider.setConfig(config);
|
||||
},
|
||||
start() {
|
||||
start () {
|
||||
this.baseProvider.start();
|
||||
},
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.baseProvider.fetchCurrentWeather();
|
||||
},
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.baseProvider.fetchWeatherForecast();
|
||||
},
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.baseProvider.fetchEatherHourly();
|
||||
},
|
||||
weatherForecast() {
|
||||
weatherForecast () {
|
||||
this.baseProvider.weatherForecast();
|
||||
},
|
||||
weatherHourly() {
|
||||
weatherHourly () {
|
||||
this.baseProvider.weatherHourly();
|
||||
},
|
||||
fetchedLocation() {
|
||||
fetchedLocation () {
|
||||
this.baseProvider.fetchedLocation();
|
||||
},
|
||||
setWeatherForecast(weatherForecastArray) {
|
||||
setWeatherForecast (weatherForecastArray) {
|
||||
this.baseProvider.setWeatherForecast(weatherForecastArray);
|
||||
},
|
||||
setWeatherHourly(weatherHourlyArray) {
|
||||
setWeatherHourly (weatherHourlyArray) {
|
||||
this.baseProvider.setWeatherHourly(weatherHourlyArray);
|
||||
},
|
||||
setFetchedLocation(name) {
|
||||
setFetchedLocation (name) {
|
||||
this.baseProvider.setFetchedLocation(name);
|
||||
},
|
||||
updateAvailable() {
|
||||
updateAvailable () {
|
||||
this.baseProvider.updateAvailable();
|
||||
},
|
||||
async fetchData(url, type = "json", requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
async fetchData (url, type = "json", requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
this.baseProvider.fetchData(url, type, requestHeaders, expectedResponseHeaders);
|
||||
},
|
||||
|
||||
@@ -79,7 +79,7 @@ const OverrideWrapper = Class.extend({
|
||||
* Override to return this scope's
|
||||
* @returns {WeatherObject} The current weather object. May or may not contain overridden data.
|
||||
*/
|
||||
currentWeather() {
|
||||
currentWeather () {
|
||||
return this.currentOverrideWeatherObject;
|
||||
},
|
||||
|
||||
@@ -89,7 +89,7 @@ const OverrideWrapper = Class.extend({
|
||||
* api provider fetchData implementation.
|
||||
* @param {WeatherObject} currentWeatherObject - the api provider weather object
|
||||
*/
|
||||
setCurrentWeather(currentWeatherObject) {
|
||||
setCurrentWeather (currentWeatherObject) {
|
||||
this.currentOverrideWeatherObject = Object.assign(currentWeatherObject, this.notificationWeatherObject);
|
||||
},
|
||||
|
||||
@@ -101,7 +101,7 @@ const OverrideWrapper = Class.extend({
|
||||
* notification. Represents information to augment the
|
||||
* existing currentOverrideWeatherObject with.
|
||||
*/
|
||||
notificationReceived(payload) {
|
||||
notificationReceived (payload) {
|
||||
this.notificationWeatherObject = payload;
|
||||
|
||||
// setCurrentWeather combines the newly received notification weather with
|
||||
|
@@ -25,7 +25,7 @@ WeatherProvider.register("pirateweather", {
|
||||
lon: 0
|
||||
},
|
||||
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
if (!data || !data.currently || typeof data.currently.temperature === "undefined") {
|
||||
@@ -42,7 +42,7 @@ WeatherProvider.register("pirateweather", {
|
||||
.finally(() => this.updateAvailable());
|
||||
},
|
||||
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
if (!data || !data.daily || !data.daily.data.length) {
|
||||
@@ -60,12 +60,12 @@ WeatherProvider.register("pirateweather", {
|
||||
},
|
||||
|
||||
// Create a URL from the config and base URL.
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return `${this.config.apiBase}${this.config.weatherEndpoint}/${this.config.apiKey}/${this.config.lat},${this.config.lon}?units=si&lang=${this.config.lang}`;
|
||||
},
|
||||
|
||||
// Implement WeatherDay generator.
|
||||
generateWeatherDayFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherDayFromCurrentWeather (currentWeatherData) {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
currentWeather.date = moment();
|
||||
@@ -80,7 +80,7 @@ WeatherProvider.register("pirateweather", {
|
||||
return currentWeather;
|
||||
},
|
||||
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
const days = [];
|
||||
|
||||
for (const forecast of forecasts) {
|
||||
@@ -114,7 +114,7 @@ WeatherProvider.register("pirateweather", {
|
||||
},
|
||||
|
||||
// Map icons from Pirate Weather to our icons.
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
"clear-day": "day-sunny",
|
||||
"clear-night": "night-clear",
|
||||
|
@@ -24,7 +24,7 @@ WeatherProvider.register("smhi", {
|
||||
/**
|
||||
* Implements method in interface for fetching current weather.
|
||||
*/
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getURL())
|
||||
.then((data) => {
|
||||
const closest = this.getClosestToCurrentTime(data.timeSeries);
|
||||
@@ -40,7 +40,7 @@ WeatherProvider.register("smhi", {
|
||||
/**
|
||||
* Implements method in interface for fetching a multi-day forecast.
|
||||
*/
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getURL())
|
||||
.then((data) => {
|
||||
const coordinates = this.resolveCoordinates(data);
|
||||
@@ -55,7 +55,7 @@ WeatherProvider.register("smhi", {
|
||||
/**
|
||||
* Implements method in interface for fetching hourly forecasts.
|
||||
*/
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.fetchData(this.getURL())
|
||||
.then((data) => {
|
||||
const coordinates = this.resolveCoordinates(data);
|
||||
@@ -71,7 +71,7 @@ WeatherProvider.register("smhi", {
|
||||
* Overrides method for setting config with checks for the precipitationValue being unset or invalid
|
||||
* @param {object} config The configuration object
|
||||
*/
|
||||
setConfig(config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
if (!config.precipitationValue || ["pmin", "pmean", "pmedian", "pmax"].indexOf(config.precipitationValue) === -1) {
|
||||
Log.log(`invalid or not set: ${config.precipitationValue}`);
|
||||
@@ -84,7 +84,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {object[]} times Array of time objects
|
||||
* @returns {object} The weatherdata closest to the current time
|
||||
*/
|
||||
getClosestToCurrentTime(times) {
|
||||
getClosestToCurrentTime (times) {
|
||||
let now = moment();
|
||||
let minDiff = undefined;
|
||||
for (const time of times) {
|
||||
@@ -100,7 +100,7 @@ WeatherProvider.register("smhi", {
|
||||
* Get the forecast url for the configured coordinates
|
||||
* @returns {string} the url for the specified coordinates
|
||||
*/
|
||||
getURL() {
|
||||
getURL () {
|
||||
const formatter = new Intl.NumberFormat("en-US", {
|
||||
minimumFractionDigits: 6,
|
||||
maximumFractionDigits: 6
|
||||
@@ -115,7 +115,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {object} weatherData Weatherdata to use for the calculation
|
||||
* @returns {number} The apparent temperature
|
||||
*/
|
||||
calculateApparentTemperature(weatherData) {
|
||||
calculateApparentTemperature (weatherData) {
|
||||
const Ta = this.paramValue(weatherData, "t");
|
||||
const rh = this.paramValue(weatherData, "r");
|
||||
const ws = this.paramValue(weatherData, "ws");
|
||||
@@ -132,7 +132,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {object} coordinates Coordinates of the locations of the weather
|
||||
* @returns {WeatherObject} The converted weatherdata at the specified location
|
||||
*/
|
||||
convertWeatherDataToObject(weatherData, coordinates) {
|
||||
convertWeatherDataToObject (weatherData, coordinates) {
|
||||
let currentWeather = new WeatherObject();
|
||||
|
||||
currentWeather.date = moment(weatherData.validTime);
|
||||
@@ -178,7 +178,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {string} groupBy The interval to use for grouping the data (day, hour)
|
||||
* @returns {WeatherObject[]} Array of weatherobjects
|
||||
*/
|
||||
convertWeatherDataGroupedBy(allWeatherData, coordinates, groupBy = "day") {
|
||||
convertWeatherDataGroupedBy (allWeatherData, coordinates, groupBy = "day") {
|
||||
let currentWeather;
|
||||
let result = [];
|
||||
|
||||
@@ -227,7 +227,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {object} data Response data from the weather service
|
||||
* @returns {{lon, lat}} the lat/long coordinates of the data
|
||||
*/
|
||||
resolveCoordinates(data) {
|
||||
resolveCoordinates (data) {
|
||||
return { lat: data.geometry.coordinates[0][1], lon: data.geometry.coordinates[0][0] };
|
||||
},
|
||||
|
||||
@@ -237,7 +237,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {object[]} data Response data from the weather service
|
||||
* @returns {object[]} Given data with filled gaps
|
||||
*/
|
||||
fillInGaps(data) {
|
||||
fillInGaps (data) {
|
||||
let result = [];
|
||||
for (let i = 1; i < data.length; i++) {
|
||||
let to = moment(data[i].validTime);
|
||||
@@ -259,7 +259,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {string} name The name of the property
|
||||
* @returns {*} The value of the property in the weatherdata
|
||||
*/
|
||||
paramValue(currentWeatherData, name) {
|
||||
paramValue (currentWeatherData, name) {
|
||||
return currentWeatherData.parameters.filter((p) => p.name === name).flatMap((p) => p.values)[0];
|
||||
},
|
||||
|
||||
@@ -271,7 +271,7 @@ WeatherProvider.register("smhi", {
|
||||
* @param {boolean} isDayTime True if the icon should be for daytime, false for nighttime
|
||||
* @returns {string} The icon name for the MagicMirror
|
||||
*/
|
||||
convertWeatherType(input, isDayTime) {
|
||||
convertWeatherType (input, isDayTime) {
|
||||
switch (input) {
|
||||
case 1:
|
||||
return isDayTime ? "day-sunny" : "night-clear"; // Clear sky
|
||||
|
@@ -22,7 +22,7 @@ WeatherProvider.register("ukmetoffice", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchCurrentWeather method.
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl("3hourly"))
|
||||
.then((data) => {
|
||||
if (!data || !data.SiteRep || !data.SiteRep.DV || !data.SiteRep.DV.Location || !data.SiteRep.DV.Location.Period || data.SiteRep.DV.Location.Period.length === 0) {
|
||||
@@ -43,7 +43,7 @@ WeatherProvider.register("ukmetoffice", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchCurrentWeather method.
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl("daily"))
|
||||
.then((data) => {
|
||||
if (!data || !data.SiteRep || !data.SiteRep.DV || !data.SiteRep.DV.Location || !data.SiteRep.DV.Location.Period || data.SiteRep.DV.Location.Period.length === 0) {
|
||||
@@ -67,14 +67,14 @@ WeatherProvider.register("ukmetoffice", {
|
||||
/*
|
||||
* Gets the complete url for the request
|
||||
*/
|
||||
getUrl(forecastType) {
|
||||
getUrl (forecastType) {
|
||||
return this.config.apiBase + this.config.locationID + this.getParams(forecastType);
|
||||
},
|
||||
|
||||
/*
|
||||
* Generate a WeatherObject based on currentWeatherInformation
|
||||
*/
|
||||
generateWeatherObjectFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherObjectFromCurrentWeather (currentWeatherData) {
|
||||
const currentWeather = new WeatherObject();
|
||||
const location = currentWeatherData.SiteRep.DV.Location;
|
||||
|
||||
@@ -119,7 +119,7 @@ WeatherProvider.register("ukmetoffice", {
|
||||
/*
|
||||
* Generate WeatherObjects based on forecast information
|
||||
*/
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
const days = [];
|
||||
|
||||
// loop round the (5) periods getting the data
|
||||
@@ -150,7 +150,7 @@ WeatherProvider.register("ukmetoffice", {
|
||||
/*
|
||||
* Convert the Met Office icons to a more usable name.
|
||||
*/
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
0: "night-clear",
|
||||
1: "day-sunny",
|
||||
@@ -192,7 +192,7 @@ WeatherProvider.register("ukmetoffice", {
|
||||
* @param {string} forecastType daily or 3hourly forecast
|
||||
* @returns {string} url
|
||||
*/
|
||||
getParams(forecastType) {
|
||||
getParams (forecastType) {
|
||||
let params = "?";
|
||||
params += `res=${forecastType}`;
|
||||
params += `&key=${this.config.apiKey}`;
|
||||
|
@@ -53,7 +53,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Build URL with query strings according to DataHub API (https://metoffice.apiconnect.ibmcloud.com/metoffice/production/api)
|
||||
getUrl(forecastType) {
|
||||
getUrl (forecastType) {
|
||||
let queryStrings = "?";
|
||||
queryStrings += `latitude=${this.config.lat}`;
|
||||
queryStrings += `&longitude=${this.config.lon}`;
|
||||
@@ -66,7 +66,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
// Build the list of headers for the request
|
||||
// For DataHub requests, the API key/secret are sent in the headers rather than as query strings.
|
||||
// Headers defined according to Data Hub API (https://metoffice.apiconnect.ibmcloud.com/metoffice/production/api)
|
||||
getHeaders() {
|
||||
getHeaders () {
|
||||
return {
|
||||
accept: "application/json",
|
||||
"x-ibm-client-id": this.config.apiKey,
|
||||
@@ -75,7 +75,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Fetch data using supplied URL and request headers
|
||||
async fetchWeather(url, headers) {
|
||||
async fetchWeather (url, headers) {
|
||||
const response = await fetch(url, { headers: headers });
|
||||
|
||||
// Return JSON data
|
||||
@@ -83,7 +83,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Fetch hourly forecast data (to use for current weather)
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchWeather(this.getUrl("hourly"), this.getHeaders())
|
||||
.then((data) => {
|
||||
// Check data is usable
|
||||
@@ -111,7 +111,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Create a WeatherObject using current weather data (data for the current hour)
|
||||
generateWeatherObjectFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherObjectFromCurrentWeather (currentWeatherData) {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
// Extract the actual forecasts
|
||||
@@ -152,7 +152,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Fetch daily forecast data
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchWeather(this.getUrl("daily"), this.getHeaders())
|
||||
.then((data) => {
|
||||
// Check data is usable
|
||||
@@ -180,7 +180,7 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Create a WeatherObject for each day using daily forecast data
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
const dailyForecasts = [];
|
||||
|
||||
// Extract the actual forecasts
|
||||
@@ -225,14 +225,14 @@ WeatherProvider.register("ukmetofficedatahub", {
|
||||
},
|
||||
|
||||
// Set the fetched location name.
|
||||
setFetchedLocation: function (name) {
|
||||
setFetchedLocation (name) {
|
||||
this.fetchedLocationName = name;
|
||||
},
|
||||
|
||||
// Match the Met Office "significant weather code" to a weathericons.css icon
|
||||
// Use: https://metoffice.apiconnect.ibmcloud.com/metoffice/production/node/264
|
||||
// and: https://erikflowers.github.io/weather-icons/
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
0: "night-clear",
|
||||
1: "day-sunny",
|
||||
|
@@ -23,11 +23,11 @@ WeatherProvider.register("weatherbit", {
|
||||
lon: 0
|
||||
},
|
||||
|
||||
fetchedLocation: function () {
|
||||
fetchedLocation () {
|
||||
return this.fetchedLocationName || "";
|
||||
},
|
||||
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
if (!data || !data.data[0] || typeof data.data[0].temp === "undefined") {
|
||||
@@ -44,7 +44,7 @@ WeatherProvider.register("weatherbit", {
|
||||
.finally(() => this.updateAvailable());
|
||||
},
|
||||
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
if (!data || !data.data) {
|
||||
@@ -67,7 +67,7 @@ WeatherProvider.register("weatherbit", {
|
||||
* Overrides method for setting config to check if endpoint is correct for hourly
|
||||
* @param {object} config The configuration object
|
||||
*/
|
||||
setConfig(config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
if (!this.config.weatherEndpoint) {
|
||||
switch (this.config.type) {
|
||||
@@ -88,12 +88,12 @@ WeatherProvider.register("weatherbit", {
|
||||
},
|
||||
|
||||
// Create a URL from the config and base URL.
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return `${this.config.apiBase}${this.config.weatherEndpoint}?lat=${this.config.lat}&lon=${this.config.lon}&units=M&key=${this.config.apiKey}`;
|
||||
},
|
||||
|
||||
// Implement WeatherDay generator.
|
||||
generateWeatherDayFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherDayFromCurrentWeather (currentWeatherData) {
|
||||
//Calculate TZ Offset and invert to convert Sunrise/Sunset times to Local
|
||||
const d = new Date();
|
||||
let tzOffset = d.getTimezoneOffset();
|
||||
@@ -115,7 +115,7 @@ WeatherProvider.register("weatherbit", {
|
||||
return currentWeather;
|
||||
},
|
||||
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
const days = [];
|
||||
|
||||
for (const forecast of forecasts) {
|
||||
@@ -135,7 +135,7 @@ WeatherProvider.register("weatherbit", {
|
||||
},
|
||||
|
||||
// Map icons from Dark Sky to our icons.
|
||||
convertWeatherType(weatherType) {
|
||||
convertWeatherType (weatherType) {
|
||||
const weatherTypes = {
|
||||
t01d: "day-thunderstorm",
|
||||
t01n: "night-alt-thunderstorm",
|
||||
|
@@ -23,7 +23,7 @@ WeatherProvider.register("weatherflow", {
|
||||
stationid: ""
|
||||
},
|
||||
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
const currentWeather = new WeatherObject();
|
||||
@@ -44,7 +44,7 @@ WeatherProvider.register("weatherflow", {
|
||||
.finally(() => this.updateAvailable());
|
||||
},
|
||||
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.fetchData(this.getUrl())
|
||||
.then((data) => {
|
||||
const days = [];
|
||||
@@ -71,7 +71,7 @@ WeatherProvider.register("weatherflow", {
|
||||
},
|
||||
|
||||
// Create a URL from the config and base URL.
|
||||
getUrl() {
|
||||
getUrl () {
|
||||
return `${this.config.apiBase}better_forecast?station_id=${this.config.stationid}&units_temp=c&units_wind=kph&units_pressure=mb&units_precip=mm&units_distance=km&token=${this.config.token}`;
|
||||
}
|
||||
});
|
||||
|
@@ -37,24 +37,24 @@ WeatherProvider.register("weathergov", {
|
||||
stationObsURL: "tbd",
|
||||
|
||||
// Called to set the config, this config is the same as the weather module's config.
|
||||
setConfig: function (config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
this.config.apiBase = "https://api.weather.gov";
|
||||
this.fetchWxGovURLs(this.config);
|
||||
},
|
||||
|
||||
// Called when the weather provider is about to start.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.info(`Weather provider: ${this.providerName} started.`);
|
||||
},
|
||||
|
||||
// This returns the name of the fetched location or an empty string.
|
||||
fetchedLocation: function () {
|
||||
fetchedLocation () {
|
||||
return this.fetchedLocationName || "";
|
||||
},
|
||||
|
||||
// Overwrite the fetchCurrentWeather method.
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
if (!this.configURLs) {
|
||||
Log.info("fetchCurrentWeather: fetch wx waiting on config URLs");
|
||||
return;
|
||||
@@ -75,7 +75,7 @@ WeatherProvider.register("weathergov", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchWeatherForecast method.
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
if (!this.configURLs) {
|
||||
Log.info("fetchWeatherForecast: fetch wx waiting on config URLs");
|
||||
return;
|
||||
@@ -96,7 +96,7 @@ WeatherProvider.register("weathergov", {
|
||||
},
|
||||
|
||||
// Overwrite the fetchWeatherHourly method.
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
if (!this.configURLs) {
|
||||
Log.info("fetchWeatherHourly: fetch wx waiting on config URLs");
|
||||
return;
|
||||
@@ -122,7 +122,7 @@ WeatherProvider.register("weathergov", {
|
||||
/*
|
||||
* Get specific URLs
|
||||
*/
|
||||
fetchWxGovURLs(config) {
|
||||
fetchWxGovURLs (config) {
|
||||
this.fetchData(`${config.apiBase}/points/${config.lat},${config.lon}`)
|
||||
.then((data) => {
|
||||
if (!data || !data.properties) {
|
||||
@@ -162,12 +162,13 @@ WeatherProvider.register("weathergov", {
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/*
|
||||
* Generate a WeatherObject based on hourlyWeatherInformation
|
||||
* Weather.gov API uses specific units; API does not include choice of units
|
||||
* ... object needs data in units based on config!
|
||||
*/
|
||||
generateWeatherObjectsFromHourly(forecasts) {
|
||||
generateWeatherObjectsFromHourly (forecasts) {
|
||||
const days = [];
|
||||
|
||||
// variable for date
|
||||
@@ -206,7 +207,7 @@ WeatherProvider.register("weathergov", {
|
||||
* Weather.gov API uses specific units; API does not include choice of units
|
||||
* ... object needs data in units based on config!
|
||||
*/
|
||||
generateWeatherObjectFromCurrentWeather(currentWeatherData) {
|
||||
generateWeatherObjectFromCurrentWeather (currentWeatherData) {
|
||||
const currentWeather = new WeatherObject();
|
||||
|
||||
currentWeather.date = moment(currentWeatherData.timestamp);
|
||||
@@ -236,14 +237,14 @@ WeatherProvider.register("weathergov", {
|
||||
/*
|
||||
* Generate WeatherObjects based on forecast information
|
||||
*/
|
||||
generateWeatherObjectsFromForecast(forecasts) {
|
||||
generateWeatherObjectsFromForecast (forecasts) {
|
||||
return this.fetchForecastDaily(forecasts);
|
||||
},
|
||||
|
||||
/*
|
||||
* fetch forecast information for daily forecast.
|
||||
*/
|
||||
fetchForecastDaily(forecasts) {
|
||||
fetchForecastDaily (forecasts) {
|
||||
// initial variable declaration
|
||||
const days = [];
|
||||
// variables for temperature range and rain
|
||||
@@ -306,7 +307,7 @@ WeatherProvider.register("weathergov", {
|
||||
/*
|
||||
* Convert the icons to a more usable name.
|
||||
*/
|
||||
convertWeatherType(weatherType, isDaytime) {
|
||||
convertWeatherType (weatherType, isDaytime) {
|
||||
//https://w1.weather.gov/xml/current_obs/weather.php
|
||||
// There are way too many types to create, so lets just look for certain strings
|
||||
|
||||
|
@@ -18,11 +18,13 @@ WeatherProvider.register("yr", {
|
||||
defaults: {
|
||||
useCorsProxy: true,
|
||||
apiBase: "https://api.met.no/weatherapi",
|
||||
forecastApiVersion: "2.0",
|
||||
sunriseApiVersion: "3.0",
|
||||
altitude: 0,
|
||||
currentForecastHours: 1 //1, 6 or 12
|
||||
},
|
||||
|
||||
start() {
|
||||
start () {
|
||||
if (typeof Storage === "undefined") {
|
||||
//local storage unavailable
|
||||
Log.error("The Yr weather provider requires local storage.");
|
||||
@@ -31,7 +33,7 @@ WeatherProvider.register("yr", {
|
||||
Log.info(`Weather provider: ${this.providerName} started.`);
|
||||
},
|
||||
|
||||
fetchCurrentWeather() {
|
||||
fetchCurrentWeather () {
|
||||
this.getCurrentWeather()
|
||||
.then((currentWeather) => {
|
||||
this.setCurrentWeather(currentWeather);
|
||||
@@ -43,9 +45,8 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
async getCurrentWeather() {
|
||||
const getRequests = [this.getWeatherData(), this.getStellarData()];
|
||||
const [weatherData, stellarData] = await Promise.all(getRequests);
|
||||
async getCurrentWeather () {
|
||||
const [weatherData, stellarData] = await Promise.all([this.getWeatherData(), this.getStellarData()]);
|
||||
if (!stellarData) {
|
||||
Log.warn("No stellar data available.");
|
||||
}
|
||||
@@ -72,7 +73,7 @@ WeatherProvider.register("yr", {
|
||||
return this.getWeatherDataFrom(forecast, stellarData, weatherData.properties.meta.units);
|
||||
},
|
||||
|
||||
getWeatherData() {
|
||||
getWeatherData () {
|
||||
return new Promise((resolve, reject) => {
|
||||
// If a user has several Yr-modules, for instance one current and one forecast, the API calls must be synchronized across classes.
|
||||
// This is to avoid multiple similar calls to the API.
|
||||
@@ -98,7 +99,7 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
getWeatherDataFromYrOrCache(resolve, reject) {
|
||||
getWeatherDataFromYrOrCache (resolve, reject) {
|
||||
localStorage.setItem("yrIsFetchingWeatherData", "true");
|
||||
|
||||
let weatherData = this.getWeatherDataFromCache();
|
||||
@@ -130,16 +131,16 @@ WeatherProvider.register("yr", {
|
||||
}
|
||||
},
|
||||
|
||||
weatherDataIsValid(weatherData) {
|
||||
weatherDataIsValid (weatherData) {
|
||||
return (
|
||||
weatherData &&
|
||||
weatherData.timeout &&
|
||||
0 < moment(weatherData.timeout).diff(moment()) &&
|
||||
(!weatherData.geometry || !weatherData.geometry.coordinates || !weatherData.geometry.coordinates.length < 2 || (weatherData.geometry.coordinates[0] === this.config.lat && weatherData.geometry.coordinates[1] === this.config.lon))
|
||||
weatherData
|
||||
&& weatherData.timeout
|
||||
&& 0 < moment(weatherData.timeout).diff(moment())
|
||||
&& (!weatherData.geometry || !weatherData.geometry.coordinates || !weatherData.geometry.coordinates.length < 2 || (weatherData.geometry.coordinates[0] === this.config.lat && weatherData.geometry.coordinates[1] === this.config.lon))
|
||||
);
|
||||
},
|
||||
|
||||
getWeatherDataFromCache() {
|
||||
getWeatherDataFromCache () {
|
||||
const weatherData = localStorage.getItem("weatherData");
|
||||
if (weatherData) {
|
||||
return JSON.parse(weatherData);
|
||||
@@ -148,7 +149,7 @@ WeatherProvider.register("yr", {
|
||||
}
|
||||
},
|
||||
|
||||
getWeatherDataFromYr(currentDataFetchedAt) {
|
||||
getWeatherDataFromYr (currentDataFetchedAt) {
|
||||
const requestHeaders = [{ name: "Accept", value: "application/json" }];
|
||||
if (currentDataFetchedAt) {
|
||||
requestHeaders.push({ name: "If-Modified-Since", value: currentDataFetchedAt });
|
||||
@@ -170,7 +171,7 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
getForecastUrl() {
|
||||
getConfigOptions () {
|
||||
if (!this.config.lat) {
|
||||
Log.error("Latitude not provided.");
|
||||
throw new Error("Latitude not provided.");
|
||||
@@ -183,6 +184,11 @@ WeatherProvider.register("yr", {
|
||||
let lat = this.config.lat.toString();
|
||||
let lon = this.config.lon.toString();
|
||||
const altitude = this.config.altitude ?? 0;
|
||||
return { lat, lon, altitude };
|
||||
},
|
||||
|
||||
getForecastUrl () {
|
||||
let { lat, lon, altitude } = this.getConfigOptions();
|
||||
|
||||
if (lat.includes(".") && lat.split(".")[1].length > 4) {
|
||||
Log.warn("Latitude is too specific for weather data. Do not use more than four decimals. Trimming to maximum length.");
|
||||
@@ -195,19 +201,14 @@ WeatherProvider.register("yr", {
|
||||
lon = `${lonParts[0]}.${lonParts[1].substring(0, 4)}`;
|
||||
}
|
||||
|
||||
return `${this.config.apiBase}/locationforecast/2.0/complete?&altitude=${altitude}&lat=${lat}&lon=${lon}`;
|
||||
return `${this.config.apiBase}/locationforecast/${this.config.forecastApiVersion}/complete?&altitude=${altitude}&lat=${lat}&lon=${lon}`;
|
||||
},
|
||||
|
||||
cacheWeatherData(weatherData) {
|
||||
cacheWeatherData (weatherData) {
|
||||
localStorage.setItem("weatherData", JSON.stringify(weatherData));
|
||||
},
|
||||
|
||||
getAuthenticationString() {
|
||||
if (!this.config.authenticationEmail) throw new Error("Authentication email not provided.");
|
||||
return `${this.config.applicaitionName} ${this.config.authenticationEmail}`;
|
||||
},
|
||||
|
||||
getStellarData() {
|
||||
getStellarData () {
|
||||
// If a user has several Yr-modules, for instance one current and one forecast, the API calls must be synchronized across classes.
|
||||
// This is to avoid multiple similar calls to the API.
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -233,7 +234,7 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
getStellarDataFromYrOrCache(resolve, reject) {
|
||||
getStellarDataFromYrOrCache (resolve, reject) {
|
||||
localStorage.setItem("yrIsFetchingStellarData", "true");
|
||||
|
||||
let stellarData = this.getStellarDataFromCache();
|
||||
@@ -291,7 +292,7 @@ WeatherProvider.register("yr", {
|
||||
}
|
||||
},
|
||||
|
||||
getStellarDataFromCache() {
|
||||
getStellarDataFromCache () {
|
||||
const stellarData = localStorage.getItem("stellarData");
|
||||
if (stellarData) {
|
||||
return JSON.parse(stellarData);
|
||||
@@ -300,9 +301,9 @@ WeatherProvider.register("yr", {
|
||||
}
|
||||
},
|
||||
|
||||
getStellarDataFromYr(date, days = 1) {
|
||||
getStellarDataFromYr (date, days = 1) {
|
||||
const requestHeaders = [{ name: "Accept", value: "application/json" }];
|
||||
return this.fetchData(this.getStellarDatatUrl(date, days), "json", requestHeaders)
|
||||
return this.fetchData(this.getStellarDataUrl(date, days), "json", requestHeaders)
|
||||
.then((data) => {
|
||||
Log.debug("Got stellar data from yr.");
|
||||
return data;
|
||||
@@ -313,19 +314,8 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
getStellarDatatUrl(date, days) {
|
||||
if (!this.config.lat) {
|
||||
Log.error("Latitude not provided.");
|
||||
throw new Error("Latitude not provided.");
|
||||
}
|
||||
if (!this.config.lon) {
|
||||
Log.error("Longitude not provided.");
|
||||
throw new Error("Longitude not provided.");
|
||||
}
|
||||
|
||||
let lat = this.config.lat.toString();
|
||||
let lon = this.config.lon.toString();
|
||||
const altitude = this.config.altitude ?? 0;
|
||||
getStellarDataUrl (date, days) {
|
||||
let { lat, lon, altitude } = this.getConfigOptions();
|
||||
|
||||
if (lat.includes(".") && lat.split(".")[1].length > 4) {
|
||||
Log.warn("Latitude is too specific for stellar data. Do not use more than four decimals. Trimming to maximum length.");
|
||||
@@ -352,14 +342,14 @@ WeatherProvider.register("yr", {
|
||||
if (hours.length < 2) {
|
||||
hours = `0${hours}`;
|
||||
}
|
||||
return `${this.config.apiBase}/sunrise/2.3/sun?lat=${lat}&lon=${lon}&date=${date}&offset=${utcOffsetPrefix}${hours}%3A${minutes}`;
|
||||
return `${this.config.apiBase}/sunrise/${this.config.sunriseApiVersion}/sun?lat=${lat}&lon=${lon}&date=${date}&offset=${utcOffsetPrefix}${hours}%3A${minutes}`;
|
||||
},
|
||||
|
||||
cacheStellarData(data) {
|
||||
cacheStellarData (data) {
|
||||
localStorage.setItem("stellarData", JSON.stringify(data));
|
||||
},
|
||||
|
||||
getWeatherDataFrom(forecast, stellarData, units) {
|
||||
getWeatherDataFrom (forecast, stellarData, units) {
|
||||
const weather = new WeatherObject();
|
||||
|
||||
weather.date = moment(forecast.time);
|
||||
@@ -380,7 +370,7 @@ WeatherProvider.register("yr", {
|
||||
return weather;
|
||||
},
|
||||
|
||||
convertWeatherType(weatherType, weatherTime) {
|
||||
convertWeatherType (weatherType, weatherTime) {
|
||||
const weatherHour = moment(weatherTime).format("HH");
|
||||
|
||||
const weatherTypes = {
|
||||
@@ -472,16 +462,7 @@ WeatherProvider.register("yr", {
|
||||
return weatherTypes.hasOwnProperty(weatherType) ? weatherTypes[weatherType] : null;
|
||||
},
|
||||
|
||||
getStellarTimesFrom(stellarData, date) {
|
||||
for (const time of stellarData.location.time) {
|
||||
if (time.date === date) {
|
||||
return time;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
|
||||
getForecastForXHoursFrom(weather) {
|
||||
getForecastForXHoursFrom (weather) {
|
||||
if (this.config.currentForecastHours === 1) {
|
||||
if (weather.next_1_hours) {
|
||||
return weather.next_1_hours;
|
||||
@@ -509,7 +490,7 @@ WeatherProvider.register("yr", {
|
||||
}
|
||||
},
|
||||
|
||||
fetchWeatherHourly() {
|
||||
fetchWeatherHourly () {
|
||||
this.getWeatherForecast("hourly")
|
||||
.then((forecast) => {
|
||||
this.setWeatherHourly(forecast);
|
||||
@@ -521,9 +502,8 @@ WeatherProvider.register("yr", {
|
||||
});
|
||||
},
|
||||
|
||||
async getWeatherForecast(type) {
|
||||
const getRequests = [this.getWeatherData(), this.getStellarData()];
|
||||
const [weatherData, stellarData] = await Promise.all(getRequests);
|
||||
async getWeatherForecast (type) {
|
||||
const [weatherData, stellarData] = await Promise.all([this.getWeatherData(), this.getStellarData()]);
|
||||
if (!weatherData.properties.timeseries || !weatherData.properties.timeseries[0]) {
|
||||
Log.error("No weather data available.");
|
||||
return;
|
||||
@@ -548,7 +528,7 @@ WeatherProvider.register("yr", {
|
||||
return series;
|
||||
},
|
||||
|
||||
getHourlyForecastFrom(weatherData) {
|
||||
getHourlyForecastFrom (weatherData) {
|
||||
const series = [];
|
||||
|
||||
for (const forecast of weatherData.properties.timeseries) {
|
||||
@@ -563,7 +543,7 @@ WeatherProvider.register("yr", {
|
||||
return series;
|
||||
},
|
||||
|
||||
getDailyForecastFrom(weatherData) {
|
||||
getDailyForecastFrom (weatherData) {
|
||||
const series = [];
|
||||
|
||||
const days = weatherData.properties.timeseries.reduce(function (days, forecast) {
|
||||
@@ -573,7 +553,7 @@ WeatherProvider.register("yr", {
|
||||
return days;
|
||||
}, Object.create(null));
|
||||
|
||||
Object.keys(days).forEach(function (time, index) {
|
||||
Object.keys(days).forEach(function (time) {
|
||||
let minTemperature = undefined;
|
||||
let maxTemperature = undefined;
|
||||
|
||||
@@ -613,7 +593,7 @@ WeatherProvider.register("yr", {
|
||||
return series;
|
||||
},
|
||||
|
||||
fetchWeatherForecast() {
|
||||
fetchWeatherForecast () {
|
||||
this.getWeatherForecast("daily")
|
||||
.then((forecast) => {
|
||||
this.setWeatherForecast(forecast);
|
||||
|
@@ -56,17 +56,17 @@ Module.register("weather", {
|
||||
firstEvent: null,
|
||||
|
||||
// Define required scripts.
|
||||
getStyles: function () {
|
||||
getStyles () {
|
||||
return ["font-awesome.css", "weather-icons.css", "weather.css"];
|
||||
},
|
||||
|
||||
// Return the scripts that are necessary for the weather module.
|
||||
getScripts: function () {
|
||||
getScripts () {
|
||||
return ["moment.js", "weatherutils.js", "weatherobject.js", this.file("providers/overrideWrapper.js"), "weatherprovider.js", "suncalc.js", this.file(`providers/${this.config.weatherProvider.toLowerCase()}.js`)];
|
||||
},
|
||||
|
||||
// Override getHeader method.
|
||||
getHeader: function () {
|
||||
getHeader () {
|
||||
if (this.config.appendLocationNameToHeader && this.weatherProvider) {
|
||||
if (this.data.header) return `${this.data.header} ${this.weatherProvider.fetchedLocation()}`;
|
||||
else return this.weatherProvider.fetchedLocation();
|
||||
@@ -76,7 +76,7 @@ Module.register("weather", {
|
||||
},
|
||||
|
||||
// Start the weather module.
|
||||
start: function () {
|
||||
start () {
|
||||
moment.locale(this.config.lang);
|
||||
|
||||
if (this.config.useKmh) {
|
||||
@@ -101,7 +101,7 @@ Module.register("weather", {
|
||||
},
|
||||
|
||||
// Override notification handler.
|
||||
notificationReceived: function (notification, payload, sender) {
|
||||
notificationReceived (notification, payload, sender) {
|
||||
if (notification === "CALENDAR_EVENTS") {
|
||||
const senderClasses = sender.data.classes.toLowerCase().split(" ");
|
||||
if (senderClasses.indexOf(this.config.calendarClass.toLowerCase()) !== -1) {
|
||||
@@ -126,7 +126,7 @@ Module.register("weather", {
|
||||
},
|
||||
|
||||
// Select the template depending on the display type.
|
||||
getTemplate: function () {
|
||||
getTemplate () {
|
||||
switch (this.config.type.toLowerCase()) {
|
||||
case "current":
|
||||
return "current.njk";
|
||||
@@ -142,7 +142,7 @@ Module.register("weather", {
|
||||
},
|
||||
|
||||
// Add all the data to the template.
|
||||
getTemplateData: function () {
|
||||
getTemplateData () {
|
||||
const currentData = this.weatherProvider.currentWeather();
|
||||
const forecastData = this.weatherProvider.weatherForecast();
|
||||
|
||||
@@ -162,7 +162,7 @@ Module.register("weather", {
|
||||
},
|
||||
|
||||
// What to do when the weather provider has new information available?
|
||||
updateAvailable: function () {
|
||||
updateAvailable () {
|
||||
Log.log("New weather information available.");
|
||||
this.updateDom(0);
|
||||
this.scheduleUpdate();
|
||||
@@ -181,7 +181,7 @@ Module.register("weather", {
|
||||
this.sendNotification("WEATHER_UPDATED", notificationPayload);
|
||||
},
|
||||
|
||||
scheduleUpdate: function (delay = null) {
|
||||
scheduleUpdate (delay = null) {
|
||||
let nextLoad = this.config.updateInterval;
|
||||
if (delay !== null && delay >= 0) {
|
||||
nextLoad = delay;
|
||||
@@ -205,13 +205,13 @@ Module.register("weather", {
|
||||
}, nextLoad);
|
||||
},
|
||||
|
||||
roundValue: function (temperature) {
|
||||
roundValue (temperature) {
|
||||
const decimals = this.config.roundTemp ? 0 : 1;
|
||||
const roundValue = parseFloat(temperature).toFixed(decimals);
|
||||
return roundValue === "-0" ? 0 : roundValue;
|
||||
},
|
||||
|
||||
addFilters() {
|
||||
addFilters () {
|
||||
this.nunjucksEnvironment().addFilter(
|
||||
"formatTime",
|
||||
function (date) {
|
||||
|
@@ -16,10 +16,11 @@
|
||||
* @external Moment
|
||||
*/
|
||||
class WeatherObject {
|
||||
|
||||
/**
|
||||
* Constructor for a WeatherObject
|
||||
*/
|
||||
constructor() {
|
||||
constructor () {
|
||||
this.date = null;
|
||||
this.windSpeed = null;
|
||||
this.windFromDirection = null;
|
||||
@@ -36,7 +37,7 @@ class WeatherObject {
|
||||
this.feelsLikeTemp = null;
|
||||
}
|
||||
|
||||
cardinalWindDirection() {
|
||||
cardinalWindDirection () {
|
||||
if (this.windFromDirection > 11.25 && this.windFromDirection <= 33.75) {
|
||||
return "NNE";
|
||||
} else if (this.windFromDirection > 33.75 && this.windFromDirection <= 56.25) {
|
||||
@@ -79,11 +80,11 @@ class WeatherObject {
|
||||
* action for. Useful only in tests, defaults to the current time.
|
||||
* @returns {string} "sunset" or "sunrise"
|
||||
*/
|
||||
nextSunAction(date = moment()) {
|
||||
nextSunAction (date = moment()) {
|
||||
return date.isBetween(this.sunrise, this.sunset) ? "sunset" : "sunrise";
|
||||
}
|
||||
|
||||
feelsLike() {
|
||||
feelsLike () {
|
||||
if (this.feelsLikeTemp) {
|
||||
return this.feelsLikeTemp;
|
||||
}
|
||||
@@ -94,7 +95,7 @@ class WeatherObject {
|
||||
* Checks if the weatherObject is at dayTime.
|
||||
* @returns {boolean} true if it is at dayTime
|
||||
*/
|
||||
isDayTime() {
|
||||
isDayTime () {
|
||||
const now = !this.date ? moment() : this.date;
|
||||
return now.isBetween(this.sunrise, this.sunset, undefined, "[]");
|
||||
}
|
||||
@@ -106,7 +107,7 @@ class WeatherObject {
|
||||
* @param {number} lat latitude
|
||||
* @param {number} lon longitude
|
||||
*/
|
||||
updateSunTime(lat, lon) {
|
||||
updateSunTime (lat, lon) {
|
||||
const now = !this.date ? new Date() : this.date.toDate();
|
||||
const times = SunCalc.getTimes(now, lat, lon);
|
||||
this.sunrise = moment(times.sunrise);
|
||||
@@ -120,7 +121,7 @@ class WeatherObject {
|
||||
* Especially 'moment' object is not immutable, so original 'date', 'sunrise', 'sunset' could be corrupted or changed by other modules.
|
||||
* @returns {object} plained object clone of original weatherObject
|
||||
*/
|
||||
simpleClone() {
|
||||
simpleClone () {
|
||||
const toFlat = ["date", "sunrise", "sunset"];
|
||||
let clone = { ...this };
|
||||
for (const prop of toFlat) {
|
||||
|
@@ -30,84 +30,84 @@ const WeatherProvider = Class.extend({
|
||||
// All the following methods can be overwritten, although most are good as they are.
|
||||
|
||||
// Called when a weather provider is initialized.
|
||||
init: function (config) {
|
||||
init (config) {
|
||||
this.config = config;
|
||||
Log.info(`Weather provider: ${this.providerName} initialized.`);
|
||||
},
|
||||
|
||||
// Called to set the config, this config is the same as the weather module's config.
|
||||
setConfig: function (config) {
|
||||
setConfig (config) {
|
||||
this.config = config;
|
||||
Log.info(`Weather provider: ${this.providerName} config set.`, this.config);
|
||||
},
|
||||
|
||||
// Called when the weather provider is about to start.
|
||||
start: function () {
|
||||
start () {
|
||||
Log.info(`Weather provider: ${this.providerName} started.`);
|
||||
},
|
||||
|
||||
// This method should start the API request to fetch the current weather.
|
||||
// This method should definitely be overwritten in the provider.
|
||||
fetchCurrentWeather: function () {
|
||||
fetchCurrentWeather () {
|
||||
Log.warn(`Weather provider: ${this.providerName} does not subclass the fetchCurrentWeather method.`);
|
||||
},
|
||||
|
||||
// This method should start the API request to fetch the weather forecast.
|
||||
// This method should definitely be overwritten in the provider.
|
||||
fetchWeatherForecast: function () {
|
||||
fetchWeatherForecast () {
|
||||
Log.warn(`Weather provider: ${this.providerName} does not subclass the fetchWeatherForecast method.`);
|
||||
},
|
||||
|
||||
// This method should start the API request to fetch the weather hourly.
|
||||
// This method should definitely be overwritten in the provider.
|
||||
fetchWeatherHourly: function () {
|
||||
fetchWeatherHourly () {
|
||||
Log.warn(`Weather provider: ${this.providerName} does not subclass the fetchWeatherHourly method.`);
|
||||
},
|
||||
|
||||
// This returns a WeatherDay object for the current weather.
|
||||
currentWeather: function () {
|
||||
currentWeather () {
|
||||
return this.currentWeatherObject;
|
||||
},
|
||||
|
||||
// This returns an array of WeatherDay objects for the weather forecast.
|
||||
weatherForecast: function () {
|
||||
weatherForecast () {
|
||||
return this.weatherForecastArray;
|
||||
},
|
||||
|
||||
// This returns an object containing WeatherDay object(s) depending on the type of call.
|
||||
weatherHourly: function () {
|
||||
weatherHourly () {
|
||||
return this.weatherHourlyArray;
|
||||
},
|
||||
|
||||
// This returns the name of the fetched location or an empty string.
|
||||
fetchedLocation: function () {
|
||||
fetchedLocation () {
|
||||
return this.fetchedLocationName || "";
|
||||
},
|
||||
|
||||
// Set the currentWeather and notify the delegate that new information is available.
|
||||
setCurrentWeather: function (currentWeatherObject) {
|
||||
setCurrentWeather (currentWeatherObject) {
|
||||
// We should check here if we are passing a WeatherDay
|
||||
this.currentWeatherObject = currentWeatherObject;
|
||||
},
|
||||
|
||||
// Set the weatherForecastArray and notify the delegate that new information is available.
|
||||
setWeatherForecast: function (weatherForecastArray) {
|
||||
setWeatherForecast (weatherForecastArray) {
|
||||
// We should check here if we are passing a WeatherDay
|
||||
this.weatherForecastArray = weatherForecastArray;
|
||||
},
|
||||
|
||||
// Set the weatherHourlyArray and notify the delegate that new information is available.
|
||||
setWeatherHourly: function (weatherHourlyArray) {
|
||||
setWeatherHourly (weatherHourlyArray) {
|
||||
this.weatherHourlyArray = weatherHourlyArray;
|
||||
},
|
||||
|
||||
// Set the fetched location name.
|
||||
setFetchedLocation: function (name) {
|
||||
setFetchedLocation (name) {
|
||||
this.fetchedLocationName = name;
|
||||
},
|
||||
|
||||
// Notify the delegate that new weather is available.
|
||||
updateAvailable: function () {
|
||||
updateAvailable () {
|
||||
this.delegate.updateAvailable(this);
|
||||
},
|
||||
|
||||
@@ -119,7 +119,7 @@ const WeatherProvider = Class.extend({
|
||||
* @param {Array.<string>} expectedResponseHeaders the expected HTTP headers to recieve
|
||||
* @returns {Promise} resolved when the fetch is done
|
||||
*/
|
||||
fetchData: async function (url, type = "json", requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
async fetchData (url, type = "json", requestHeaders = undefined, expectedResponseHeaders = undefined) {
|
||||
const mockData = this.config.mockData;
|
||||
if (mockData) {
|
||||
const data = mockData.substring(1, mockData.length - 1);
|
||||
|
@@ -5,12 +5,13 @@
|
||||
* MIT Licensed.
|
||||
*/
|
||||
const WeatherUtils = {
|
||||
|
||||
/**
|
||||
* Convert wind (from m/s) to beaufort scale
|
||||
* @param {number} speedInMS the windspeed you want to convert
|
||||
* @returns {number} the speed in beaufort
|
||||
*/
|
||||
beaufortWindSpeed(speedInMS) {
|
||||
beaufortWindSpeed (speedInMS) {
|
||||
const windInKmh = this.convertWind(speedInMS, "kmh");
|
||||
const speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
|
||||
for (const [index, speed] of speeds.entries()) {
|
||||
@@ -29,7 +30,7 @@ const WeatherUtils = {
|
||||
* @param {string} outputUnit - The unit system (imperial/metric) the return value should have.
|
||||
* @returns {string} - A string with tha value and a unit postfix.
|
||||
*/
|
||||
convertPrecipitationUnit(value, valueUnit, outputUnit) {
|
||||
convertPrecipitationUnit (value, valueUnit, outputUnit) {
|
||||
if (valueUnit === "%") return `${value.toFixed(0)} ${valueUnit}`;
|
||||
|
||||
let convertedValue = value;
|
||||
@@ -52,7 +53,7 @@ const WeatherUtils = {
|
||||
* @param {string} unit can be 'imperial' or 'metric'
|
||||
* @returns {number} the converted temperature
|
||||
*/
|
||||
convertTemp(tempInC, unit) {
|
||||
convertTemp (tempInC, unit) {
|
||||
return unit === "imperial" ? tempInC * 1.8 + 32 : tempInC;
|
||||
},
|
||||
|
||||
@@ -63,7 +64,7 @@ const WeatherUtils = {
|
||||
* or 'metric' (mps)
|
||||
* @returns {number} the converted windspeed
|
||||
*/
|
||||
convertWind(windInMS, unit) {
|
||||
convertWind (windInMS, unit) {
|
||||
switch (unit) {
|
||||
case "beaufort":
|
||||
return this.beaufortWindSpeed(windInMS);
|
||||
@@ -82,7 +83,7 @@ const WeatherUtils = {
|
||||
/*
|
||||
* Convert the wind direction cardinal to value
|
||||
*/
|
||||
convertWindDirection(windDirection) {
|
||||
convertWindDirection (windDirection) {
|
||||
const windCardinals = {
|
||||
N: 0,
|
||||
NNE: 22,
|
||||
@@ -105,15 +106,15 @@ const WeatherUtils = {
|
||||
return windCardinals.hasOwnProperty(windDirection) ? windCardinals[windDirection] : null;
|
||||
},
|
||||
|
||||
convertWindToMetric(mph) {
|
||||
convertWindToMetric (mph) {
|
||||
return mph / 2.2369362920544;
|
||||
},
|
||||
|
||||
convertWindToMs(kmh) {
|
||||
convertWindToMs (kmh) {
|
||||
return kmh * 0.27777777777778;
|
||||
},
|
||||
|
||||
calculateFeelsLike(temperature, windSpeed, humidity) {
|
||||
calculateFeelsLike (temperature, windSpeed, humidity) {
|
||||
const windInMph = this.convertWind(windSpeed, "imperial");
|
||||
const tempInF = this.convertTemp(temperature, "imperial");
|
||||
let feelsLike = tempInF;
|
||||
@@ -121,16 +122,16 @@ const WeatherUtils = {
|
||||
if (windInMph > 3 && tempInF < 50) {
|
||||
feelsLike = Math.round(35.74 + 0.6215 * tempInF - 35.75 * Math.pow(windInMph, 0.16) + 0.4275 * tempInF * Math.pow(windInMph, 0.16));
|
||||
} else if (tempInF > 80 && humidity > 40) {
|
||||
feelsLike =
|
||||
-42.379 +
|
||||
2.04901523 * tempInF +
|
||||
10.14333127 * humidity -
|
||||
0.22475541 * tempInF * humidity -
|
||||
6.83783 * Math.pow(10, -3) * tempInF * tempInF -
|
||||
5.481717 * Math.pow(10, -2) * humidity * humidity +
|
||||
1.22874 * Math.pow(10, -3) * tempInF * tempInF * humidity +
|
||||
8.5282 * Math.pow(10, -4) * tempInF * humidity * humidity -
|
||||
1.99 * Math.pow(10, -6) * tempInF * tempInF * humidity * humidity;
|
||||
feelsLike
|
||||
= -42.379
|
||||
+ 2.04901523 * tempInF
|
||||
+ 10.14333127 * humidity
|
||||
- 0.22475541 * tempInF * humidity
|
||||
- 6.83783 * Math.pow(10, -3) * tempInF * tempInF
|
||||
- 5.481717 * Math.pow(10, -2) * humidity * humidity
|
||||
+ 1.22874 * Math.pow(10, -3) * tempInF * tempInF * humidity
|
||||
+ 8.5282 * Math.pow(10, -4) * tempInF * humidity * humidity
|
||||
- 1.99 * Math.pow(10, -6) * tempInF * tempInF * humidity * humidity;
|
||||
}
|
||||
|
||||
return ((feelsLike - 32) * 5) / 9;
|
||||
|
Reference in New Issue
Block a user