Files
Karsten Hassel d05ea751d9 Release 2.35.0 (#4072)
## Release Notes
Thanks to: @angeldeejay, @in-voker, @JHWelch, @khassel,
@KristjanESPERANTO, @rejas, @sdetweil
> ⚠️ This release needs nodejs version >=22.21.1 <23 || >=24 (no change
to previous release)

[Compare to previous Release
v2.34.0](https://github.com/MagicMirrorOrg/MagicMirror/compare/v2.34.0...v2.25.0)

> ⚠️ We introduced some internal changes with this release, please read
[this forum
post](https://forum.magicmirror.builders/topic/20138/upcoming-release-april-1-2026-breaking-changes-some-operational-changes)
before upgrading!

### [core]
- Prepare Release 2.35.0 (#4071)
- docs: add security policy and vulnerability reporting guidelines
(#4069)
- refactor: simplify internal `require()` calls (#4056)
- allow environment variables in cors urls (#4033)
- fix cors proxy getting binary data (e.g. png, webp) (#4030)
- fix: correct secret redaction and optimize loadConfig (#4031)
- change loading config.js, allow variables in config.js and try to
protect sensitive data (#4029)
- remove kioskmode (#4027)
- Add dark theme logo (#4026)
- move custom.css from css to config (#4020)
- move default modules from /modules/default to /defaultmodules (#4019)
- update node versions in workflows (#4018)
- [core] refactor: extract and centralize HTTP fetcher (#4016)
- fix systeminformation not displaying electron version (#4012)
- Update node-ical and support it's rrule-temporal changes (#4010)
- Change default start scripts from X11 to Wayland (#4011)
- refactor: unify favicon for index.html and Electron (#4006)
- [core] run systeminformation in subprocess so the info is always
displayed (#4002)
- set next release dev number (#4000)

### [dependencies]
- update dependencies (#4068)
- update dependencies incl. electron to v41 (#4058)
- chore: upgrade ESLint to v10 and fix newly surfaced issues (#4057)
- chore: update ESLint and plugins, simplify config, apply new rules
(#4052)
- chore: update dependencies + add exports, files, and sideEffects
fields to package.json (#4040)
- [core] refactor: enable ESLint rule require-await and handle detected
issues (#4038)
- Update node-ical and other deps (#4025)
- chore: update dependencies (#4021)
- chore(eslint): migrate from eslint-plugin-vitest to
@vitest/eslint-plugin and run rules only on test files (#4014)
- Update deps as requested by dependabot (#4008)
- update Collaboration.md and dependencies (#4001)

### [logging]
- refactor: further logger clean-up (#4050)
- Fix Node.js v25 logging prefix and modernize logger (#4049)

### [modules/calendar]
- fix(calendar): make showEnd behavior more consistent across time
formats (#4059)
- test(calendar): fix hardcoded date in event shape test (#4055)
- [calendar] refactor: delegate event expansion to node-ical's
expandRecurringEvent (#4047)
- calendar.js: remove useless hasCalendarURL function (#4028)
- fix(calendar): update to node-ical 0.23.1 and fix full-day recurrence
lookup (#4013)
- fix(calendar): correct day-of-week for full-day recurring events
across all timezones (#4004)

### [modules/newsfeed]
- fix(newsfeed): fix full article view and add framing check (#4039)
- [newsfeed] refactor: migrate to centralized HTTPFetcher (#4023)

### [modules/weather]
- fix(weather): fix openmeteo forecast stuck in the past (#4064)
- fix(weather): fix weathergov forecast day labels off by one (#4065)
- weather: fixes for templates (#4054)
- weather: add possibility to override njk's and css (#4051)
- Use getDateString in openmeteo (#4046)
- [weather] refactor: migrate to server-side providers with centralized
HTTPFetcher (#4032)
- [weather] feat: add Weather API Provider  (#4036)

### [testing]
- chore: remove obsolete Jest config and unit test global setup (#4044)
- replace template_spec test with config_variables test (#4034)
- refactor(clientonly): modernize code structure and add comprehensive
tests (#4022)
- Switch to undici Agent for HTTPS requests (#4015)
- chore: migrate CI workflows to ubuntu-slim for faster startup times
(#4007)

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Kristjan ESPERANTO <35647502+KristjanESPERANTO@users.noreply.github.com>
Co-authored-by: Bugsounet - Cédric <github@bugsounet.fr>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: sam detweiler <sdetweil@gmail.com>
Co-authored-by: Veeck <github@veeck.de>
Co-authored-by: veeck <gitkraken@veeck.de>
Co-authored-by: Magnus <34011212+MagMar94@users.noreply.github.com>
Co-authored-by: Ikko Eltociear Ashimine <eltociear@gmail.com>
Co-authored-by: DevIncomin <56730075+Developer-Incoming@users.noreply.github.com>
Co-authored-by: Nathan <n8nyoung@gmail.com>
Co-authored-by: mixasgr <mixasgr@users.noreply.github.com>
Co-authored-by: Savvas Adamtziloglou <savvas-gr@greeklug.gr>
Co-authored-by: Konstantinos <geraki@gmail.com>
Co-authored-by: OWL4C <124401812+OWL4C@users.noreply.github.com>
Co-authored-by: BugHaver <43462320+bughaver@users.noreply.github.com>
Co-authored-by: BugHaver <43462320+lsaadeh@users.noreply.github.com>
Co-authored-by: Koen Konst <koenspero@gmail.com>
Co-authored-by: Koen Konst <c.h.konst@avisi.nl>
Co-authored-by: dathbe <github@beffa.us>
Co-authored-by: Marcel <m-idler@users.noreply.github.com>
Co-authored-by: Kevin G. <crazylegstoo@gmail.com>
Co-authored-by: Jboucly <33218155+jboucly@users.noreply.github.com>
Co-authored-by: Jboucly <contact@jboucly.fr>
Co-authored-by: Jarno <54169345+jarnoml@users.noreply.github.com>
Co-authored-by: Jordan Welch <JordanHWelch@gmail.com>
Co-authored-by: Blackspirits <blackspirits@gmail.com>
Co-authored-by: Samed Ozdemir <samed@xsor.io>
Co-authored-by: in-voker <58696565+in-voker@users.noreply.github.com>
Co-authored-by: Andrés Vanegas Jiménez <142350+angeldeejay@users.noreply.github.com>
2026-04-01 12:35:16 +02:00

451 lines
13 KiB
JavaScript

const Log = require("logger");
const { convertKmhToMs } = require("../provider-utils");
const HTTPFetcher = require("#http_fetcher");
/**
* Server-side weather provider for Environment Canada MSC Datamart
* Canada only, no API key required (anonymous access)
*
* Documentation:
* https://dd.weather.gc.ca/citypage_weather/schema/
* https://eccc-msc.github.io/open-data/msc-datamart/readme_en/
*
* Requires siteCode and provCode config parameters
* See https://dd.weather.gc.ca/citypage_weather/docs/site_list_en.csv
*/
class EnvCanadaProvider {
constructor (config) {
this.config = {
siteCode: "s0000000",
provCode: "ON",
type: "current",
updateInterval: 10 * 60 * 1000,
...config
};
this.fetcher = null;
this.onDataCallback = null;
this.onErrorCallback = null;
this.lastCityPageURL = null;
this.cacheCurrentTemp = null;
this.currentHour = null; // Track current hour for URL updates
}
initialize () {
this.#validateConfig();
this.#initializeFetcher();
}
setCallbacks (onData, onError) {
this.onDataCallback = onData;
this.onErrorCallback = onError;
}
start () {
if (this.fetcher) {
this.fetcher.startPeriodicFetch();
}
}
stop () {
if (this.fetcher) {
this.fetcher.clearTimer();
}
}
#validateConfig () {
if (!this.config.siteCode || !this.config.provCode) {
throw new Error("siteCode and provCode are required");
}
}
#initializeFetcher () {
this.currentHour = new Date().toISOString().substring(11, 13);
const indexURL = this.#getIndexUrl();
this.fetcher = new HTTPFetcher(indexURL, {
reloadInterval: this.config.updateInterval,
logContext: "weatherprovider.envcanada"
});
this.fetcher.on("response", async (response) => {
try {
// Check if hour changed - restart fetcher with new URL
const newHour = new Date().toISOString().substring(11, 13);
if (newHour !== this.currentHour) {
Log.info("[envcanada] Hour changed, reinitializing fetcher");
this.stop();
this.#initializeFetcher();
this.start();
return;
}
const html = await response.text();
const cityPageURL = this.#extractCityPageURL(html);
if (!cityPageURL) {
// This can happen during hour transitions when old responses arrive
Log.debug("[envcanada] Could not find city page URL (may be stale response from previous hour)");
return;
}
if (cityPageURL === this.lastCityPageURL) {
Log.debug("[envcanada] City page unchanged");
return;
}
this.lastCityPageURL = cityPageURL;
await this.#fetchCityPage(cityPageURL);
} catch (error) {
Log.error("[envcanada] Error:", error);
if (this.onErrorCallback) {
this.onErrorCallback({
message: error.message,
translationKey: "MODULE_ERROR_UNSPECIFIED"
});
}
}
});
this.fetcher.on("error", (errorInfo) => {
if (this.onErrorCallback) {
this.onErrorCallback(errorInfo);
}
});
}
async #fetchCityPage (url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const xml = await response.text();
const weatherData = this.#parseWeatherData(xml);
if (this.onDataCallback) {
this.onDataCallback(weatherData);
}
} catch (error) {
Log.error("[envcanada] Fetch city page error:", error);
if (this.onErrorCallback) {
this.onErrorCallback({
message: "Failed to fetch city data",
translationKey: "MODULE_ERROR_UNSPECIFIED"
});
}
}
}
#parseWeatherData (xml) {
switch (this.config.type) {
case "current":
return this.#generateCurrentWeather(xml);
case "forecast":
case "daily":
return this.#generateForecast(xml);
case "hourly":
return this.#generateHourly(xml);
default:
Log.error(`[envcanada] Unknown weather type: ${this.config.type}`);
return null;
}
}
#generateCurrentWeather (xml) {
const current = { date: new Date() };
// Try to get temperature from currentConditions first
const currentTempStr = this.#extract(xml, /<currentConditions>.*?<temperature[^>]*>(.*?)<\/temperature>/s);
if (currentTempStr && currentTempStr !== "") {
current.temperature = parseFloat(currentTempStr);
this.cacheCurrentTemp = current.temperature;
} else {
// Fallback: extract from first forecast period if currentConditions is empty
const firstForecast = xml.match(/<forecast>(.*?)<\/forecast>/s);
if (firstForecast) {
const forecastXml = firstForecast[1];
const temp = this.#extract(forecastXml, /<temperature[^>]*>(.*?)<\/temperature>/);
if (temp && temp !== "") {
current.temperature = parseFloat(temp);
this.cacheCurrentTemp = current.temperature;
} else if (this.cacheCurrentTemp !== null) {
current.temperature = this.cacheCurrentTemp;
} else {
current.temperature = null;
}
}
}
// Wind chill / humidex for feels like temperature
const windChill = this.#extract(xml, /<windChill[^>]*>(.*?)<\/windChill>/);
const humidex = this.#extract(xml, /<humidex[^>]*>(.*?)<\/humidex>/);
if (windChill) {
current.feelsLikeTemp = parseFloat(windChill);
} else if (humidex) {
current.feelsLikeTemp = parseFloat(humidex);
}
// Get wind and icon from currentConditions or first forecast
const firstForecast = xml.match(/<forecast>(.*?)<\/forecast>/s);
if (!firstForecast) {
Log.warn("[envcanada] No forecast data available");
return current;
}
const forecastXml = firstForecast[1];
// Wind speed - try currentConditions first, fallback to forecast
let windSpeed = this.#extract(xml, /<currentConditions>.*?<wind>.*?<speed[^>]*>(.*?)<\/speed>/s);
if (!windSpeed) {
windSpeed = this.#extract(forecastXml, /<speed[^>]*>(.*?)<\/speed>/);
}
if (windSpeed) {
current.windSpeed = (windSpeed === "calm") ? 0 : convertKmhToMs(parseFloat(windSpeed));
}
// Wind bearing - try currentConditions first, fallback to forecast
let windBearing = this.#extract(xml, /<currentConditions>.*?<wind>.*?<bearing[^>]*>(.*?)<\/bearing>/s);
if (!windBearing) {
windBearing = this.#extract(forecastXml, /<bearing[^>]*>(.*?)<\/bearing>/);
}
if (windBearing) current.windFromDirection = parseFloat(windBearing);
// Try icon from currentConditions first, fallback to forecast
let iconCode = this.#extract(xml, /<currentConditions>.*?<iconCode[^>]*>(.*?)<\/iconCode>/s);
if (!iconCode) {
iconCode = this.#extract(forecastXml, /<iconCode[^>]*>(.*?)<\/iconCode>/);
}
if (iconCode) current.weatherType = this.#convertWeatherType(iconCode);
// Humidity from currentConditions
const humidity = this.#extract(xml, /<currentConditions>.*?<relativeHumidity[^>]*>(.*?)<\/relativeHumidity>/s);
if (humidity) current.humidity = parseFloat(humidity);
// Precipitation probability from forecast
const pop = this.#extract(forecastXml, /<pop[^>]*>(.*?)<\/pop>/);
if (pop && pop !== "") {
current.precipitationProbability = parseFloat(pop);
}
// Sunrise/sunset (from riseSet, independent of currentConditions)
const sunriseTime = this.#extract(xml, /<dateTime[^>]*name="sunrise"[^>]*>.*?<timeStamp>(.*?)<\/timeStamp>/s);
const sunsetTime = this.#extract(xml, /<dateTime[^>]*name="sunset"[^>]*>.*?<timeStamp>(.*?)<\/timeStamp>/s);
if (sunriseTime) current.sunrise = this.#parseECTime(sunriseTime);
if (sunsetTime) current.sunset = this.#parseECTime(sunsetTime);
return current;
}
#generateForecast (xml) {
const days = [];
const forecasts = xml.match(/<forecast>(.*?)<\/forecast>/gs) || [];
if (forecasts.length === 0) return days;
// Get current temp
const currentTempStr = this.#extract(xml, /<currentConditions>.*?<temperature[^>]*>(.*?)<\/temperature>/s);
const currentTemp = currentTempStr ? parseFloat(currentTempStr) : null;
// Check if first forecast is Today or Tonight
const isToday = forecasts[0].includes("textForecastName=\"Today\"");
let nextDay = isToday ? 2 : 1;
const lastDay = isToday ? 12 : 11;
// Process first day
const firstDay = {
date: new Date(),
precipitationProbability: null
};
this.#extractForecastTemps(firstDay, forecasts, 0, isToday, currentTemp);
this.#extractForecastPrecip(firstDay, forecasts, 0);
const firstIcon = this.#extract(forecasts[0], /<iconCode[^>]*>(.*?)<\/iconCode>/);
if (firstIcon) firstDay.weatherType = this.#convertWeatherType(firstIcon);
days.push(firstDay);
// Process remaining days
let date = new Date();
for (let i = nextDay; i < lastDay && i < forecasts.length; i += 2) {
date = new Date(date);
date.setDate(date.getDate() + 1);
const day = {
date: new Date(date),
precipitationProbability: null
};
this.#extractForecastTemps(day, forecasts, i, true, currentTemp);
this.#extractForecastPrecip(day, forecasts, i);
const icon = this.#extract(forecasts[i], /<iconCode[^>]*>(.*?)<\/iconCode>/);
if (icon) day.weatherType = this.#convertWeatherType(icon);
days.push(day);
}
return days;
}
#extractForecastTemps (weather, forecasts, index, hasToday, currentTemp) {
let tempToday = null;
let tempTonight = null;
if (hasToday && forecasts[index]) {
const temp = this.#extract(forecasts[index], /<temperature[^>]*>(.*?)<\/temperature>/);
if (temp) tempToday = parseFloat(temp);
}
if (forecasts[index + 1]) {
const temp = this.#extract(forecasts[index + 1], /<temperature[^>]*>(.*?)<\/temperature>/);
if (temp) tempTonight = parseFloat(temp);
}
if (tempToday !== null && tempTonight !== null) {
weather.maxTemperature = Math.max(tempToday, tempTonight);
weather.minTemperature = Math.min(tempToday, tempTonight);
} else if (tempToday !== null) {
weather.maxTemperature = tempToday;
weather.minTemperature = currentTemp || tempToday;
} else if (tempTonight !== null) {
weather.maxTemperature = currentTemp || tempTonight;
weather.minTemperature = tempTonight;
}
}
#extractForecastPrecip (weather, forecasts, index) {
const precips = [];
if (forecasts[index]) {
const pop = this.#extract(forecasts[index], /<pop[^>]*>(.*?)<\/pop>/);
if (pop) precips.push(parseFloat(pop));
}
if (forecasts[index + 1]) {
const pop = this.#extract(forecasts[index + 1], /<pop[^>]*>(.*?)<\/pop>/);
if (pop) precips.push(parseFloat(pop));
}
if (precips.length > 0) {
weather.precipitationProbability = Math.max(...precips);
}
}
#generateHourly (xml) {
const hours = [];
const hourlyMatches = xml.matchAll(/<hourlyForecast[^>]*dateTimeUTC="([^"]*)"[^>]*>(.*?)<\/hourlyForecast>/gs);
for (const [, dateTimeUTC, hourXML] of hourlyMatches) {
const weather = {};
weather.date = this.#parseECTime(dateTimeUTC);
const temp = this.#extract(hourXML, /<temperature[^>]*>(.*?)<\/temperature>/);
if (temp) weather.temperature = parseFloat(temp);
const lop = this.#extract(hourXML, /<lop[^>]*>(.*?)<\/lop>/);
if (lop) weather.precipitationProbability = parseFloat(lop);
const icon = this.#extract(hourXML, /<iconCode[^>]*>(.*?)<\/iconCode>/);
if (icon) weather.weatherType = this.#convertWeatherType(icon);
hours.push(weather);
if (hours.length >= 24) break;
}
return hours;
}
#extract (text, pattern) {
const match = text.match(pattern);
return match ? match[1].trim() : null;
}
#getIndexUrl () {
const hour = new Date().toISOString().substring(11, 13);
return `https://dd.weather.gc.ca/today/citypage_weather/${this.config.provCode}/${hour}/`;
}
#extractCityPageURL (html) {
// New format: {timestamp}_MSC_CitypageWeather_{siteCode}_en.xml
const pattern = `[^"]*_MSC_CitypageWeather_${this.config.siteCode}_en\\.xml`;
const match = html.match(new RegExp(`href="(${pattern})"`));
if (match && match[1]) {
return this.#getIndexUrl() + match[1];
}
return null;
}
#parseECTime (timeStr) {
if (!timeStr || timeStr.length < 12) return new Date();
const y = parseInt(timeStr.substring(0, 4), 10);
const m = parseInt(timeStr.substring(4, 6), 10) - 1;
const d = parseInt(timeStr.substring(6, 8), 10);
const h = parseInt(timeStr.substring(8, 10), 10);
const min = parseInt(timeStr.substring(10, 12), 10);
const s = timeStr.length >= 14 ? parseInt(timeStr.substring(12, 14), 10) : 0;
// Create UTC date since input timestamps are in UTC
return new Date(Date.UTC(y, m, d, h, min, s));
}
#convertWeatherType (iconCode) {
const code = parseInt(iconCode, 10);
const map = {
0: "day-sunny",
1: "day-sunny",
2: "day-sunny-overcast",
3: "day-cloudy",
4: "day-cloudy",
5: "day-cloudy",
6: "day-sprinkle",
7: "day-showers",
8: "snow",
9: "day-thunderstorm",
10: "cloud",
11: "showers",
12: "rain",
13: "rain",
14: "sleet",
15: "sleet",
16: "snow",
17: "snow",
18: "snow",
19: "thunderstorm",
20: "cloudy",
21: "cloudy",
22: "day-cloudy",
23: "day-haze",
24: "fog",
25: "snow-wind",
26: "sleet",
27: "sleet",
28: "rain",
29: "na",
30: "night-clear",
31: "night-clear",
32: "night-partly-cloudy",
33: "night-alt-cloudy",
34: "night-alt-cloudy",
35: "night-partly-cloudy",
36: "night-alt-showers",
37: "night-rain-mix",
38: "night-alt-snow",
39: "night-thunderstorm",
40: "snow-wind",
41: "tornado",
42: "tornado",
43: "windy",
44: "smoke",
45: "sandstorm",
46: "thunderstorm",
47: "thunderstorm",
48: "tornado"
};
return map[code] || null;
}
}
module.exports = EnvCanadaProvider;