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:
Michael Teeuw
2024-01-01 15:38:08 +01:00
committed by GitHub
parent 343e7de7bd
commit 8c0e7db494
110 changed files with 3433 additions and 2915 deletions

View File

@@ -1,9 +1,9 @@
{
"extends": ["eslint:recommended", "plugin:prettier/recommended", "plugin:jsdoc/recommended"],
"plugins": ["prettier", "import", "jsdoc", "jest"],
"extends": ["eslint:recommended", "plugin:@stylistic/all-extends", "plugin:import/recommended", "plugin:jest/recommended", "plugin:jsdoc/recommended"],
"plugins": [],
"env": {
"browser": true,
"es2022": true,
"es2023": true,
"jest/globals": true,
"node": true
},
@@ -16,7 +16,7 @@
},
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2022,
"ecmaVersion": 2023,
"ecmaFeatures": {
"globalReturn": true
}
@@ -24,11 +24,60 @@
"rules": {
"eqeqeq": "error",
"import/order": "error",
"import/extensions": "error",
"import/newline-after-import": "error",
"jest/consistent-test-it": "warn",
"jest/expect-expect": "warn",
"jest/no-done-callback": "warn",
"jest/prefer-expect-resolves": "warn",
"jest/prefer-mock-promise-shorthand": "warn",
"jest/prefer-to-be": "warn",
"jest/prefer-to-have-length": "warn",
"no-param-reassign": "error",
"no-prototype-builtins": "off",
"no-throw-literal": "error",
"no-unused-vars": "off",
"no-useless-return": "error",
"prefer-template": "error"
"object-shorthand": ["error", "methods"],
"prefer-template": "error",
"@stylistic/array-element-newline": ["error", "consistent"],
"@stylistic/arrow-parens": ["error", "always"],
"@stylistic/brace-style": "off",
"@stylistic/comma-dangle": ["error", "never"],
"@stylistic/dot-location": ["error", "property"],
"@stylistic/function-call-argument-newline": ["error", "consistent"],
"@stylistic/function-paren-newline": ["error", "consistent"],
"@stylistic/implicit-arrow-linebreak": ["error", "beside"],
"@stylistic/max-statements-per-line": ["error", { "max": 2 }],
"@stylistic/multiline-ternary": ["error", "always-multiline"],
"@stylistic/newline-per-chained-call": ["error", { "ignoreChainWithDepth": 4 }],
"@stylistic/no-extra-parens": "off",
"@stylistic/no-tabs": "off",
"@stylistic/object-curly-spacing": ["error", "always"],
"@stylistic/object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }],
"@stylistic/operator-linebreak": ["error", "before"],
"@stylistic/padded-blocks": "off",
"@stylistic/quote-props": ["error", "as-needed"],
"@stylistic/quotes": ["error", "double"],
"@stylistic/indent": ["error", "tab"],
"@stylistic/semi": ["error", "always"],
"@stylistic/space-before-function-paren": ["error", "always"],
"@stylistic/spaced-comment": "off"
},
"overrides": [
{
"files": ["config/config.js*"],
"rules": {
"@stylistic/comma-dangle": "off",
"@stylistic/indent": "off",
"@stylistic/no-multi-spaces": "off"
}
},
{
"files": ["tests/configs/modules/weather/*.js"],
"rules": {
"@stylistic/quotes": "off"
}
}
]
}

View File

@@ -1,6 +1,6 @@
Hello and thank you for opening an issue.
**Please make sure that you have read the following lines before submitting your Issue:**
**⚠️ Please make sure that you have read the following lines before submitting your Issue:**
## I'm not sure if this is a bug

View File

@@ -18,12 +18,12 @@ jobs:
timeout-minutes: 30
strategy:
matrix:
node-version: [18.x, 20.x]
node-version: [18.x, 20.x, 21.x]
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Use Node.js ${{ matrix.node-version }}"
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: "npm"

View File

@@ -1,35 +0,0 @@
# This workflow runs the automated test and uploads the coverage results to codecov.io
# For more information see: https://github.com/codecov/codecov-action
name: "Run Codecov Tests"
on:
push:
branches: [master, develop]
pull_request:
branches: [master, develop]
permissions:
contents: read
jobs:
run-and-upload-coverage-report:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: "Checkout code"
uses: actions/checkout@v4
- name: "Install dependencies"
run: |
npm ci
- name: "Run coverage"
run: |
Xvfb :99 -screen 0 1024x768x16 &
export DISPLAY=:99
touch css/custom.css
npm run test:coverage
- name: "Upload coverage results to codecov"
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
fail_ci_if_error: true

View File

@@ -1,3 +1,6 @@
*.js
.prettierignore
/config
/coverage
package-lock.json
**.ics

View File

@@ -5,6 +5,57 @@ This project adheres to [Semantic Versioning](https://semver.org/).
❤️ **Donate:** Enjoying MagicMirror²? [Please consider a donation!](https://magicmirror.builders/donate) With your help we can continue to improve the MagicMirror².
## [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)
## [2.25.0] - 2023-10-01
Thanks to: @bugsounet, @dgoth, @dependabot, @kenzal, @Knapoc, @KristjanESPERANTO, @martingron, @NolanKingdon, @Paranoid93, @TeddyStarinvest and @Ybbet.
@@ -37,7 +88,7 @@ Special thanks to @khassel, @rejas and @sdetweil for taking over most (if not al
- Update issue template
- Update dev/dependencies incl. electron to v26
- Replace pretty-quick by lint-staged (<https://github.com/azz/pretty-quick/issues/164>)
- Update engine node >=18. v16 reached it's end of life. (#3170)
- Update engine node >=18. v16 reached its end of life. (#3170)
- Update typescript definition for modules
- Cleaned up nunjuck templates
- Replace `node-fetch` with internal fetch (#2649) and remove `digest-fetch`
@@ -50,7 +101,7 @@ Special thanks to @khassel, @rejas and @sdetweil for taking over most (if not al
- Fix engine check on npm install (#3135)
- Fix undefined formatTime method in clock module (#3143)
- Fix clientonly startup fails after async added (#3151)
- Fix electron width/heigth when using xrandr under bullseye
- Fix electron width/height when using xrandr under bullseye
- Fix time issue with certain recurring events in calendar module
- Fix ipWhiteList test (#3179)
- Fix newsfeed: Convert HTML entities, codes and tag in description (#3191)
@@ -59,6 +110,7 @@ Special thanks to @khassel, @rejas and @sdetweil for taking over most (if not al
- Fix `Uncaught SyntaxError: Identifier 'getCorsUrl' has already been declared (at utils.js:1:1)` when using `clock` and `weather` module (#3204)
- Fix overriding `config.js` when running tests (#3201)
- Fix issue in weathergov provider with probability of precipitation not showing up on hourly or daily forecast
- Fix yr weather provider after changes in yr API (#3189)
## [2.24.0] - 2023-07-01
@@ -101,7 +153,6 @@ Special thanks to @khassel, @rejas and @sdetweil for taking over most (if not al
- Fix date not shown when clock in analog mode (#3100)
- Fix envcanada today percentage-of-precipitation (#3106)
- Fix updatenotification where no branch is checked out but e.g. a version tag (#3130)
- Fix yr weather provider after changes in yr API (#3189)
## [2.23.0] - 2023-04-04

View File

@@ -6,9 +6,6 @@
</a>
<img src="https://img.shields.io/github/actions/workflow/status/michmich/magicmirror/automated-tests.yaml" alt="GitHub Actions">
<img src="https://img.shields.io/github/checks-status/michmich/magicmirror/master" alt="Build Status">
<a href="https://codecov.io/gh/MichMich/MagicMirror">
<img src="https://codecov.io/gh/MichMich/MagicMirror/branch/master/graph/badge.svg?token=LEG1KitZR6" alt="CodeCov Status"/>
</a>
<a href="https://github.com/MichMich/MagicMirror">
<img src="https://img.shields.io/github/stars/michmich/magicmirror?style=social">
</a>

View File

@@ -8,6 +8,7 @@
* Helper function to get server address/hostname from either the commandline or env
*/
function getServerAddress () {
/**
* Get command line parameters
* Assumes that a cmdline parameter is defined with `--key [value]`
@@ -121,4 +122,4 @@
} else {
fail();
}
})();
}());

View File

@@ -1,6 +1,6 @@
{
"name": "magicmirror-fonts",
"lockfileVersion": 2,
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
@@ -8,7 +8,7 @@
"license": "MIT",
"dependencies": {
"@fontsource/roboto": "^5.0.8",
"@fontsource/roboto-condensed": "^5.0.8"
"@fontsource/roboto-condensed": "^5.0.14"
}
},
"node_modules/@fontsource/roboto": {
@@ -17,21 +17,9 @@
"integrity": "sha512-XxPltXs5R31D6UZeLIV1td3wTXU3jzd3f2DLsXI8tytMGBkIsGcc9sIyiupRtA8y73HAhuSCeweOoBqf6DbWCA=="
},
"node_modules/@fontsource/roboto-condensed": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/@fontsource/roboto-condensed/-/roboto-condensed-5.0.8.tgz",
"integrity": "sha512-xAXYY+ys24OZ/eOfXJZILPu2xOB7c0ZruM4cd4TSzX3WGj4dZbXYwCEowLldKbZye6LTqiltpFLP/g/Ne0qGLg=="
}
},
"dependencies": {
"@fontsource/roboto": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/@fontsource/roboto/-/roboto-5.0.8.tgz",
"integrity": "sha512-XxPltXs5R31D6UZeLIV1td3wTXU3jzd3f2DLsXI8tytMGBkIsGcc9sIyiupRtA8y73HAhuSCeweOoBqf6DbWCA=="
},
"@fontsource/roboto-condensed": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/@fontsource/roboto-condensed/-/roboto-condensed-5.0.8.tgz",
"integrity": "sha512-xAXYY+ys24OZ/eOfXJZILPu2xOB7c0ZruM4cd4TSzX3WGj4dZbXYwCEowLldKbZye6LTqiltpFLP/g/Ne0qGLg=="
"version": "5.0.14",
"resolved": "https://registry.npmjs.org/@fontsource/roboto-condensed/-/roboto-condensed-5.0.14.tgz",
"integrity": "sha512-ZNBHUhE5/3z9efMIjpBblFsfLHgGotJjlzKd5Q8DODbkRRWy6Yh+JnbiaJZ8zwQyHyYBNOolk57BG4BcjSzrRg=="
}
}
}

View File

@@ -11,6 +11,6 @@
},
"dependencies": {
"@fontsource/roboto": "^5.0.8",
"@fontsource/roboto-condensed": "^5.0.8"
"@fontsource/roboto-condensed": "^5.0.14"
}
}

View File

@@ -139,7 +139,7 @@ function addAnimateCSS(element, animation, animationTime) {
const node = document.getElementById(element);
if (!node) {
// don't execute animate: we don't find div
Log.warn(`addAnimateCSS: node not found for`, element);
Log.warn("addAnimateCSS: node not found for", element);
return;
}
node.style.setProperty("--animate-duration", `${animationTime}s`);
@@ -156,7 +156,7 @@ function removeAnimateCSS(element, animation) {
const node = document.getElementById(element);
if (!node) {
// don't execute animate: we don't find div
Log.warn(`removeAnimateCSS: node not found for`, element);
Log.warn("removeAnimateCSS: node not found for", element);
return;
}
node.classList.remove("animate__animated", animationName);

View File

@@ -12,6 +12,7 @@ const fs = require("fs");
const path = require("path");
const envsub = require("envsub");
const Log = require("logger");
const Server = require(`${__dirname}/server`);
const Utils = require(`${__dirname}/utils`);
const defaultModules = require(`${__dirname}/../modules/default/defaultmodules`);
@@ -24,7 +25,7 @@ Log.log(`Starting MagicMirror: v${global.version}`);
global.root_path = path.resolve(`${__dirname}/../`);
if (process.env.MM_CONFIG_FILE) {
global.configuration_file = process.env.MM_CONFIG_FILE;
global.configuration_file = process.env.MM_CONFIG_FILE.replace(`${global.root_path}/`, "");
}
// FIXME: Hotfix Pull Request

View File

@@ -9,7 +9,7 @@
*/
(function () {
let initializing = false;
const fnTest = /xyz/.test(function () {
const fnTest = (/xyz/).test(function () {
xyz;
})
? /\b_super\b/
@@ -36,8 +36,8 @@
// Copy the properties over onto the new prototype
for (const name in prop) {
// Check if we're overwriting an existing function
prototype[name] =
typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name])
prototype[name]
= typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name])
? (function (name, fn) {
return function () {
const tmp = this._super;
@@ -53,7 +53,7 @@
return ret;
};
})(name, prop[name])
}(name, prop[name]))
: prop[name];
}
@@ -78,7 +78,7 @@
return Class;
};
})();
}());
/**
* Define the clone method for later use. Helper Method.
@@ -90,6 +90,10 @@ function cloneObject(obj) {
return obj;
}
if (obj.constructor.name === "RegExp") {
return new RegExp(obj);
}
const temp = obj.constructor(); // give temp the original obj's constructor
for (const key in obj) {
temp[key] = cloneObject(obj[key]);

View File

@@ -8,9 +8,10 @@ const Log = require("./logger");
let config = process.env.config ? JSON.parse(process.env.config) : {};
// Module to control application life.
const app = electron.app;
// If ELECTRON_DISABLE_GPU is set electron is started with --disable-gpu flag.
// Per default electron is started with --disable-gpu flag, if you want the gpu enabled,
// you must set the env var ELECTRON_ENABLE_GPU=1 on startup.
// See https://www.electronjs.org/docs/latest/tutorial/offscreen-rendering for more info.
if (process.env.ELECTRON_DISABLE_GPU !== undefined) {
if (process.env.ELECTRON_ENABLE_GPU !== "1") {
app.disableHardwareAcceleration();
}
@@ -77,8 +78,9 @@ function createWindow() {
prefix = "http://";
}
let address = (config.address === void 0) | (config.address === "") ? (config.address = "localhost") : config.address;
mainWindow.loadURL(`${prefix}${address}:${config.port}`);
let address = (config.address === void 0) | (config.address === "") | (config.address === "0.0.0.0") ? (config.address = "localhost") : config.address;
const port = process.env.MM_PORT || config.port;
mainWindow.loadURL(`${prefix}${address}:${port}`);
// Open the DevTools if run with "npm start dev"
if (process.argv.includes("dev")) {
@@ -120,11 +122,11 @@ function createWindow() {
mainWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
let curHeaders = details.responseHeaders;
if (config["ignoreXOriginHeader"] || false) {
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !/x-frame-options/i.test(header[0])));
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !(/x-frame-options/i).test(header[0])));
}
if (config["ignoreContentSecurityPolicy"] || false) {
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !/content-security-policy/i.test(header[0])));
curHeaders = Object.fromEntries(Object.entries(curHeaders).filter((header) => !(/content-security-policy/i).test(header[0])));
}
callback({ responseHeaders: curHeaders });

View File

@@ -7,6 +7,7 @@
* MIT Licensed.
*/
const Loader = (function () {
/* Create helper variables */
const loadedModuleFiles = [];
@@ -196,10 +197,11 @@ const Loader = (function () {
/* Public Methods */
return {
/**
* Load all modules as defined in the config.
*/
loadModules: async function () {
async loadModules () {
let moduleData = getModuleData();
/**
@@ -230,7 +232,7 @@ const Loader = (function () {
* @param {Module} module The module that calls the loadFile function.
* @returns {Promise} resolved when the file is loaded
*/
loadFileForModule: async function (fileName, module) {
async loadFileForModule (fileName, module) {
if (loadedFiles.indexOf(fileName.toLowerCase()) !== -1) {
Log.log(`File already loaded: ${fileName}`);
return;
@@ -256,4 +258,4 @@ const Loader = (function () {
return loadFile(module.file(fileName));
}
};
})();
}());

View File

@@ -22,7 +22,7 @@
// Browser globals (root is window)
root.Log = factory(root.config);
}
})(this, function (config) {
}(this, function (config) {
let logLevel;
let enableLog;
if (typeof exports === "object") {
@@ -50,7 +50,7 @@
logLevel.setLogLevel = function (newLevel) {
if (newLevel) {
Object.keys(logLevel).forEach(function (key, index) {
Object.keys(logLevel).forEach(function (key) {
if (!newLevel.includes(key.toLocaleUpperCase())) {
logLevel[key] = function () {};
}
@@ -59,21 +59,21 @@
};
} else {
logLevel = {
debug: function () {},
log: function () {},
info: function () {},
warn: function () {},
error: function () {},
group: function () {},
groupCollapsed: function () {},
groupEnd: function () {},
time: function () {},
timeEnd: function () {},
timeStamp: function () {}
debug () {},
log () {},
info () {},
warn () {},
error () {},
group () {},
groupCollapsed () {},
groupEnd () {},
time () {},
timeEnd () {},
timeStamp () {}
};
logLevel.setLogLevel = function () {};
}
return logLevel;
});
}));

View File

@@ -479,7 +479,6 @@ const MM = (function () {
*/
const loadConfig = function () {
// FIXME: Think about how to pass config around without breaking tests
/* eslint-disable */
if (typeof config === "undefined") {
config = defaults;
Log.error("Config file is missing! Please create a config file.");
@@ -487,7 +486,6 @@ const MM = (function () {
}
config = Object.assign({}, defaults, config);
/* eslint-enable */
};
/**
@@ -495,6 +493,7 @@ const MM = (function () {
* @param {Module[]} modules Array of modules.
*/
const setSelectionMethodsForModules = function (modules) {
/**
* Filter modules with the specified classes.
* @param {string|string[]} className one or multiple classnames (array or space divided).
@@ -580,12 +579,13 @@ const MM = (function () {
};
return {
/* Public Methods */
/**
* Main init method.
*/
init: async function () {
async init () {
Log.info("Initializing MagicMirror².");
loadConfig();
@@ -599,7 +599,7 @@ const MM = (function () {
* Gets called when all modules are started.
* @param {Module[]} moduleObjects All module instances.
*/
modulesStarted: function (moduleObjects) {
modulesStarted (moduleObjects) {
modules = [];
let startUp = "";
@@ -636,7 +636,7 @@ const MM = (function () {
* @param {*} payload The payload of the notification.
* @param {Module} sender The module that sent the notification.
*/
sendNotification: function (notification, payload, sender) {
sendNotification (notification, payload, sender) {
if (arguments.length < 3) {
Log.error("sendNotification: Missing arguments.");
return;
@@ -661,7 +661,7 @@ const MM = (function () {
* @param {Module} module The module that needs an update.
* @param {object|number} [updateOptions] The (optional) number of microseconds for the animation or object with updateOptions (speed/animates)
*/
updateDom: function (module, updateOptions) {
updateDom (module, updateOptions) {
if (!(module instanceof Module)) {
Log.error("updateDom: Sender should be a module.");
return;
@@ -680,7 +680,7 @@ const MM = (function () {
* Returns a collection of all modules currently active.
* @returns {Module[]} A collection of all modules currently active.
*/
getModules: function () {
getModules () {
setSelectionMethodsForModules(modules);
return modules;
},
@@ -692,7 +692,7 @@ const MM = (function () {
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the hide method.
*/
hideModule: function (module, speed, callback, options) {
hideModule (module, speed, callback, options) {
module.hidden = true;
hideModule(module, speed, callback, options);
},
@@ -704,12 +704,12 @@ const MM = (function () {
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the show method.
*/
showModule: function (module, speed, callback, options) {
showModule (module, speed, callback, options) {
// do not change module.hidden yet, only if we really show it later
showModule(module, speed, callback, options);
}
};
})();
}());
// Add polyfill for Object.assign.
if (typeof Object.assign !== "function") {
@@ -732,7 +732,7 @@ if (typeof Object.assign !== "function") {
}
return output;
};
})();
}());
}
MM.init();

View File

@@ -8,6 +8,7 @@
* MIT Licensed.
*/
const Module = Class.extend({
/*********************************************************
* All methods (and properties) below can be subclassed. *
*********************************************************/
@@ -33,14 +34,14 @@ const Module = Class.extend({
/**
* Called when the module is instantiated.
*/
init: function () {
init () {
//Log.log(this.defaults);
},
/**
* Called when the module is started.
*/
start: async function () {
async start () {
Log.info(`Starting module: ${this.name}`);
},
@@ -48,7 +49,7 @@ const Module = Class.extend({
* Returns a list of scripts the module requires to be loaded.
* @returns {string[]} An array with filenames.
*/
getScripts: function () {
getScripts () {
return [];
},
@@ -56,7 +57,7 @@ const Module = Class.extend({
* Returns a list of stylesheets the module requires to be loaded.
* @returns {string[]} An array with filenames.
*/
getStyles: function () {
getStyles () {
return [];
},
@@ -66,7 +67,7 @@ const Module = Class.extend({
* return Map<String, String> -
* @returns {*} A map with langKeys and filenames.
*/
getTranslations: function () {
getTranslations () {
return false;
},
@@ -76,14 +77,14 @@ const Module = Class.extend({
* Alternatively, the getTemplate method could be subclassed.
* @returns {HTMLElement|Promise} The dom or a promise with the dom to display.
*/
getDom: function () {
getDom () {
return new Promise((resolve) => {
const div = document.createElement("div");
const template = this.getTemplate();
const templateData = this.getTemplateData();
// Check to see if we need to render a template string or a file.
if (/^.*((\.html)|(\.njk))$/.test(template)) {
if ((/^.*((\.html)|(\.njk))$/).test(template)) {
// the template is a filename
this.nunjucksEnvironment().render(template, templateData, function (err, res) {
if (err) {
@@ -109,7 +110,7 @@ const Module = Class.extend({
* This method needs to be subclassed if the module wants to display modified headers on the mirror.
* @returns {string} The header to display above the header.
*/
getHeader: function () {
getHeader () {
return this.data.header;
},
@@ -120,7 +121,7 @@ const Module = Class.extend({
* If the string ends with '.html' it's considered a file from within the module's folder.
* @returns {string} The template string of filename.
*/
getTemplate: function () {
getTemplate () {
return `<div class="normal">${this.name}</div><div class="small dimmed">${this.identifier}</div>`;
},
@@ -129,7 +130,7 @@ const Module = Class.extend({
* This method needs to be subclassed if the module wants to use a custom data.
* @returns {object} The data for the template
*/
getTemplateData: function () {
getTemplateData () {
return {};
},
@@ -139,7 +140,7 @@ const Module = Class.extend({
* @param {*} payload The payload of the notification.
* @param {Module} sender The module that sent the notification.
*/
notificationReceived: function (notification, payload, sender) {
notificationReceived (notification, payload, sender) {
if (sender) {
// Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
} else {
@@ -152,7 +153,7 @@ const Module = Class.extend({
* The environment is checked in the _nunjucksEnvironment instance variable.
* @returns {object} The Nunjucks Environment
*/
nunjucksEnvironment: function () {
nunjucksEnvironment () {
if (this._nunjucksEnvironment !== null) {
return this._nunjucksEnvironment;
}
@@ -174,21 +175,21 @@ const Module = Class.extend({
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
socketNotificationReceived: function (notification, payload) {
socketNotificationReceived (notification, payload) {
Log.log(`${this.name} received a socket notification: ${notification} - Payload: ${payload}`);
},
/**
* Called when the module is hidden.
*/
suspend: function () {
suspend () {
Log.log(`${this.name} is suspended.`);
},
/**
* Called when the module is shown.
*/
resume: function () {
resume () {
Log.log(`${this.name} is resumed.`);
},
@@ -200,7 +201,7 @@ const Module = Class.extend({
* Set the module data.
* @param {object} data The module data
*/
setData: function (data) {
setData (data) {
this.data = data;
this.name = data.name;
this.identifier = data.identifier;
@@ -216,7 +217,7 @@ const Module = Class.extend({
* @param {object} config The combined module config.
* @param {boolean} deep Merge module config in deep.
*/
setConfig: function (config, deep) {
setConfig (config, deep) {
this.config = deep ? configMerge({}, this.defaults, config) : Object.assign({}, this.defaults, config);
},
@@ -225,7 +226,7 @@ const Module = Class.extend({
* It also registers the notification callback.
* @returns {MMSocket} a socket object
*/
socket: function () {
socket () {
if (typeof this._socket === "undefined") {
this._socket = new MMSocket(this.name);
}
@@ -242,7 +243,7 @@ const Module = Class.extend({
* @param {string} file Filename
* @returns {string} the file path
*/
file: function (file) {
file (file) {
return `${this.data.path}/${file}`.replace("//", "/");
},
@@ -250,7 +251,7 @@ const Module = Class.extend({
* Load all required stylesheets by requesting the MM object to load the files.
* @returns {Promise<void>}
*/
loadStyles: function () {
loadStyles () {
return this.loadDependencies("getStyles");
},
@@ -258,7 +259,7 @@ const Module = Class.extend({
* Load all required scripts by requesting the MM object to load the files.
* @returns {Promise<void>}
*/
loadScripts: function () {
loadScripts () {
return this.loadDependencies("getScripts");
},
@@ -267,7 +268,7 @@ const Module = Class.extend({
* @param {string} funcName Function name to call to get scripts or styles.
* @returns {Promise<void>}
*/
loadDependencies: async function (funcName) {
async loadDependencies (funcName) {
let dependencies = this[funcName]();
const loadNextDependency = async () => {
@@ -288,7 +289,7 @@ const Module = Class.extend({
* Load all translations.
* @returns {Promise<void>}
*/
loadTranslations: async function () {
async loadTranslations () {
const translations = this.getTranslations() || {};
const language = config.language.toLowerCase();
@@ -320,7 +321,7 @@ const Module = Class.extend({
* @param {string} [defaultValue] The default value with variables.
* @returns {string} the translated key
*/
translate: function (key, defaultValueOrVariables, defaultValue) {
translate (key, defaultValueOrVariables, defaultValue) {
if (typeof defaultValueOrVariables === "object") {
return Translator.translate(this, key, defaultValueOrVariables) || defaultValue || "";
}
@@ -331,7 +332,7 @@ const Module = Class.extend({
* Request an (animated) update of the module.
* @param {number|object} [updateOptions] The speed of the animation or object with for updateOptions (speed/animates)
*/
updateDom: function (updateOptions) {
updateDom (updateOptions) {
MM.updateDom(this, updateOptions);
},
@@ -340,7 +341,7 @@ const Module = Class.extend({
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
sendNotification: function (notification, payload) {
sendNotification (notification, payload) {
MM.sendNotification(notification, payload, this);
},
@@ -349,7 +350,7 @@ const Module = Class.extend({
* @param {string} notification The identifier of the notification.
* @param {*} payload The payload of the notification.
*/
sendSocketNotification: function (notification, payload) {
sendSocketNotification (notification, payload) {
this.socket().sendNotification(notification, payload);
},
@@ -359,7 +360,7 @@ const Module = Class.extend({
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the hide method.
*/
hide: function (speed, callback, options = {}) {
hide (speed, callback, options = {}) {
let usedCallback = callback || function () {};
let usedOptions = options;
@@ -386,7 +387,7 @@ const Module = Class.extend({
* @param {Function} callback Called when the animation is done.
* @param {object} [options] Optional settings for the show method.
*/
show: function (speed, callback, options) {
show (speed, callback, options) {
let usedCallback = callback || function () {};
let usedOptions = options;

View File

@@ -1,6 +1,7 @@
const fs = require("fs");
const path = require("path");
const Log = require("logger");
const startUp = new Date();
/**

View File

@@ -7,6 +7,7 @@
* MIT Licensed.
*/
const Translator = (function () {
/**
* Load a JSON file via XHR.
* @param {string} file Path of the file we want to load.
@@ -47,7 +48,8 @@ const Translator = (function () {
* @param {object} variables The variables to use within the translation template (optional)
* @returns {string} the translated key
*/
translate: function (module, key, variables = {}) {
translate (module, key, variables = {}) {
/**
* Combines template and variables like:
* template: "Please wait for {timeToWait} before continuing with {work}."
@@ -115,7 +117,7 @@ const Translator = (function () {
* Load the core translations.
* @param {string} lang The language identifier of the core language.
*/
loadCoreTranslations: async function (lang) {
async loadCoreTranslations (lang) {
if (lang in translations) {
Log.log(`Loading core translation file: ${translations[lang]}`);
this.coreTranslations = await loadJSON(translations[lang]);
@@ -130,7 +132,7 @@ const Translator = (function () {
* Load the core translations' fallback.
* The first language defined in translations.js will be used.
*/
loadCoreTranslationsFallback: async function () {
async loadCoreTranslationsFallback () {
let first = Object.keys(translations)[0];
if (first) {
Log.log(`Loading core translation fallback file: ${translations[first]}`);
@@ -138,6 +140,6 @@ const Translator = (function () {
}
}
};
})();
}());
window.Translator = Translator;

View File

@@ -22,7 +22,7 @@ Module.register("alert", {
},
getStyles () {
return ["font-awesome.css", this.file(`./styles/notificationFx.css`), this.file(`./styles/${this.config.position}.css`)];
return ["font-awesome.css", this.file("./styles/notificationFx.css"), this.file(`./styles/${this.config.position}.css`)];
},
getTranslations () {

View File

@@ -12,6 +12,7 @@
* @param {object} window The window object
*/
(function (window) {
/**
* Extend one object with another one
* @param {object} a The object to extend
@@ -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));

View File

@@ -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)
);
}
});

View File

@@ -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

View File

@@ -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,24 +91,40 @@ 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];
const regParts = needle.match(/^\/(.+)\/([gim]*)$/);
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.
// the parsed pattern is a regexp with flags.
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);
}
}
}
return transformedTitle;
}
};

View File

@@ -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(),

View File

@@ -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);
}

View File

@@ -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;
}

View File

@@ -10,11 +10,11 @@ Module.register("helloworld", {
text: "Hello World!"
},
getTemplate: function () {
getTemplate () {
return "helloworld.njk";
},
getTemplateData: function () {
getTemplateData () {
return this.config;
}
});

View File

@@ -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

View File

@@ -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,

View File

@@ -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();

View File

@@ -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,6 +12,7 @@ module.exports = NodeHelper.create({
updateProcessStarted: false,
gitHelper: new GitHelper(),
updateHelper: null,
async configureModules (modules) {
for (const moduleName of modules) {
@@ -28,6 +30,8 @@ module.exports = NodeHelper.create({
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
@@ -51,12 +55,22 @@ module.exports = NodeHelper.create({
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);
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);

View 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;

View File

@@ -9,11 +9,16 @@ 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 () {
Log.info(`Starting module: ${this.name}`);
@@ -47,12 +52,15 @@ Module.register("updatenotification", {
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;
}
},
@@ -65,7 +73,7 @@ Module.register("updatenotification", {
},
getTemplateData () {
return { moduleList: this.moduleList, suspended: this.suspended };
return { moduleList: this.moduleList, updatesList: this.updates, suspended: this.suspended, needRestart: this.needRestart };
},
updateUI (payload) {
@@ -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);
}
}
});

View File

@@ -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 %}

View File

@@ -165,8 +165,7 @@ const formatTime = (config, time) => {
return date.format("HH:mm");
};
if (typeof module !== "undefined")
module.exports = {
if (typeof module !== "undefined") module.exports = {
performWebRequest,
formatTime
};

View File

@@ -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);
},

View File

@@ -140,7 +140,7 @@ WeatherProvider.register("openmeteo", {
"et0_fao_evapotranspiration"
],
fetchedLocation: function () {
fetchedLocation () {
return this.fetchedLocationName || "";
},
@@ -284,15 +284,13 @@ WeatherProvider.register("openmeteo", {
// Transpose hourly and daily data matrices
transposeDataMatrix (data) {
return data.time.map((_, index) =>
Object.keys(data).reduce((row, key) => {
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
@@ -350,6 +348,7 @@ WeatherProvider.register("openmeteo", {
// Implement WeatherDay generator.
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.
@@ -397,7 +396,7 @@ WeatherProvider.register("openmeteo", {
generateWeatherObjectsFromForecast (weathers) {
const days = [];
weathers.daily.forEach((weather, i) => {
weathers.daily.forEach((weather) => {
const currentWeather = new WeatherObject();
currentWeather.date = weather.time;
@@ -542,7 +541,7 @@ WeatherProvider.register("openmeteo", {
},
// Define required scripts.
getScripts: function () {
getScripts () {
return ["moment.js"];
}
});

View File

@@ -225,7 +225,7 @@ WeatherProvider.register("ukmetofficedatahub", {
},
// Set the fetched location name.
setFetchedLocation: function (name) {
setFetchedLocation (name) {
this.fetchedLocationName = name;
},

View File

@@ -23,7 +23,7 @@ WeatherProvider.register("weatherbit", {
lon: 0
},
fetchedLocation: function () {
fetchedLocation () {
return this.fetchedLocationName || "";
},

View File

@@ -37,19 +37,19 @@ 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 || "";
},
@@ -162,6 +162,7 @@ WeatherProvider.register("weathergov", {
}
});
},
/*
* Generate a WeatherObject based on hourlyWeatherInformation
* Weather.gov API uses specific units; API does not include choice of units

View File

@@ -18,6 +18,8 @@ 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
},
@@ -44,8 +46,7 @@ WeatherProvider.register("yr", {
},
async getCurrentWeather () {
const getRequests = [this.getWeatherData(), this.getStellarData()];
const [weatherData, stellarData] = await Promise.all(getRequests);
const [weatherData, stellarData] = await Promise.all([this.getWeatherData(), this.getStellarData()]);
if (!stellarData) {
Log.warn("No stellar data available.");
}
@@ -132,10 +133,10 @@ WeatherProvider.register("yr", {
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))
);
},
@@ -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,18 +201,13 @@ 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) {
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 () {
// 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.
@@ -302,7 +303,7 @@ WeatherProvider.register("yr", {
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,7 +342,7 @@ 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) {
@@ -472,15 +462,6 @@ 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) {
if (this.config.currentForecastHours === 1) {
if (weather.next_1_hours) {
@@ -522,8 +503,7 @@ WeatherProvider.register("yr", {
},
async getWeatherForecast (type) {
const getRequests = [this.getWeatherData(), this.getStellarData()];
const [weatherData, stellarData] = await Promise.all(getRequests);
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;
@@ -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;

View File

@@ -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,7 +205,7 @@ 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;

View File

@@ -16,6 +16,7 @@
* @external Moment
*/
class WeatherObject {
/**
* Constructor for a WeatherObject
*/

View File

@@ -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);

View File

@@ -5,6 +5,7 @@
* MIT Licensed.
*/
const WeatherUtils = {
/**
* Convert wind (from m/s) to beaufort scale
* @param {number} speedInMS the windspeed you want to convert
@@ -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;

3359
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "magicmirror",
"version": "2.25.0",
"version": "2.26.0",
"description": "The open source modular smart mirror platform.",
"main": "js/electron.js",
"scripts": {
@@ -18,12 +18,12 @@
"test:e2e": "NODE_ENV=test jest --selectProjects e2e -i --forceExit",
"test:unit": "NODE_ENV=test jest --selectProjects unit",
"test:prettier": "prettier . --check",
"test:js": "eslint 'js/**/*.js' 'modules/default/**/*.js' 'clientonly/*.js' 'serveronly/*.js' 'translations/*.js' 'vendor/*.js' 'tests/**/*.js' 'config/*' --config .eslintrc.json",
"test:js": "eslint 'js/**/*.js' 'modules/default/**/*.js' 'clientonly/*.js' 'serveronly/*.js' 'translations/*.js' 'vendor/*.js' 'tests/**/*.js' 'config/*'",
"test:css": "stylelint 'css/main.css' 'fonts/*.css' 'modules/default/**/*.css' 'vendor/*.css' --config .stylelintrc.json",
"test:calendar": "node ./modules/default/calendar/debug.js",
"config:check": "node js/check_config.js",
"lint:prettier": "prettier . --write",
"lint:js": "eslint 'js/**/*.js' 'modules/default/**/*.js' 'clientonly/*.js' 'serveronly/*.js' 'translations/*.js' 'vendor/*.js' 'tests/**/*.js' 'config/*' --config .eslintrc.json --fix",
"lint:js": "eslint 'js/**/*.js' 'modules/default/**/*.js' 'clientonly/*.js' 'serveronly/*.js' 'translations/*.js' 'vendor/*.js' 'tests/**/*.js' 'config/*' --fix",
"lint:css": "stylelint 'css/main.css' 'fonts/*.css' 'modules/default/**/*.css' 'vendor/*.css' --config .stylelintrc.json --fix",
"lint:staged": "lint-staged",
"prepare": "[ -f node_modules/.bin/husky ] && husky install || echo no husky installed."
@@ -49,43 +49,42 @@
},
"homepage": "https://magicmirror.builders",
"devDependencies": {
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-import": "^2.28.1",
"eslint-plugin-jest": "^27.4.2",
"eslint-plugin-jsdoc": "^46.8.2",
"eslint-plugin-prettier": "^5.0.0",
"@stylistic/eslint-plugin": "^1.5.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-jest": "^27.6.0",
"eslint-plugin-jsdoc": "^46.9.1",
"express-basic-auth": "^1.2.1",
"husky": "^8.0.3",
"jest": "^29.7.0",
"jsdom": "^22.1.0",
"lint-staged": "^14.0.1",
"jsdom": "^23.0.1",
"lint-staged": "^15.2.0",
"lodash": "^4.17.21",
"playwright": "^1.38.1",
"prettier": "^3.0.3",
"sinon": "^16.0.0",
"stylelint": "^15.10.3",
"stylelint-config-standard": "^34.0.0",
"stylelint-prettier": "^4.0.2",
"playwright": "^1.40.1",
"prettier": "^3.1.1",
"sinon": "^17.0.1",
"stylelint": "^16.1.0",
"stylelint-config-standard": "^36.0.0",
"stylelint-prettier": "^5.0.0",
"suncalc": "^1.9.0"
},
"optionalDependencies": {
"electron": "^26.2.4"
"electron": "^27.2.0"
},
"dependencies": {
"colors": "^1.4.0",
"command-exists": "^1.2.9",
"console-stamp": "^3.1.2",
"envsub": "^4.1.0",
"eslint": "^8.50.0",
"eslint": "^8.56.0",
"express": "^4.18.2",
"express-ipfilter": "^1.3.1",
"feedme": "^2.0.2",
"helmet": "^7.0.0",
"helmet": "^7.1.0",
"html-to-text": "^9.0.5",
"iconv-lite": "^0.6.3",
"luxon": "^1.28.1",
"module-alias": "^2.2.3",
"moment": "^2.29.4",
"node-ical": "^0.16.1",
"moment": "^2.30.1",
"node-ical": "^0.17.1",
"socket.io": "^4.7.2"
},
"lint-staged": {

View File

@@ -0,0 +1,27 @@
/* MagicMirror² Test ics with out of date event causing bad return from rrule.between
*
* By Sam Detweiler
* MIT Licensed.
*/
let config = {
timeFormat: 12,
logLevel: ["INFO", "LOG", "WARN", "ERROR", "DEBUG"],
modules: [
{
module: "calendar",
position: "bottom_bar",
config: {
calendars: [
{
url: "http://localhost:8080/tests/mocks/bad_rrule.ics"
}
]
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}

View File

@@ -0,0 +1,36 @@
/* MagicMirror² Test calendar exdate
*
* By jkriegshauser
* MIT Licensed.
*
* NOTE: calendar_test_exdate.ics has exdate entries for the next 20 years, but without some
* way to set a debug date for tests, this test may become flaky on specific days (i.e. could
* not test easily on leap-years, the BYDAY specified in exdate, etc.) or when the 20 years
* elapses if this project is still in active development ;)
* See issue #3250
*/
let config = {
timeFormat: 12,
modules: [
{
module: "calendar",
position: "bottom_bar",
config: {
maximumEntries: 100,
calendars: [
{
maximumEntries: 100,
maximumNumberOfDays: 364,
url: "http://localhost:8080/tests/mocks/calendar_test_exdate.ics"
}
]
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}

View File

@@ -5,7 +5,7 @@
* 09/2023
* MIT Licensed.
*/
const helpers = require("./helpers/global-setup.js");
const helpers = require("./helpers/global-setup");
describe("AnimateCSS integration Test", () => {
// define config file for testing
@@ -21,27 +21,29 @@ describe("AnimateCSS integration Test", () => {
* move similar tests in function doTest
* @param {string} [animationIn] animation in name of AnimateCSS to test.
* @param {string} [animationOut] animation out name of AnimateCSS to test.
* @returns {boolean} result
*/
const doTest = async (animationIn, animationOut) => {
await helpers.getDocument();
let elem = await helpers.waitForElement(`.compliments`);
expect(elem).not.toBe(null);
let elem = await helpers.waitForElement(".compliments");
expect(elem).not.toBeNull();
let styles = window.getComputedStyle(elem);
if (animationIn && animationIn !== "") {
expect(styles._values["animation-name"]).toBe(animationIn);
} else {
expect(styles._values["animation-name"]).toBe(undefined);
expect(styles._values["animation-name"]).toBeUndefined();
}
if (animationOut && animationOut !== "") {
elem = await helpers.waitForElement(`.compliments.animate__animated.animate__${animationOut}`);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
styles = window.getComputedStyle(elem);
expect(styles._values["animation-name"]).toBe(animationOut);
} else {
expect(styles._values["animation-name"]).toBe(undefined);
expect(styles._values["animation-name"]).toBeUndefined();
}
return true;
};
afterEach(async () => {
@@ -51,28 +53,28 @@ describe("AnimateCSS integration Test", () => {
describe("animateIn and animateOut Test", () => {
it("with flipInX and flipOutX animation", async () => {
await helpers.startApplication(testConfigFile);
await doTest("flipInX", "flipOutX");
await expect(doTest("flipInX", "flipOutX")).resolves.toBe(true);
});
});
describe("use animateOut name for animateIn (vice versa) Test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigFileInvertedAnimationName);
await doTest();
await expect(doTest()).resolves.toBe(true);
});
});
describe("false Animation name test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigFileFallbackToDefault);
await doTest();
await expect(doTest()).resolves.toBe(true);
});
});
describe("no Animation defined test", () => {
it("without animation", async () => {
await helpers.startApplication(testConfigByDefault);
await doTest();
await expect(doTest()).resolves.toBe(true);
});
});
});

View File

@@ -21,7 +21,7 @@ describe("App environment", () => {
it("should show the title MagicMirror²", async () => {
const elem = await helpers.waitForElement("title");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toBe("MagicMirror²");
});
});

View File

@@ -20,7 +20,7 @@ describe("All font files from roboto.css should be downloadable", () => {
await helpers.stopApplication();
});
test.each(fontFiles)("should return 200 HTTP code for file '%s'", async (fontFile) => {
it.each(fontFiles)("should return 200 HTTP code for file '%s'", async (fontFile) => {
const fontUrl = `http://localhost:8080/fonts/${fontFile}`;
const res = await fetch(fontUrl);
expect(res.status).toBe(200);

View File

@@ -1,6 +1,7 @@
const path = require("path");
const auth = require("express-basic-auth");
const express = require("express");
const app = express();
const basicAuth = auth({

View File

@@ -31,6 +31,11 @@ exports.getDocument = () => {
jsdom.JSDOM.fromURL(url, { resources: "usable", runScripts: "dangerously" }).then((dom) => {
dom.window.name = "jsdom";
global.window = dom.window;
// Following fixes `navigator is not defined` errors in e2e tests, found here
// https://www.appsloveworld.com/reactjs/100/37/mocha-react-navigator-is-not-defined
global.navigator = {
useragent: "node.js"
};
dom.window.fetch = fetch;
dom.window.onload = () => {
global.document = dom.window.document;
@@ -82,6 +87,7 @@ exports.waitForAllElements = (selector) => {
exports.testMatch = async (element, regex) => {
const elem = await this.waitForElement(element);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toMatch(regex);
return true;
};

View File

@@ -4,13 +4,13 @@
*/
const mockError = (err) => {
if (
err.includes("ECONNREFUSED") ||
err.includes("ECONNRESET") ||
err.includes("socket hang up") ||
err.includes("exports is not defined") ||
err.includes("write EPIPE") ||
err.includes("AggregateError") ||
err.includes("ERR_SOCKET_CONNECTION_TIMEOUT")
err.includes("ECONNREFUSED")
|| err.includes("ECONNRESET")
|| err.includes("socket hang up")
|| err.includes("exports is not defined")
|| err.includes("write EPIPE")
|| err.includes("AggregateError")
|| err.includes("ERR_SOCKET_CONNECTION_TIMEOUT")
) {
jest.fn();
} else {

View File

@@ -3,13 +3,14 @@ const helpers = require("./global-setup");
exports.getText = async (element, result) => {
const elem = await helpers.waitForElement(element);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(
elem.textContent
.trim()
.replace(/(\r\n|\n|\r)/gm, "")
.replace(/[ ]+/g, " ")
).toBe(result);
return true;
};
exports.startApp = async (configFileName, additionalMockData) => {

View File

@@ -11,7 +11,7 @@ describe("Alert module", () => {
it("should show the welcome message", async () => {
const elem = await helpers.waitForElement(".ns-box .ns-box-inner .light.bright.small");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Welcome, start was successful!");
});
});

View File

@@ -2,25 +2,29 @@ const helpers = require("../helpers/global-setup");
const serverBasicAuth = require("../helpers/basic-auth");
describe("Calendar module", () => {
/**
* @param {string} element css selector
* @param {string} result expected number
* @param {string} not reverse result
* @returns {boolean} result
*/
const testElementLength = async (element, result, not) => {
const elem = await helpers.waitForAllElements(element);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
if (not === "not") {
expect(elem.length).not.toBe(result);
expect(elem).not.toHaveLength(result);
} else {
expect(elem.length).toBe(result);
expect(elem).toHaveLength(result);
}
return true;
};
const testTextContain = async (element, text) => {
const elem = await helpers.waitForElement(element, "undefinedLoading");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain(text);
return true;
};
afterAll(async () => {
@@ -34,11 +38,11 @@ describe("Calendar module", () => {
});
it("should show the default maximumEntries of 10", async () => {
await testElementLength(".calendar .event", 10);
await expect(testElementLength(".calendar .event", 10)).resolves.toBe(true);
});
it("should show the default calendar symbol in each event", async () => {
await testElementLength(".calendar .event .fa-calendar-alt", 0, "not");
await expect(testElementLength(".calendar .event .fa-calendar-alt", 0, "not")).resolves.toBe(true);
});
});
@@ -49,27 +53,27 @@ describe("Calendar module", () => {
});
it("should show the custom maximumEntries of 5", async () => {
await testElementLength(".calendar .event", 5);
await expect(testElementLength(".calendar .event", 5)).resolves.toBe(true);
});
it("should show the custom calendar symbol in four events", async () => {
await testElementLength(".calendar .event .fa-birthday-cake", 4);
await expect(testElementLength(".calendar .event .fa-birthday-cake", 4)).resolves.toBe(true);
});
it("should show a customEvent calendar symbol in one event", async () => {
await testElementLength(".calendar .event .fa-dice", 1);
await expect(testElementLength(".calendar .event .fa-dice", 1)).resolves.toBe(true);
});
it("should show a customEvent calendar eventClass in one event", async () => {
await testElementLength(".calendar .event.undo", 1);
await expect(testElementLength(".calendar .event.undo", 1)).resolves.toBe(true);
});
it("should show two custom icons for repeating events", async () => {
await testElementLength(".calendar .event .fa-undo", 2);
await expect(testElementLength(".calendar .event .fa-undo", 2)).resolves.toBe(true);
});
it("should show two custom icons for day events", async () => {
await testElementLength(".calendar .event .fa-calendar-day", 2);
await expect(testElementLength(".calendar .event .fa-calendar-day", 2)).resolves.toBe(true);
});
});
@@ -80,7 +84,7 @@ describe("Calendar module", () => {
});
it("should show the recurring birthday event 6 times", async () => {
await testElementLength(".calendar .event", 6);
await expect(testElementLength(".calendar .event", 6)).resolves.toBe(true);
});
});
@@ -91,7 +95,7 @@ describe("Calendar module", () => {
});
it("should show multiple events with the same title and start time from different calendars", async () => {
await testElementLength(".calendar .event", 22);
await expect(testElementLength(".calendar .event", 22)).resolves.toBe(true);
});
});
@@ -107,7 +111,7 @@ describe("Calendar module", () => {
});
it(`should contain text "Mar 25th" in timezone UTC ${-i}`, async () => {
await testTextContain(".calendar", "Mar 25th");
await expect(testTextContain(".calendar", "Mar 25th")).resolves.toBe(true);
});
});
}
@@ -124,7 +128,7 @@ describe("Calendar module", () => {
});
it("should return TestEvents", async () => {
await testElementLength(".calendar .event", 0, "not");
await expect(testElementLength(".calendar .event", 0, "not")).resolves.toBe(true);
});
});
@@ -135,7 +139,7 @@ describe("Calendar module", () => {
});
it("should return TestEvents", async () => {
await testElementLength(".calendar .event", 0, "not");
await expect(testElementLength(".calendar .event", 0, "not")).resolves.toBe(true);
});
});
@@ -146,7 +150,7 @@ describe("Calendar module", () => {
});
it("should return TestEvents", async () => {
await testElementLength(".calendar .event", 0, "not");
await expect(testElementLength(".calendar .event", 0, "not")).resolves.toBe(true);
});
});
@@ -157,7 +161,7 @@ describe("Calendar module", () => {
});
it("should return TestEvents", async () => {
await testElementLength(".calendar .event", 0, "not");
await expect(testElementLength(".calendar .event", 0, "not")).resolves.toBe(true);
});
});
@@ -173,7 +177,7 @@ describe("Calendar module", () => {
});
it("should show Unauthorized error", async () => {
await testTextContain(".calendar", "Error in the calendar module. Authorization failed");
await expect(testTextContain(".calendar", "Error in the calendar module. Authorization failed")).resolves.toBe(true);
});
});
});

View File

@@ -13,12 +13,12 @@ describe("Clock set to spanish language module", () => {
it("shows date with correct format", async () => {
const dateRegex = /^(?:lunes|martes|miércoles|jueves|viernes|sábado|domingo), \d{1,2} de (?:enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre) de \d{4}$/;
await helpers.testMatch(".clock .date", dateRegex);
await expect(helpers.testMatch(".clock .date", dateRegex)).resolves.toBe(true);
});
it("shows time in 24hr format", async () => {
const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -30,12 +30,12 @@ describe("Clock set to spanish language module", () => {
it("shows date with correct format", async () => {
const dateRegex = /^(?:lunes|martes|miércoles|jueves|viernes|sábado|domingo), \d{1,2} de (?:enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre) de \d{4}$/;
await helpers.testMatch(".clock .date", dateRegex);
await expect(helpers.testMatch(".clock .date", dateRegex)).resolves.toBe(true);
});
it("shows time in 12hr format", async () => {
const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[ap]m$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -47,7 +47,7 @@ describe("Clock set to spanish language module", () => {
it("shows 12hr time with upper case AM/PM", async () => {
const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[AP]M$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -59,7 +59,7 @@ describe("Clock set to spanish language module", () => {
it("shows week with correct format", async () => {
const weekRegex = /^Semana [0-9]{1,2}$/;
await helpers.testMatch(".clock .week", weekRegex);
await expect(helpers.testMatch(".clock .week", weekRegex)).resolves.toBe(true);
});
});
});

View File

@@ -14,12 +14,12 @@ describe("Clock module", () => {
it("should show the date in the correct format", async () => {
const dateRegex = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}$/;
await helpers.testMatch(".clock .date", dateRegex);
await expect(helpers.testMatch(".clock .date", dateRegex)).resolves.toBe(true);
});
it("should show the time in 24hr format", async () => {
const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -31,12 +31,12 @@ describe("Clock module", () => {
it("should show the date in the correct format", async () => {
const dateRegex = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (?:January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4}$/;
await helpers.testMatch(".clock .date", dateRegex);
await expect(helpers.testMatch(".clock .date", dateRegex)).resolves.toBe(true);
});
it("should show the time in 12hr format", async () => {
const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[ap]m$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -48,7 +48,7 @@ describe("Clock module", () => {
it("should show 12hr time with upper case AM/PM", async () => {
const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[AP]M$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -60,7 +60,7 @@ describe("Clock module", () => {
it("should show 12hr time without seconds am/pm", async () => {
const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[ap]m$/;
await helpers.testMatch(".clock .time", timeRegex);
await expect(helpers.testMatch(".clock .time", timeRegex)).resolves.toBe(true);
});
});
@@ -72,7 +72,7 @@ describe("Clock module", () => {
it("should not show the time when digital clock is shown", async () => {
const elem = document.querySelector(".clock .digital .time");
expect(elem).toBe(null);
expect(elem).toBeNull();
});
});
@@ -84,12 +84,12 @@ describe("Clock module", () => {
it("should show the sun times", async () => {
const elem = await helpers.waitForElement(".clock .digital .sun");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
});
it("should show the moon times", async () => {
const elem = await helpers.waitForElement(".clock .digital .moon");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
});
});
@@ -101,14 +101,14 @@ describe("Clock module", () => {
it("should show the week in the correct format", async () => {
const weekRegex = /^Week [0-9]{1,2}$/;
await helpers.testMatch(".clock .week", weekRegex);
await expect(helpers.testMatch(".clock .week", weekRegex)).resolves.toBe(true);
});
it("should show the week with the correct number of week of year", async () => {
const currentWeekNumber = moment().week();
const weekToShow = `Week ${currentWeekNumber}`;
const elem = await helpers.waitForElement(".clock .week");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toBe(weekToShow);
});
});
@@ -121,7 +121,7 @@ describe("Clock module", () => {
it("should show the analog clock face", async () => {
const elem = helpers.waitForElement(".clock-circle");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
});
});
@@ -133,9 +133,9 @@ describe("Clock module", () => {
it("should show the analog clock face and the date", async () => {
const elemClock = helpers.waitForElement(".clock-circle");
await expect(elemClock).not.toBe(null);
await expect(elemClock).not.toBeNull();
const elemDate = helpers.waitForElement(".clock .date");
await expect(elemDate).not.toBe(null);
await expect(elemDate).not.toBeNull();
});
});
});

View File

@@ -1,16 +1,19 @@
const helpers = require("../helpers/global-setup");
describe("Compliments module", () => {
/**
* move similar tests in function doTest
* @param {Array} complimentsArray The array of compliments.
* @returns {boolean} result
*/
const doTest = async (complimentsArray) => {
let elem = await helpers.waitForElement(".compliments");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
elem = await helpers.waitForElement(".module-content");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(complimentsArray).toContain(elem.textContent);
return true;
};
afterAll(async () => {
@@ -25,7 +28,7 @@ describe("Compliments module", () => {
});
it("shows anytime because if configure empty parts of day compliments and set anytime compliments", async () => {
await doTest(["Anytime here"]);
await expect(doTest(["Anytime here"])).resolves.toBe(true);
});
});
@@ -36,7 +39,7 @@ describe("Compliments module", () => {
});
it("shows anytime compliments", async () => {
await doTest(["Anytime here"]);
await expect(doTest(["Anytime here"])).resolves.toBe(true);
});
});
});
@@ -48,7 +51,7 @@ describe("Compliments module", () => {
});
it("should show compliments from a remote file", async () => {
await doTest(["Remote compliment file works!"]);
await expect(doTest(["Remote compliment file works!"])).resolves.toBe(true);
});
});
});

View File

@@ -13,7 +13,7 @@ describe("Test helloworld module", () => {
it("Test message helloworld module", async () => {
const elem = await helpers.waitForElement(".helloworld");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Test HelloWorld Module");
});
});
@@ -26,7 +26,7 @@ describe("Test helloworld module", () => {
it("Test message helloworld module", async () => {
const elem = await helpers.waitForElement(".helloworld");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Hello World!");
});
});

View File

@@ -13,20 +13,20 @@ describe("Newsfeed module", () => {
it("should show the newsfeed title", async () => {
const elem = await helpers.waitForElement(".newsfeed .newsfeed-source");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Rodrigo Ramirez Blog");
});
it("should show the newsfeed article", async () => {
const elem = await helpers.waitForElement(".newsfeed .newsfeed-title");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("QPanel");
});
it("should NOT show the newsfeed description", async () => {
await helpers.waitForElement(".newsfeed");
const elem = document.querySelector(".newsfeed .newsfeed-desc");
expect(elem).toBe(null);
expect(elem).toBeNull();
});
});
@@ -38,14 +38,14 @@ describe("Newsfeed module", () => {
it("should not show articles with prohibited words", async () => {
const elem = await helpers.waitForElement(".newsfeed .newsfeed-title");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Problema VirtualBox");
});
it("should show the newsfeed description", async () => {
const elem = await helpers.waitForElement(".newsfeed .newsfeed-desc");
expect(elem).not.toBe(null);
expect(elem.textContent.length).not.toBe(0);
expect(elem).not.toBeNull();
expect(elem.textContent).not.toHaveLength(0);
});
});
@@ -57,7 +57,7 @@ describe("Newsfeed module", () => {
it("should show malformed url warning", async () => {
const elem = await helpers.waitForElement(".newsfeed .small", "No news at the moment.");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("Error in the Newsfeed module. Malformed url.");
});
});
@@ -70,7 +70,7 @@ describe("Newsfeed module", () => {
it("should show empty items info message", async () => {
const elem = await helpers.waitForElement(".newsfeed .small");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("No news at the moment.");
});
});

View File

@@ -15,15 +15,15 @@ describe("Weather module", () => {
});
it("should render wind speed and wind direction", async () => {
await weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "12 WSW");
await expect(weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "12 WSW")).resolves.toBe(true);
});
it("should render temperature with icon", async () => {
await weatherFunc.getText(".weather .large.light span.bright", "1.5°");
await expect(weatherFunc.getText(".weather .large.light span.bright", "1.5°")).resolves.toBe(true);
});
it("should render feels like temperature", async () => {
await weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like -5.6°");
await expect(weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like -5.6°")).resolves.toBe(true);
});
});
});
@@ -34,7 +34,7 @@ describe("Weather module", () => {
});
it("should render a compliment based on the current weather", async () => {
await weatherFunc.getText(".compliments .module-content span", "snow");
await expect(weatherFunc.getText(".compliments .module-content span", "snow")).resolves.toBe(true);
});
});
@@ -44,25 +44,25 @@ describe("Weather module", () => {
});
it("should render windUnits in beaufort", async () => {
await weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "6");
await expect(weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "6")).resolves.toBe(true);
});
it("should render windDirection with an arrow", async () => {
const elem = await helpers.waitForElement(".weather .normal.medium sup i.fa-long-arrow-alt-down");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.outerHTML).toContain("transform:rotate(250deg)");
});
it("should render humidity", async () => {
await weatherFunc.getText(".weather .normal.medium span:nth-child(3)", "93.7");
await expect(weatherFunc.getText(".weather .normal.medium span:nth-child(3)", "93.7")).resolves.toBe(true);
});
it("should render degreeLabel for temp", async () => {
await weatherFunc.getText(".weather .large.light span.bright", "1°C");
await expect(weatherFunc.getText(".weather .large.light span.bright", "1°C")).resolves.toBe(true);
});
it("should render degreeLabel for feels like", async () => {
await weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like -6°C");
await expect(weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like -6°C")).resolves.toBe(true);
});
});
@@ -72,15 +72,15 @@ describe("Weather module", () => {
});
it("should render wind in imperial units", async () => {
await weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "26 WSW");
await expect(weatherFunc.getText(".weather .normal.medium span:nth-child(2)", "26 WSW")).resolves.toBe(true);
});
it("should render temperatures in fahrenheit", async () => {
await weatherFunc.getText(".weather .large.light span.bright", "34,7°");
await expect(weatherFunc.getText(".weather .large.light span.bright", "34,7°")).resolves.toBe(true);
});
it("should render 'feels like' in fahrenheit", async () => {
await weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like 21,9°");
await expect(weatherFunc.getText(".weather .normal.medium.feelslike span.dimmed", "Feels like 21,9°")).resolves.toBe(true);
});
});
});

View File

@@ -16,7 +16,7 @@ describe("Weather module: Weather Forecast", () => {
const days = ["Today", "Tomorrow", "Sun", "Mon", "Tue"];
for (const [index, day] of days.entries()) {
it(`should render day ${day}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day)).resolves.toBe(true);
});
}
@@ -24,21 +24,21 @@ describe("Weather module: Weather Forecast", () => {
for (const [index, icon] of icons.entries()) {
it(`should render icon ${icon}`, async () => {
const elem = await helpers.waitForElement(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(2) span.wi-${icon}`);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
});
}
const maxTemps = ["24.4°", "21.0°", "22.9°", "23.4°", "20.6°"];
for (const [index, temp] of maxTemps.entries()) {
it(`should render max temperature ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp)).resolves.toBe(true);
});
}
const minTemps = ["15.3°", "13.6°", "13.8°", "13.9°", "10.9°"];
for (const [index, temp] of minTemps.entries()) {
it(`should render min temperature ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(4)`, temp);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(4)`, temp)).resolves.toBe(true);
});
}
@@ -46,7 +46,7 @@ describe("Weather module: Weather Forecast", () => {
for (const [index, opacity] of opacities.entries()) {
it(`should render fading of rows with opacity=${opacity}`, async () => {
const elem = await helpers.waitForElement(`.weather table.small tr:nth-child(${index + 1})`);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.outerHTML).toContain(`<tr style="opacity: ${opacity};">`);
});
}
@@ -60,7 +60,7 @@ describe("Weather module: Weather Forecast", () => {
const days = ["Fri", "Sat", "Sun", "Mon", "Tue"];
for (const [index, day] of days.entries()) {
it(`should render day ${day}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(1)`, day)).resolves.toBe(true);
});
}
});
@@ -72,21 +72,21 @@ describe("Weather module: Weather Forecast", () => {
it("should render custom table class", async () => {
const elem = await helpers.waitForElement(".weather table.myTableClass");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
});
it("should render colored rows", async () => {
const table = await helpers.waitForElement(".weather table.myTableClass");
expect(table).not.toBe(null);
expect(table.rows).not.toBe(null);
expect(table.rows.length).toBe(5);
expect(table).not.toBeNull();
expect(table.rows).not.toBeNull();
expect(table.rows).toHaveLength(5);
});
const precipitations = [undefined, "2.51 mm"];
for (const [index, precipitation] of precipitations.entries()) {
if (precipitation) {
it(`should render precipitation amount ${precipitation}`, async () => {
await weatherFunc.getText(`.weather table tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation);
await expect(weatherFunc.getText(`.weather table tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation)).resolves.toBe(true);
});
}
}
@@ -101,7 +101,7 @@ describe("Weather module: Weather Forecast", () => {
const temperatures = ["75_9°", "69_8°", "73_2°", "74_1°", "69_1°"];
for (const [index, temp] of temperatures.entries()) {
it(`should render custom decimalSymbol = '_' for temp ${temp}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td:nth-child(3)`, temp)).resolves.toBe(true);
});
}
});
@@ -111,7 +111,7 @@ describe("Weather module: Weather Forecast", () => {
for (const [index, precipitation] of precipitations.entries()) {
if (precipitation) {
it(`should render precipitation amount ${precipitation}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-amount`, precipitation)).resolves.toBe(true);
});
}
}

View File

@@ -16,7 +16,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
const minTemps = ["7:00 pm", "8:00 pm", "9:00 pm", "10:00 pm", "11:00 pm"];
for (const [index, hour] of minTemps.entries()) {
it(`should render forecast for hour ${hour}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.day`, hour);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.day`, hour)).resolves.toBe(true);
});
}
});
@@ -30,7 +30,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
const minTemps = ["7:00 pm", "9:00 pm", "11:00 pm", "1:00 am", "3:00 am"];
for (const [index, hour] of minTemps.entries()) {
it(`should render forecast for hour ${hour}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.day`, hour);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.day`, hour)).resolves.toBe(true);
});
}
});
@@ -46,7 +46,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
for (const [index, amount] of amounts.entries()) {
if (amount) {
it(`should render precipitation amount ${amount}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-amount`, amount);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-amount`, amount)).resolves.toBe(true);
});
}
}
@@ -57,7 +57,7 @@ describe("Weather module: Weather Hourly Forecast", () => {
for (const [index, pop] of propabilities.entries()) {
if (pop) {
it(`should render probability ${pop}`, async () => {
await weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-prob`, pop);
await expect(weatherFunc.getText(`.weather table.small tr:nth-child(${index + 1}) td.precipitation-prob`, pop)).resolves.toBe(true);
});
}
}

View File

@@ -11,14 +11,14 @@ describe("Display of modules", () => {
it("should show the test header", async () => {
const elem = await helpers.waitForElement("#module_0_helloworld .module-header");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
// textContent gibt hier lowercase zurück, das uppercase wird durch css realisiert, was daher nicht in textContent landet
expect(elem.textContent).toBe("test_header");
});
it("should show no header if no header text is specified", async () => {
const elem = await helpers.waitForElement("#module_1_helloworld .module-header");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toBe("undefined");
});
});

View File

@@ -11,13 +11,13 @@ describe("Check configuration without modules", () => {
it("shows the message MagicMirror² title", async () => {
const elem = await helpers.waitForElement("#module_1_helloworld .module-content");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("MagicMirror²");
});
it("shows the url of michael's website", async () => {
const elem = await helpers.waitForElement("#module_5_helloworld .module-content");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain("www.michaelteeuw.nl");
});
});

View File

@@ -15,7 +15,7 @@ describe("Position of modules", () => {
const className = position.replace("_", ".");
it(`should show text in ${position}`, async () => {
const elem = await helpers.waitForElement(`.${className}`);
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(elem.textContent).toContain(`Text in ${position}`);
});
}

View File

@@ -1,5 +1,3 @@
const helpers = require("./helpers/global-setup");
const delay = (time) => {
return new Promise((resolve) => setTimeout(resolve, time));
};

View File

@@ -44,7 +44,8 @@ describe("Translations", () => {
);
});
it("should load translation file", (done) => {
it("should load translation file", () => {
return new Promise((done) => {
dom.window.onload = async () => {
const { Translator, Module, config } = dom.window;
config.language = "en";
@@ -55,14 +56,16 @@ describe("Translations", () => {
await MMM.loadTranslations();
expect(Translator.load.args.length).toBe(1);
expect(Translator.load.args).toHaveLength(1);
expect(Translator.load.calledWith(MMM, "translations/en.json", false)).toBe(true);
done();
};
});
});
it("should load translation + fallback file", (done) => {
it("should load translation + fallback file", () => {
return new Promise((done) => {
dom.window.onload = async () => {
const { Translator, Module } = dom.window;
Translator.load = sinon.stub().callsFake((_m, _f, _fb) => null);
@@ -72,15 +75,17 @@ describe("Translations", () => {
await MMM.loadTranslations();
expect(Translator.load.args.length).toBe(2);
expect(Translator.load.args).toHaveLength(2);
expect(Translator.load.calledWith(MMM, "translations/de.json", false)).toBe(true);
expect(Translator.load.calledWith(MMM, "translations/en.json", true)).toBe(true);
done();
};
});
});
it("should load translation fallback file", (done) => {
it("should load translation fallback file", () => {
return new Promise((done) => {
dom.window.onload = async () => {
const { Translator, Module, config } = dom.window;
config.language = "--";
@@ -91,14 +96,16 @@ describe("Translations", () => {
await MMM.loadTranslations();
expect(Translator.load.args.length).toBe(1);
expect(Translator.load.args).toHaveLength(1);
expect(Translator.load.calledWith(MMM, "translations/en.json", true)).toBe(true);
done();
};
});
});
it("should load no file", (done) => {
it("should load no file", () => {
return new Promise((done) => {
dom.window.onload = async () => {
const { Translator, Module } = dom.window;
Translator.load = sinon.stub();
@@ -114,6 +121,7 @@ describe("Translations", () => {
};
});
});
});
const mmm = {
name: "TranslationTest",
@@ -124,7 +132,8 @@ describe("Translations", () => {
describe("Parsing language files through the Translator class", () => {
for (let language in translations) {
it(`should parse ${language}`, (done) => {
it(`should parse ${language}`, () => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = ${JSON.stringify(translations)}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "js", "translator.js")}">`,
@@ -139,6 +148,7 @@ describe("Translations", () => {
done();
};
});
});
}
});
@@ -146,7 +156,8 @@ describe("Translations", () => {
let base;
let missing = [];
beforeAll((done) => {
beforeAll(() => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = ${JSON.stringify(translations)}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "js", "translator.js")}">`,
@@ -160,6 +171,7 @@ describe("Translations", () => {
done();
};
});
});
afterAll(() => {
console.log(missing);
@@ -175,7 +187,8 @@ describe("Translations", () => {
describe(`Translation keys of ${language}`, () => {
let keys;
beforeAll((done) => {
beforeAll(() => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = ${JSON.stringify(translations)}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "js", "translator.js")}">`,
@@ -189,6 +202,7 @@ describe("Translations", () => {
done();
};
});
});
it(`${language} keys should be in base`, () => {
keys.forEach((key) => {

View File

@@ -12,8 +12,8 @@ describe("Electron app environment", () => {
it("should open browserwindow", async () => {
const module = await helpers.getElement("#module_0_helloworld");
expect(await module.textContent()).toContain("Test Display Header");
expect(global.electronApp.windows().length).toBe(1);
await expect(module.textContent()).resolves.toContain("Test Display Header");
expect(global.electronApp.windows()).toHaveLength(1);
});
});
@@ -29,7 +29,7 @@ describe("Development console tests", () => {
it("should open browserwindow and dev console", async () => {
while (global.electronApp.windows().length < 2) await events.once(global.electronApp, "window");
const pageArray = await global.electronApp.windows();
expect(pageArray.length).toBe(2);
expect(pageArray).toHaveLength(2);
for (const page of pageArray) {
expect(["MagicMirror²", "DevTools"]).toContain(await page.title());
}

View File

@@ -37,9 +37,9 @@ exports.stopApplication = async () => {
};
exports.getElement = async (selector) => {
expect(global.page);
expect(global.page).not.toBeNull();
let elem = global.page.locator(selector);
await elem.waitFor();
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
return elem;
};

View File

@@ -3,7 +3,7 @@ const helpers = require("./global-setup");
exports.getText = async (element, result) => {
const elem = await helpers.getElement(element);
await expect(elem).not.toBe(null);
await expect(elem).not.toBeNull();
const text = await elem.textContent();
await expect(
text
@@ -11,6 +11,7 @@ exports.getText = async (element, result) => {
.replace(/(\r\n|\n|\r)/gm, "")
.replace(/[ ]+/g, " ")
).toBe(result);
return true;
};
exports.startApp = async (configFileName, systemDate) => {

View File

@@ -1,13 +1,16 @@
const helpers = require("../helpers/global-setup");
describe("Calendar module", () => {
/**
* move similar tests in function doTest
* @param {string} cssClass css selector
* @returns {boolean} result
*/
const doTest = async (cssClass) => {
let elem = await helpers.getElement(`.calendar .module-content .event${cssClass}`);
expect(await elem.isVisible()).toBe(true);
const elem = await helpers.getElement(`.calendar .module-content .event${cssClass}`);
await expect(elem.isVisible()).resolves.toBe(true);
return true;
};
afterEach(async () => {
@@ -17,27 +20,41 @@ describe("Calendar module", () => {
describe("Test css classes", () => {
it("has css class dayBeforeYesterday", async () => {
await helpers.startApplication("tests/configs/modules/calendar/custom.js", "03 Jan 2030 12:30:00 GMT");
await doTest(".dayBeforeYesterday");
await expect(doTest(".dayBeforeYesterday")).resolves.toBe(true);
});
it("has css class yesterday", async () => {
await helpers.startApplication("tests/configs/modules/calendar/custom.js", "02 Jan 2030 12:30:00 GMT");
await doTest(".yesterday");
await expect(doTest(".yesterday")).resolves.toBe(true);
});
it("has css class today", async () => {
await helpers.startApplication("tests/configs/modules/calendar/custom.js", "01 Jan 2030 12:30:00 GMT");
await doTest(".today");
await expect(doTest(".today")).resolves.toBe(true);
});
it("has css class tomorrow", async () => {
await helpers.startApplication("tests/configs/modules/calendar/custom.js", "31 Dec 2029 12:30:00 GMT");
await doTest(".tomorrow");
await expect(doTest(".tomorrow")).resolves.toBe(true);
});
it("has css class dayAfterTomorrow", async () => {
await helpers.startApplication("tests/configs/modules/calendar/custom.js", "30 Dec 2029 12:30:00 GMT");
await doTest(".dayAfterTomorrow");
await expect(doTest(".dayAfterTomorrow")).resolves.toBe(true);
});
});
describe("Exdate check", () => {
it("should show the recurring event 51 times (excluded once) in a 364-day (inclusive) period", async () => {
// test must run on a Thursday
await helpers.startApplication("tests/configs/modules/calendar/exdate.js", "14 Dec 2023 12:30:00 GMT");
expect(global.page).not.toBeNull();
const loc = await global.page.locator(".calendar .event");
const elem = loc.first();
await elem.waitFor();
expect(elem).not.toBeNull();
const cnt = await loc.count();
expect(cnt).toBe(51);
});
});
});

View File

@@ -1,15 +1,18 @@
const helpers = require("../helpers/global-setup");
describe("Compliments module", () => {
/**
* move similar tests in function doTest
* @param {Array} complimentsArray The array of compliments.
* @returns {boolean} result
*/
const doTest = async (complimentsArray) => {
await helpers.getElement(".compliments");
const elem = await helpers.getElement(".module-content");
expect(elem).not.toBe(null);
expect(elem).not.toBeNull();
expect(complimentsArray).toContain(await elem.textContent());
return true;
};
afterEach(async () => {
@@ -19,17 +22,17 @@ describe("Compliments module", () => {
describe("parts of days", () => {
it("Morning compliments for that part of day", async () => {
await helpers.startApplication("tests/configs/modules/compliments/compliments_parts_day.js", "01 Oct 2022 10:00:00 GMT");
await doTest(["Hi", "Good Morning", "Morning test"]);
await expect(doTest(["Hi", "Good Morning", "Morning test"])).resolves.toBe(true);
});
it("Afternoon show Compliments for that part of day", async () => {
await helpers.startApplication("tests/configs/modules/compliments/compliments_parts_day.js", "01 Oct 2022 15:00:00 GMT");
await doTest(["Hello", "Good Afternoon", "Afternoon test"]);
await expect(doTest(["Hello", "Good Afternoon", "Afternoon test"])).resolves.toBe(true);
});
it("Evening show Compliments for that part of day", async () => {
await helpers.startApplication("tests/configs/modules/compliments/compliments_parts_day.js", "01 Oct 2022 20:00:00 GMT");
await doTest(["Hello There", "Good Evening", "Evening test"]);
await expect(doTest(["Hello There", "Good Evening", "Evening test"])).resolves.toBe(true);
});
});
@@ -37,7 +40,7 @@ describe("Compliments module", () => {
describe("Set date and empty compliments for anytime, morning, evening and afternoon", () => {
it("shows happy new year compliment on new years day", async () => {
await helpers.startApplication("tests/configs/modules/compliments/compliments_date.js", "01 Jan 2022 10:00:00 GMT");
await doTest(["Happy new year!"]);
await expect(doTest(["Happy new year!"])).resolves.toBe(true);
});
});
});

View File

@@ -14,7 +14,7 @@ describe("Weather module", () => {
});
it("should render sunrise", async () => {
await weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "7:00 am");
await expect(weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "7:00 am")).resolves.toBe(true);
});
});
@@ -24,7 +24,7 @@ describe("Weather module", () => {
});
it("should render sunset", async () => {
await weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "3:45 pm");
await expect(weatherHelper.getText(".weather .normal.medium span:nth-child(4)", "3:45 pm")).resolves.toBe(true);
});
});
});

20
tests/mocks/bad_rrule.ics Normal file
View File

@@ -0,0 +1,20 @@
BEGIN:VCALENDAR
BEGIN:VEVENT
DTSTAMP:20210413T203456Z
UID:E689AEB8C02C4E2CADD8C7D3D303CEAD0
DTSTART;TZID="Amsterdam, Belgrade, Berlin, Brussels, Budapest, Madrid, Paris, Prague, Stockholm":20210415T190000
DTEND;TZID="Amsterdam, Belgrade, Berlin, Brussels, Budapest, Madrid, Paris, Prague, Stockholm":20210415T210000
CLASS:PUBLIC
LOCATION:albert heijn
SUMMARY:xxx xxxx
SEQUENCE:10
RRULE:FREQ=DAILY;UNTIL=20210418T170000Z
EXDATE;TZID="Amsterdam, Belgrade, Berlin, Brussels, Budapest, Madrid, Paris, Prague, Stockholm":20210417T190000
EXDATE;TZID="Amsterdam, Belgrade, Berlin, Brussels, Budapest, Madrid, Paris, Prague, Stockholm":20210416T190000
EXDATE;TZID="Amsterdam, Belgrade, Berlin, Brussels, Budapest, Madrid, Paris, Prague, Stockholm":20210415T190000
BEGIN:VALARM
ACTION:DISPLAY
TRIGGER;RELATED=START:-PT15M
END:VALARM
END:VEVENT
END:VCALENDAR

View File

@@ -0,0 +1,34 @@
BEGIN:VEVENT
DTSTART;TZID=UTC:20231025T181000
DTEND;TZID=UTC:20231025T195000
RRULE:FREQ=WEEKLY;BYDAY=WE
EXDATE;TZID=UTC:20231101T181000
EXDATE;TZID=UTC:20241030T181000
EXDATE;TZID=UTC:20251029T181000
EXDATE;TZID=UTC:20261028T181000
EXDATE;TZID=UTC:20271027T181000
EXDATE;TZID=UTC:20281025T181000
EXDATE;TZID=UTC:20291024T181000
EXDATE;TZID=UTC:20301023T181000
EXDATE;TZID=UTC:20311022T181000
EXDATE;TZID=UTC:20321020T181000
EXDATE;TZID=UTC:20331019T181000
EXDATE;TZID=UTC:20341018T181000
EXDATE;TZID=UTC:20351017T181000
EXDATE;TZID=UTC:20361015T181000
EXDATE;TZID=UTC:20371014T181000
EXDATE;TZID=UTC:20381013T181000
EXDATE;TZID=UTC:20391012T181000
EXDATE;TZID=UTC:20401010T181000
EXDATE;TZID=UTC:20411009T181000
EXDATE;TZID=UTC:20421008T181000
EXDATE;TZID=UTC:20431007T181000
DTSTAMP:20231025T233434Z
UID:sdflbkasuhdb5fkauglkb@google.com
CREATED:20230306T193128Z
LAST-MODIFIED:20231024T222515Z
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:My Event
TRANSP:OPAQUE
END:VEVENT

View File

@@ -6,7 +6,8 @@ describe("File js/class", () => {
let clone;
let dom;
beforeAll((done) => {
beforeAll(() => {
return new Promise((done) => {
dom = new JSDOM(
`<script>var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "class.js")}">`,
@@ -18,6 +19,7 @@ describe("File js/class", () => {
done();
};
});
});
it("should clone object", () => {
const expected = { name: "Rodrigo", web: "https://rodrigoramirez.com", project: "MagicMirror" };
@@ -49,6 +51,13 @@ describe("File js/class", () => {
expect(obj).toBe(expected);
});
it("should clone regex", () => {
const expected = /.*Magic/;
const obj = clone(expected);
expect(obj).toEqual(expected);
expect(expected === obj).toBe(false);
});
it("should clone undefined", () => {
const expected = undefined;
const obj = clone(expected);

View File

@@ -77,7 +77,8 @@ describe("Translator", () => {
Translator.coreTranslationsFallback = coreTranslationsFallback;
};
it("should return custom module translation", (done) => {
it("should return custom module translation", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -89,8 +90,10 @@ describe("Translator", () => {
done();
};
});
});
it("should return core translation", (done) => {
it("should return core translation", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -102,8 +105,10 @@ describe("Translator", () => {
done();
};
});
});
it("should return custom module translation fallback", (done) => {
it("should return custom module translation fallback", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -113,8 +118,10 @@ describe("Translator", () => {
done();
};
});
});
it("should return core translation fallback", (done) => {
it("should return core translation fallback", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -124,8 +131,10 @@ describe("Translator", () => {
done();
};
});
});
it("should return translation with placeholder for missing variables", (done) => {
it("should return translation with placeholder for missing variables", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -135,8 +144,10 @@ describe("Translator", () => {
done();
};
});
});
it("should return key if no translation was found", (done) => {
it("should return key if no translation was found", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = () => {
const { Translator } = dom.window;
@@ -147,6 +158,7 @@ describe("Translator", () => {
};
});
});
});
describe("load", () => {
const mmm = {
@@ -156,7 +168,8 @@ describe("Translator", () => {
}
};
it("should load translations", (done) => {
it("should load translations", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = async () => {
const { Translator } = dom.window;
@@ -168,8 +181,10 @@ describe("Translator", () => {
done();
};
});
});
it("should load translation fallbacks", (done) => {
it("should load translation fallbacks", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = async () => {
const { Translator } = dom.window;
@@ -181,8 +196,10 @@ describe("Translator", () => {
done();
};
});
});
it("should not load translations, if module fallback exists", (done) => {
it("should not load translations, if module fallback exists", () => {
return new Promise((done) => {
const dom = new JSDOM(`<script>var Log = {log: () => {}};</script><script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`, { runScripts: "dangerously", resources: "usable" });
dom.window.onload = async () => {
const { Translator, XMLHttpRequest } = dom.window;
@@ -197,7 +214,7 @@ describe("Translator", () => {
};
await Translator.load(mmm, file, false);
expect(Translator.translations[mmm.name]).toBe(undefined);
expect(Translator.translations[mmm.name]).toBeUndefined();
expect(Translator.translationsFallback[mmm.name]).toEqual({
Hello: "Hallo"
});
@@ -205,9 +222,11 @@ describe("Translator", () => {
};
});
});
});
describe("loadCoreTranslations", () => {
it("should load core translations and fallback", (done) => {
it("should load core translations and fallback", () => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
@@ -225,8 +244,10 @@ describe("Translator", () => {
}, 500);
};
});
});
it("should load core fallback if language cannot be found", (done) => {
it("should load core fallback if language cannot be found", () => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
@@ -245,9 +266,11 @@ describe("Translator", () => {
};
});
});
});
describe("loadCoreTranslationsFallback", () => {
it("should load core translations fallback", (done) => {
it("should load core translations fallback", () => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = {en: "http://localhost:3000/translations/translation_test.json"}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
@@ -264,8 +287,10 @@ describe("Translator", () => {
}, 500);
};
});
});
it("should load core fallback if language cannot be found", (done) => {
it("should load core fallback if language cannot be found", () => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var translations = {}; var Log = {log: () => {}};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "translator.js")}">`,
@@ -283,3 +308,4 @@ describe("Translator", () => {
});
});
});
});

View File

@@ -4,7 +4,8 @@ const { JSDOM } = require("jsdom");
describe("Test function cmpVersions in js/module.js", () => {
let cmp;
beforeAll((done) => {
beforeAll(() => {
return new Promise((done) => {
const dom = new JSDOM(
`<script>var Class = {extend: () => { return {}; }};</script>\
<script src="file://${path.join(__dirname, "..", "..", "..", "js", "module.js")}">`,
@@ -16,6 +17,7 @@ describe("Test function cmpVersions in js/module.js", () => {
done();
};
});
});
it("should return -1 when comparing 2.1 to 2.2", () => {
expect(cmp("2.1", "2.2")).toBe(-1);

View File

@@ -31,47 +31,47 @@ describe("server_functions tests", () => {
};
request = {
url: `/cors?url=www.test.com`
url: "/cors?url=www.test.com"
};
});
test("Calls correct URL once", async () => {
it("Calls correct URL once", async () => {
const urlToCall = "http://www.test.com/path?param1=value1";
request.url = `/cors?url=${urlToCall}`;
await cors(request, corsResponse);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toBe(urlToCall);
});
test("Forewards Content-Type if json", async () => {
it("Forewards Content-Type if json", async () => {
fetchResponseHeadersGet.mockImplementation(() => "json");
await cors(request, corsResponse);
expect(fetchResponseHeadersGet.mock.calls.length).toBe(1);
expect(fetchResponseHeadersGet.mock.calls).toHaveLength(1);
expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type");
expect(corsResponse.set.mock.calls.length).toBe(1);
expect(corsResponse.set.mock.calls).toHaveLength(1);
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
expect(corsResponse.set.mock.calls[0][1]).toBe("json");
});
test("Forewards Content-Type if xml", async () => {
it("Forewards Content-Type if xml", async () => {
fetchResponseHeadersGet.mockImplementation(() => "xml");
await cors(request, corsResponse);
expect(fetchResponseHeadersGet.mock.calls.length).toBe(1);
expect(fetchResponseHeadersGet.mock.calls).toHaveLength(1);
expect(fetchResponseHeadersGet.mock.calls[0][0]).toBe("Content-Type");
expect(corsResponse.set.mock.calls.length).toBe(1);
expect(corsResponse.set.mock.calls).toHaveLength(1);
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
expect(corsResponse.set.mock.calls[0][1]).toBe("xml");
});
test("Sends correct data from response", async () => {
it("Sends correct data from response", async () => {
const responseData = "some data";
fetchResponseHeadersText.mockImplementation(() => responseData);
@@ -82,11 +82,11 @@ describe("server_functions tests", () => {
await cors(request, corsResponse);
expect(fetchResponseHeadersText.mock.calls.length).toBe(1);
expect(fetchResponseHeadersText.mock.calls).toHaveLength(1);
expect(sentData).toBe(responseData);
});
test("Sends error data from response", async () => {
it("Sends error data from response", async () => {
const error = new Error("error data");
fetchResponseHeadersText.mockImplementation(() => {
throw error;
@@ -99,32 +99,32 @@ describe("server_functions tests", () => {
await cors(request, corsResponse);
expect(fetchResponseHeadersText.mock.calls.length).toBe(1);
expect(fetchResponseHeadersText.mock.calls).toHaveLength(1);
expect(sentData).toBe(error);
});
test("Fetches with user agent by default", async () => {
it("Fetches with user agent by default", async () => {
await cors(request, corsResponse);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("User-Agent");
});
test("Fetches with specified headers", async () => {
it("Fetches with specified headers", async () => {
const headersParam = "sendheaders=header1:value1,header2:value2";
const urlParam = "http://www.test.com/path?param1=value1";
request.url = `/cors?${headersParam}&url=${urlParam}`;
await cors(request, corsResponse);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header1", "value1");
expect(fetchMock.mock.calls[0][1].headers).toHaveProperty("header2", "value2");
});
test("Sends specified headers", async () => {
it("Sends specified headers", async () => {
fetchResponseHeadersGet.mockImplementation((input) => input.replace("header", "value"));
const expectedheaders = "expectedheaders=header1,header2";
@@ -133,9 +133,9 @@ describe("server_functions tests", () => {
await cors(request, corsResponse);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][1]).toHaveProperty("headers");
expect(corsResponse.set.mock.calls.length).toBe(3);
expect(corsResponse.set.mock.calls).toHaveLength(3);
expect(corsResponse.set.mock.calls[0][0]).toBe("Content-Type");
expect(corsResponse.set.mock.calls[1][0]).toBe("header1");
expect(corsResponse.set.mock.calls[1][1]).toBe("value1");

View File

@@ -32,7 +32,7 @@ describe("Updatenotification", () => {
const { promisify } = require("util");
promisify.mockReturnValue(execMock);
const GitHelper = require(`../../../modules/default/updatenotification/git_helper`);
const GitHelper = require("../../../modules/default/updatenotification/git_helper");
gitHelper = new GitHelper();
});
@@ -103,7 +103,7 @@ describe("Updatenotification", () => {
execMock.mockRejectedValueOnce(errorMessage);
const repos = await gitHelper.getRepos();
expect(repos.length).toBe(0);
expect(repos).toHaveLength(0);
const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
@@ -142,7 +142,7 @@ describe("Updatenotification", () => {
execMock.mockRejectedValueOnce(errorMessage);
const repos = await gitHelper.getRepos();
expect(repos.length).toBe(0);
expect(repos).toHaveLength(0);
const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
@@ -183,7 +183,7 @@ describe("Updatenotification", () => {
execMock.mockRejectedValueOnce(errorMessage);
const repos = await gitHelper.getRepos();
expect(repos.length).toBe(0);
expect(repos).toHaveLength(0);
const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);
@@ -224,7 +224,7 @@ describe("Updatenotification", () => {
execMock.mockRejectedValueOnce(errorMessage);
const repos = await gitHelper.getRepos();
expect(repos.length).toBe(0);
expect(repos).toHaveLength(0);
const { error } = require("logger");
expect(error).toHaveBeenCalledWith(`Failed to retrieve repo info for ${moduleName}: Failed to retrieve status`);

View File

@@ -14,11 +14,11 @@ describe("'global.root_path' set in js/app.js", () => {
});
it("should not modify global.root_path for testing", () => {
expect(global.root_path).toBe(undefined);
expect(global.root_path).toBeUndefined();
});
it("should not modify global.version for testing", () => {
expect(global.version).toBe(undefined);
expect(global.version).toBeUndefined();
});
it("should expect the global.version equals package.json file", () => {

View File

@@ -1,3 +1,3 @@
module.exports = async () => {
process.env.TZ = "Europe/Berlin";
process.env.TZ = "UTC";
};

View File

@@ -0,0 +1,29 @@
global.moment = require("moment-timezone");
const CalendarFetcherUtils = require("../../../../../modules/default/calendar/calendarfetcherutils");
describe("Calendar fetcher utils test", () => {
const defaultConfig = {
excludedEvents: []
};
describe("filterEvents", () => {
it("no events, not crash", () => {
const minusOneHour = moment().subtract(1, "hours").toDate();
const minusTwoHours = moment().subtract(2, "hours").toDate();
const plusOneHour = moment().add(1, "hours").toDate();
const plusTwoHours = moment().add(2, "hours").toDate();
const filteredEvents = CalendarFetcherUtils.filterEvents(
{
pastEvent: { type: "VEVENT", start: minusTwoHours, end: minusOneHour, summary: "pastEvent" },
ongoingEvent: { type: "VEVENT", start: minusOneHour, end: plusOneHour, summary: "ongoingEvent" },
upcomingEvent: { type: "VEVENT", start: plusOneHour, end: plusTwoHours, summary: "upcomingEvent" }
},
defaultConfig
);
expect(filteredEvents).toHaveLength(0);
});
});
});

View File

@@ -26,7 +26,7 @@ describe("Calendar fetcher utils test", () => {
defaultConfig
);
expect(filteredEvents.length).toEqual(2);
expect(filteredEvents).toHaveLength(2);
expect(filteredEvents[0].title).toBe("ongoingEvent");
expect(filteredEvents[1].title).toBe("upcomingEvent");
});
@@ -45,7 +45,7 @@ describe("Calendar fetcher utils test", () => {
defaultConfig
);
expect(filteredEvents.length).toEqual(2);
expect(filteredEvents).toHaveLength(2);
expect(filteredEvents[0].title).toBe("ongoingEvent");
expect(filteredEvents[1].title).toBe("upcomingEvent");
});

View File

@@ -138,11 +138,16 @@ describe("Calendar utils tests", () => {
describe("titleTransform and shorten combined", () => {
it("should replace the birthday and wrap nicely", () => {
const transformedTitle = CalendarUtils.titleTransform("Michael Teeuw's birthday", {
"De verjaardag van ": "",
"'s birthday": ""
});
const transformedTitle = CalendarUtils.titleTransform("Michael Teeuw's birthday", [{ search: "'s birthday", replace: "" }]);
expect(CalendarUtils.shorten(transformedTitle, 10, true, 2)).toBe("Michael <br>Teeuw");
});
});
describe("titleTransform with yearmatchgroup", () => {
it("should replace the birthday and wrap nicely", () => {
const transformedTitle = CalendarUtils.titleTransform("Luciella '2000", [{ search: "^([^']*) '(\\d{4})$", replace: "$1 ($2.)", yearmatchgroup: 2 }]);
const expectedResult = `Luciella (${new Date().getFullYear() - 2000}.)`;
expect(transformedTitle).toBe(expectedResult);
});
});
});

View File

@@ -24,16 +24,16 @@ describe("Default modules utils tests", () => {
}
});
test("Calls correct URL once", async () => {
it("Calls correct URL once", async () => {
urlToCall = "http://www.test.com/path?param1=value1";
await performWebRequest(urlToCall, "json", true);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toBe(`${locationProtocol}//${locationHost}/cors?url=${urlToCall}`);
});
test("Sends correct headers", async () => {
it("Sends correct headers", async () => {
urlToCall = "http://www.test.com/path?param1=value1";
const headers = [
@@ -43,22 +43,22 @@ describe("Default modules utils tests", () => {
await performWebRequest(urlToCall, "json", true, headers);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toBe(`${locationProtocol}//${locationHost}/cors?sendheaders=header1:value1,header2:value2&url=${urlToCall}`);
});
});
describe("When not using cors proxy", () => {
test("Calls correct URL once", async () => {
it("Calls correct URL once", async () => {
urlToCall = "http://www.test.com/path?param1=value1";
await performWebRequest(urlToCall);
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toBe(urlToCall);
});
test("Sends correct headers", async () => {
it("Sends correct headers", async () => {
urlToCall = "http://www.test.com/path?param1=value1";
const headers = [
{ name: "header1", value: "value1" },
@@ -68,36 +68,36 @@ describe("Default modules utils tests", () => {
await performWebRequest(urlToCall, "json", false, headers);
const expectedHeaders = { headers: { header1: "value1", header2: "value2" } };
expect(fetchMock.mock.calls.length).toBe(1);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][1]).toStrictEqual(expectedHeaders);
});
});
describe("When receiving json format", () => {
test("Returns undefined when no data is received", async () => {
it("Returns undefined when no data is received", async () => {
urlToCall = "www.test.com";
const response = await performWebRequest(urlToCall);
expect(response).toBe(undefined);
expect(response).toBeUndefined();
});
test("Returns object when data is received", async () => {
it("Returns object when data is received", async () => {
urlToCall = "www.test.com";
fetchResponse = new Response('{"body": "some content"}');
fetchResponse = new Response("{\"body\": \"some content\"}");
const response = await performWebRequest(urlToCall);
expect(response.body).toBe("some content");
});
test("Returns expected headers when data is received", async () => {
it("Returns expected headers when data is received", async () => {
urlToCall = "www.test.com";
fetchResponse = new Response('{"body": "some content"}', { headers: { header1: "value1", header2: "value2" } });
fetchResponse = new Response("{\"body\": \"some content\"}", { headers: { header1: "value1", header2: "value2" } });
const response = await performWebRequest(urlToCall, "json", false, undefined, ["header1"]);
expect(response.headers.length).toBe(1);
expect(response.headers).toHaveLength(1);
expect(response.headers[0].name).toBe("header1");
expect(response.headers[0].value).toBe("value1");
});
@@ -150,17 +150,5 @@ describe("Default modules utils tests", () => {
)
).toBe("1:13");
});
it("should convert correctly into another timezone", () => {
expect(
formatTime(
{
timeFormat: 24,
timezone: "America/Toronto"
},
time
)
).toBe("07:13");
});
});
});

View File

@@ -2,7 +2,13 @@ const weather = require("../../../../../modules/default/weather/weatherutils");
const WeatherUtils = require("../../../../../modules/default/weather/weatherutils");
describe("Weather utils tests", () => {
describe("windspeed conversion", () => {
describe("windspeed conversion to imperial", () => {
it("should convert temp correctly from Celsius to Fahrenheit", () => {
expect(Math.round(WeatherUtils.convertTemp(10, "imperial"))).toBe(50);
});
});
describe("windspeed conversion to beaufort", () => {
it("should convert windspeed correctly from mps to beaufort", () => {
expect(Math.round(WeatherUtils.convertWind(5, "beaufort"))).toBe(3);
expect(Math.round(WeatherUtils.convertWind(300, "beaufort"))).toBe(12);
@@ -32,15 +38,16 @@ describe("Weather utils tests", () => {
describe("wind direction conversion", () => {
it("should convert wind direction correctly from cardinal to value", () => {
expect(WeatherUtils.convertWindDirection("SSE")).toBe(157);
expect(WeatherUtils.convertWindDirection("XXX")).toBeNull();
});
});
describe("feelsLike calculation", () => {
it("should return a calculated feelsLike info", () => {
it("should return a calculated feelsLike info (negative value)", () => {
expect(WeatherUtils.calculateFeelsLike(0, 20, 40)).toBe(-9.444444444444445);
});
it("should return a calculated feelsLike info", () => {
it("should return a calculated feelsLike info (positiv value)", () => {
expect(WeatherUtils.calculateFeelsLike(30, 0, 60)).toBe(32.8320322777777);
});
});

View File

@@ -43,5 +43,8 @@
"UPDATE_NOTIFICATION": "Aktualisierung für MagicMirror² verfügbar.",
"UPDATE_NOTIFICATION_MODULE": "Aktualisierung für das Modul „{MODULE_NAME}“ verfügbar.",
"UPDATE_INFO_SINGLE": "Die aktuelle Installation ist ein Commit hinter dem {BRANCH_NAME}-Branch.",
"UPDATE_INFO_MULTIPLE": "Die aktuelle Installation ist {COMMIT_COUNT} Commits hinter dem {BRANCH_NAME}-Branch."
"UPDATE_INFO_MULTIPLE": "Die aktuelle Installation ist {COMMIT_COUNT} Commits hinter dem {BRANCH_NAME}-Branch.",
"UPDATE_NOTIFICATION_DONE": "Aktualisierung für das Modul {MODULE_NAME} abgeschlossen.",
"UPDATE_NOTIFICATION_ERROR": "Fehler bei der Aktualisierung für das Modul {MODULE_NAME}.",
"UPDATE_NOTIFICATION_NEED-RESTART": "MagicMirror muss neu gestartet werden."
}

View File

@@ -41,5 +41,8 @@
"UPDATE_NOTIFICATION": "MagicMirror² update available.",
"UPDATE_NOTIFICATION_MODULE": "Update available for {MODULE_NAME} module.",
"UPDATE_INFO_SINGLE": "The current installation is {COMMIT_COUNT} commit behind on the {BRANCH_NAME} branch.",
"UPDATE_INFO_MULTIPLE": "The current installation is {COMMIT_COUNT} commits behind on the {BRANCH_NAME} branch."
"UPDATE_INFO_MULTIPLE": "The current installation is {COMMIT_COUNT} commits behind on the {BRANCH_NAME} branch.",
"UPDATE_NOTIFICATION_DONE": "Update done for {MODULE_NAME} module",
"UPDATE_NOTIFICATION_ERROR": "Update error for {MODULE_NAME} module",
"UPDATE_NOTIFICATION_NEED-RESTART": "Restarting of MagicMirror is required."
}

View File

@@ -43,5 +43,8 @@
"UPDATE_NOTIFICATION": "Une mise à jour de MagicMirror² est disponible",
"UPDATE_NOTIFICATION_MODULE": "Une mise à jour est disponible pour le module {MODULE_NAME}.",
"UPDATE_INFO_SINGLE": "L'installation actuelle est {COMMIT_COUNT} commit en retard sur la branche {BRANCH_NAME}.",
"UPDATE_INFO_MULTIPLE": "L'installation actuelle est {COMMIT_COUNT} commits en retard sur la branche {BRANCH_NAME}."
"UPDATE_INFO_MULTIPLE": "L'installation actuelle est {COMMIT_COUNT} commits en retard sur la branche {BRANCH_NAME}.",
"UPDATE_NOTIFICATION_DONE": "Mise à jour effectuée pour le module {MODULE_NAME}",
"UPDATE_NOTIFICATION_ERROR": "Erreur lors de la mise à jour du module {MODULE_NAME}",
"UPDATE_NOTIFICATION_NEED-RESTART": "Le redémarrage de MagicMirror est nécessaire."
}

78
vendor/package-lock.json generated vendored
View File

@@ -1,15 +1,15 @@
{
"name": "magicmirror-vendors",
"lockfileVersion": 2,
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "magicmirror-vendors",
"license": "MIT",
"dependencies": {
"@fortawesome/fontawesome-free": "^6.4.2",
"@fortawesome/fontawesome-free": "^6.5.1",
"animate.css": "^4.1.1",
"moment": "^2.29.4",
"moment": "^2.30.1",
"moment-timezone": "^0.5.43",
"nunjucks": "^3.2.4",
"suncalc": "^1.9.0",
@@ -17,9 +17,9 @@
}
},
"node_modules/@fortawesome/fontawesome-free": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.4.2.tgz",
"integrity": "sha512-m5cPn3e2+FDCOgi1mz0RexTUvvQibBebOUlUlW0+YrMjDTPkiJ6VTKukA1GRsvRw+12KyJndNjj0O4AgTxm2Pg==",
"version": "6.5.1",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.5.1.tgz",
"integrity": "sha512-CNy5vSwN3fsUStPRLX7fUYojyuzoEMSXPl7zSLJ8TgtRfjv24LOnOWKT2zYwaHZCJGkdyRnTmstR0P+Ah503Gw==",
"hasInstallScript": true,
"engines": {
"node": ">=6"
@@ -49,9 +49,9 @@
}
},
"node_modules/moment": {
"version": "2.29.4",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz",
"integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==",
"version": "2.30.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.30.1.tgz",
"integrity": "sha512-uEmtNhbDOrWPFS+hdjFCBfy9f2YoyzRpwcl+DqpC6taX21FzsTLQVbMV/W7PzNSX6x/bhC1zA3c2UQ5NzH6how==",
"engines": {
"node": "*"
}
@@ -101,65 +101,5 @@
"resolved": "https://registry.npmjs.org/weathericons/-/weathericons-2.1.0.tgz",
"integrity": "sha512-V45viuyuQQOuoePTqzxvP/wBpYALWkD695fkFvqpn+BiMyo64fFlyDbP2A8umZyFyz1cXFPNw1pWqeaSaQqJlQ=="
}
},
"dependencies": {
"@fortawesome/fontawesome-free": {
"version": "6.4.2",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.4.2.tgz",
"integrity": "sha512-m5cPn3e2+FDCOgi1mz0RexTUvvQibBebOUlUlW0+YrMjDTPkiJ6VTKukA1GRsvRw+12KyJndNjj0O4AgTxm2Pg=="
},
"a-sync-waterfall": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz",
"integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA=="
},
"animate.css": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/animate.css/-/animate.css-4.1.1.tgz",
"integrity": "sha512-+mRmCTv6SbCmtYJCN4faJMNFVNN5EuCTTprDTAo7YzIGji2KADmakjVA3+8mVDkZ2Bf09vayB35lSQIex2+QaQ=="
},
"asap": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA=="
},
"commander": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
"integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg=="
},
"moment": {
"version": "2.29.4",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz",
"integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w=="
},
"moment-timezone": {
"version": "0.5.43",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.43.tgz",
"integrity": "sha512-72j3aNyuIsDxdF1i7CEgV2FfxM1r6aaqJyLB2vwb33mXYyoyLly+F1zbWqhA3/bVIoJ4szlUoMbUnVdid32NUQ==",
"requires": {
"moment": "^2.29.4"
}
},
"nunjucks": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz",
"integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==",
"requires": {
"a-sync-waterfall": "^1.0.0",
"asap": "^2.0.3",
"commander": "^5.1.0"
}
},
"suncalc": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/suncalc/-/suncalc-1.9.0.tgz",
"integrity": "sha512-vMJ8Byp1uIPoj+wb9c1AdK4jpkSKVAywgHX0lqY7zt6+EWRRC3Z+0Ucfjy/0yxTVO1hwwchZe4uoFNqrIC24+A=="
},
"weathericons": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/weathericons/-/weathericons-2.1.0.tgz",
"integrity": "sha512-V45viuyuQQOuoePTqzxvP/wBpYALWkD695fkFvqpn+BiMyo64fFlyDbP2A8umZyFyz1cXFPNw1pWqeaSaQqJlQ=="
}
}
}

4
vendor/package.json vendored
View File

@@ -10,9 +10,9 @@
"url": "https://github.com/MichMich/MagicMirror/issues"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^6.4.2",
"@fortawesome/fontawesome-free": "^6.5.1",
"animate.css": "^4.1.1",
"moment": "^2.29.4",
"moment": "^2.30.1",
"moment-timezone": "^0.5.43",
"nunjucks": "^3.2.4",
"suncalc": "^1.9.0",