diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 3b406630..00000000 --- a/.dockerignore +++ /dev/null @@ -1,72 +0,0 @@ -# Various Node ignoramuses. - -logs -*.log -npm-debug.log* -pids -*.pid -*.seed -lib-cov -coverage -.grunt -.lock-wscript -build/Release -node_modules -jspm_modules -.npm -.node_repl_history - -# Various Windows ignoramuses. -Thumbs.db -ehthumbs.db -Desktop.ini -$RECYCLE.BIN/ -*.cab -*.msi -*.msm -*.msp -*.lnk - -# Various OSX ignoramuses. -.DS_Store -.AppleDouble -.LSOverride -Icon -._* -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -# Various Linux ignoramuses. - -.fuse_hidden* -.directory -.Trash-* - -# Various Magic Mirror ignoramuses and anti-ignoramuses. - -# Don't ignore the node_helper core module. -!/modules/node_helper -!/modules/node_helper/** - -# Ignore all modules except the default modules. -/modules/** -!/modules/default/** - -# Ignore changes to the custom css files. -/css/custom.css - -# Ignore unnecessary files for docker -CHANGELOG.md -LICENSE.md -README.md -Gruntfile.js -.* diff --git a/.gitignore b/.gitignore index e130a22e..9b851b18 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,9 @@ jspm_modules .npm .node_repl_history +# Visual Studio Code ignoramuses. +.vscode/ + # Various Windows ignoramuses. Thumbs.db ehthumbs.db @@ -65,3 +68,13 @@ Temporary Items # Ignore changes to the custom css files. /css/custom.css + +# Vim +## swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] + +## diff patch +*.orig +*.rej +*.bak diff --git a/.travis.yml b/.travis.yml index 5f6f2821..ec119b78 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: node_js node_js: + - "8" - "7" - "6" - "5.1" @@ -10,7 +11,10 @@ before_script: - sleep 5 script: - grunt -- npm test +- npm run test:unit +- npm run test:e2e +after_script: + - npm list cache: directories: - node_modules diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fe62971..9a68b174 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,34 +2,103 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). +## [2.1.3] - Unreleased -## [2.1.1] - Unreleased +### Changed +- Remove Roboto fonts files inside `fonts` and these are installed by npm install command. + +### Added +- Add `clientonly` script to start only the electron client for a remote server. +- Add symbol and color properties of event when `CALENDAR_EVENTS` notification is broadcasted from `default/calendar` module. +- Add `.vscode/` folder to `.gitignore` to keep custom Visual Studio Code config out of git. +- Add unit test the capitalizeFirstLetter function of newfeed module. +- Add new unit tests for function `shorten` in calendar module. +- Add new unit tests for function `getLocaleSpecification` in calendar module. +- Add unit test for js/class.js. +- Add unit tests for function `roundValue` in currentweather module. +- Add test e2e showWeek feature in spanish language. +- Add warning Log when is used old authentication method in the calendar module. + +### Updated +- Changed 'default.js' - listen on all attached interfaces by default. +- Add execution of `npm list` after the test are ran in Travis CI. +- Change hooks for the vendors e2e tests. +- Add log when clientonly failed on starting. +- Add warning color when are using full ip whitelist. + +### Fixed +- Fixed issue with incorrect allignment of analog clock when displayed in the center column of the MM. +- Fixed ipWhitelist behaviour to make empty whitelist ([]) allow any and all hosts access to the MM. +- Fixed issue with calendar module where 'excludedEvents' count towards 'maximumEntries'. +- Fixed issue with calendar module where global configuration of maximumEntries was not overridden by calendar specific config (see module doc). +- Fixed issue where `this.file(filename)` returns a path with two hashes + +## [2.1.2] - 2017-07-01 + +### Changed +- Revert Docker related changes in favor of [docker-MagicMirror](https://github.com/bastilimbach/docker-MagicMirror). All Docker images are outsourced. ([#856](https://github.com/MichMich/MagicMirror/pull/856)) +- Change Docker base image (Debian + Node) to an arm based distro (AlpineARM + Node) ([#846](https://github.com/MichMich/MagicMirror/pull/846)) +- Fix the dockerfile to have it running from the first time. + +### Added +- Add in option to wrap long calendar events to multiple lines using `wrapEvents` configuration option. +- Add test e2e `show title newsfeed` for newsfeed module. +- Add task to check configuration file. +- Add test check URLs of vendors. +- Add test of match current week number on clock module with showWeek configuration. +- Add test default modules present modules/default/defaultmodules.js. +- Add unit test calendar_modules function capFirst. +- Add test for check if exists the directories present in defaults modules. +- Add support for showing wind direction as an arrow instead of abbreviation in currentWeather module. +- Add support for writing translation fucntions to support flexible word order +- Add test for check if exits the directories present in defaults modules. +- Add calendar option to set a separate date format for full day events. +- Add ability for `currentweather` module to display indoor temperature via INDOOR_TEMPERATURE notification +- Add ability to change the path of the `custom.css`. +- Add translation Dutch to Alert module. +- Added Romanian translation. + +### Updated +- Added missing keys to Polish translation. +- Added missing key to German translation. +- Added better translation with flexible word order to Finnish translation. + +### Fixed +- Fix instruction in README for using automatically installer script. +- Bug of duplicated compliments as described in [here](https://forum.magicmirror.builders/topic/2381/compliments-module-stops-cycling-compliments). +- Fix double message about port when server is starting +- Corrected Swedish translations for TODAY/TOMORROW/DAYAFTERTOMORROW. +- Removed unused import from js/electron.js +- Made calendar.js respect config.timeFormat irrespecive of locale setting. +- Fixed alignment of analog clock when a large calendar is displayed in the same side bar. + +## [2.1.1] - 2017-04-01 **Note:** This update uses new dependencies. Please update using the following command: `git pull && npm install` ### Changed - Add `anytime` group for Compliments module. -- Compliments module can use remoteFile without default daytime arrays defined +- Compliments module can use remoteFile without default daytime arrays defined. - Installer: Use init config.js from config.js.sample. - Switched out `rrule` package for `rrule-alt` and fixes in `ical.js` in order to fix calendar issues. ([#565](https://github.com/MichMich/MagicMirror/issues/565)) - Make mouse events pass through the region fullscreen_above to modules below. - Scaled the splash screen down to make it a bit more subtle. - Replace HTML tables with markdown tables in README files. - Added `DAYAFTERTOMORROW`, `UPDATE_NOTIFICATION` and `UPDATE_NOTIFICATION_MODULE` to Finnish translations. -- Run `npm test` on Travis automatically +- Run `npm test` on Travis automatically. - Show the splash screen image even when is reboot or halted. - Added some missing translaton strings in the sv.json file. - Run task jsonlint to check translation files. -- Restructured Test Suite +- Restructured Test Suite. ### Added -- Added Docker support (Pull Request [#673](https://github.com/MichMich/MagicMirror/pull/673)) -- Calendar-specific support for `maximumEntries`, and ` maximumNumberOfDays` +- Added Docker support (Pull Request [#673](https://github.com/MichMich/MagicMirror/pull/673)). +- Calendar-specific support for `maximumEntries`, and ` maximumNumberOfDays`. - Add loaded function to modules, providing an async callback. - Made default newsfeed module aware of gesture events from [MMM-Gestures](https://github.com/thobach/MMM-Gestures) -- Add use pm2 for manager process into Installer RaspberryPi script -- Russian Translation -- Afrikaans Translation +- Add use pm2 for manager process into Installer RaspberryPi script. +- Russian Translation. +- Afrikaans Translation. - Add postinstall script to notify user that MagicMirror installed successfully despite warnings from NPM. - Init tests using mocha. - Option to use RegExp in Calendar's titleReplace. @@ -37,24 +106,32 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Icelandic Translation. - Add use a script to prevent when is run by SSH session set DISPLAY enviroment. - Enable ability to set configuration file by the enviroment variable called MM_CONFIG_FILE. -- Option to give each calendar a different color -- Option for colored min-temp and max-temp -- Add test e2e helloworld -- Add test e2e enviroment -- Add `chai-as-promised` npm module to devDependencies -- Basic set of tests for clock module -- Run e2e test in Travis +- Option to give each calendar a different color. +- Option for colored min-temp and max-temp. +- Add test e2e helloworld. +- Add test e2e enviroment. +- Add `chai-as-promised` npm module to devDependencies. +- Basic set of tests for clock module. +- Run e2e test in Travis. - Estonian Translation. -- Add test for compliments module for parts of day +- Add test for compliments module for parts of day. - Korean Translation. -- Added console warning on startup when deprecated config options are used -- Add option to display temperature unit label to the current weather module -- Added ability to disable wrapping of news items +- Added console warning on startup when deprecated config options are used. +- Add option to display temperature unit label to the current weather module. +- Added ability to disable wrapping of news items. - Added in the ability to hide events in the calendar module based on simple string filters. - Updated Norwegian translation. -- Added hideLoading option for News Feed module +- Added hideLoading option for News Feed module. - Added configurable dateFormat to clock module. - Added multiple calendar icon support. +- Added tests for Translations, dev argument, version, dev console. +- Added test anytime feature compliments module. +- Added test ipwhitelist configuration directive. +- Added test for calendar module: default, basic-auth, backward compability, fail-basic-auth. +- Added meta tags to support fullscreen mode on iOS (for server mode) +- Added `ignoreOldItems` and `ignoreOlderThan` options to the News Feed module +- Added test for MM_PORT enviroment variable. +- Added a configurable Week section to the clock module. ### Fixed - Update .gitignore to not ignore default modules folder. @@ -63,8 +140,9 @@ This project adheres to [Semantic Versioning](http://semver.org/). - Fix an issue where the analog clock looked scrambled. ([#611](https://github.com/MichMich/MagicMirror/issues/611)) - If units is set to imperial, the showRainAmount option of weatherforecast will show the correct unit. - Module currentWeather: check if temperature received from api is defined. -- Fix an issue with module hidden status changing to `true` although lock string prevented showing it +- Fix an issue with module hidden status changing to `true` although lock string prevented showing it. - Fix newsfeed module bug (removeStartTags) +- Fix when is set MM_PORT enviroment variable. - Fixed missing animation on `this.show(speed)` when module is alone in a region. ## [2.1.0] - 2016-12-31 diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index ddf6d9d6..00000000 --- a/Dockerfile +++ /dev/null @@ -1,19 +0,0 @@ -FROM node:latest - -RUN apt-get update && apt-get -y install dos2unix - -WORKDIR /opt/magic_mirror -COPY . . -COPY /modules unmount_modules -COPY /config unmount_config - -ENV NODE_ENV production -ENV MM_PORT 8080 - -RUN npm install - -RUN ["dos2unix", "docker-entrypoint.sh"] -RUN ["chmod", "+x", "docker-entrypoint.sh"] - -EXPOSE $MM_PORT -ENTRYPOINT ["/opt/magic_mirror/docker-entrypoint.sh"] diff --git a/Gruntfile.js b/Gruntfile.js index 06fed2d5..8d069c82 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -6,12 +6,20 @@ module.exports = function(grunt) { options: { configFile: ".eslintrc.json" }, - target: ["js/*.js", "modules/default/*.js", "modules/default/*/*.js", - "serveronly/*.js", "*.js", "tests/*/*.js", "!modules/default/alert/notificationFx.js", - "!modules/default/alert/modernizr.custom.js", "!modules/default/alert/classie.js", + target: [ + "js/*.js", + "modules/default/*.js", + "modules/default/*/*.js", + "serveronly/*.js", + "*.js", + "tests/**/*.js", + "!modules/default/alert/notificationFx.js", + "!modules/default/alert/modernizr.custom.js", + "!modules/default/alert/classie.js", "config/*", - "translations/translations.js", "vendor/vendor.js" - + "translations/translations.js", + "vendor/vendor.js", + "modules/node_modules/node_helper/index.js" ] }, stylelint: { @@ -19,14 +27,26 @@ module.exports = function(grunt) { options: { configFile: ".stylelintrc" }, - src: ["css/main.css", "modules/default/calendar/calendar.css", "modules/default/clock/clock_styles.css", "modules/default/currentweather/currentweather.css", "modules/default/weatherforcast/weatherforcast.css"] + src: [ + "css/main.css", + "modules/default/calendar/calendar.css", + "modules/default/clock/clock_styles.css", + "modules/default/currentweather/currentweather.css", + "modules/default/weatherforcast/weatherforcast.css" + ] } }, jsonlint: { main: { - src: ["package.json", ".eslintrc.json", ".stylelintrc", "translations/*.json", - "modules/default/*/translations/*.json", "installers/pm2_MagicMirror.json", - "vendor/package.js"], + src: [ + "package.json", + ".eslintrc.json", + ".stylelintrc", + "translations/*.json", + "modules/default/*/translations/*.json", + "installers/pm2_MagicMirror.json", + "vendor/package.js" + ], options: { reporter: "jshint" } @@ -58,11 +78,20 @@ module.exports = function(grunt) { "MD038": false } }, - src: ["README.md", "CHANGELOG.md", "LICENSE.md", "modules/README.md", "modules/default/**/*.md", "!modules/default/calendar/vendor/ical.js/readme.md"] + src: [ + "README.md", + "CHANGELOG.md", + "LICENSE.md", + "modules/README.md", + "modules/default/**/*.md", + "!modules/default/calendar/vendor/ical.js/readme.md" + ] } }, yamllint: { - all: [".travis.yml"] + all: [ + ".travis.yml" + ] } }); grunt.loadNpmTasks("grunt-eslint"); diff --git a/README.md b/README.md index 98ca4154..b7dea0fb 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Electron, the app wrapper around MagicMirror², only supports the Raspberry Pi 2 Execute the following command on your Raspberry Pi to install MagicMirror²: ```` -curl -sL https://raw.githubusercontent.com/MichMich/MagicMirror/master/installers/raspberry.sh | bash +bash -c "$(curl -sL https://raw.githubusercontent.com/MichMich/MagicMirror/master/installers/raspberry.sh)" ```` ### Manual Installation @@ -48,6 +48,11 @@ curl -sL https://raw.githubusercontent.com/MichMich/MagicMirror/master/installer ### Server Only In some cases, you want to start the application without an actual app window. In this case, you can start MagicMirror² in server only mode by manually running `node serveronly` or using Docker. This will start the server, after which you can open the application in your browser of choice. Detailed description below. +### Client Only +When you have a server running remotely and want to connect a standalone client to this instance, you can manually run `node clientonly --address 192.168.1.5 --port 8080`. (Specify the ip address and port number of the server) + +**Important:** Make sure that you whitelist the interface/ip in the server config where you want the client to connect to, otherwise it will not be allowed to connect to the server + #### Docker MagicMirror² in server only mode can be deployed using [Docker](https://docker.com). After a successful [Docker installation](https://docs.docker.com/engine/installation/) you just need to execute the following command in the shell: @@ -59,7 +64,7 @@ docker run -d \ --volume ~/magic_mirror/config:/opt/magic_mirror/config \ --volume ~/magic_mirror/modules:/opt/magic_mirror/modules \ --name magic_mirror \ - MichMich/MagicMirror + bastilimbach/docker-magicmirror ``` | **Volumes** | **Description** | @@ -75,6 +80,8 @@ var config = { }; ``` +If you want to run the server on a raspberry pi, use the `raspberry` tag. (bastilimbach/docker-magicmirror:raspberry) + #### Manual 1. Download and install the latest Node.js version. @@ -104,6 +111,11 @@ Type `git status` to see your changes, if there are any, you can reset them with 1. Duplicate `config/config.js.sample` to `config/config.js`. **Note:** If you used the installer script. This step is already done for you. 2. Modify your required settings. +Note: You'll can check your configuration running the follow command: +```bash +npm run config:check +``` + The following properties can be configured: | **Option** | **Description** | @@ -117,7 +129,7 @@ The following properties can be configured: | `units` | The units that will be used in the default weather modules. Possible values are `metric` or `imperial`. The default is `metric`. | | `modules` | An array of active modules. **The array must contain objects. See the next table below for more information.** | | `electronOptions` | An optional array of Electron (browser) options. This allows configuration of e.g. the browser screen size and position (example: `electronOptions: { fullscreen: false, width: 800, height: 600 }`). Kiosk mode can be enabled by setting `kiosk = true`, `autoHideMenuBar = false` and `fullscreen = false`. More options can be found [here](https://github.com/electron/electron/blob/master/docs/api/browser-window.md). | - +| `customCss` | The path of the `custom.css` stylesheet. The default is `css/custom.css`. | Module configuration: diff --git a/clientonly/index.js b/clientonly/index.js new file mode 100644 index 00000000..72495504 --- /dev/null +++ b/clientonly/index.js @@ -0,0 +1,104 @@ +/* jshint esversion: 6 */ + +"use strict"; + +// Use seperate scope to prevent global scope pollution +(function () { + var config = {}; + + // Helper function to get server address/hostname from either the commandline or env + function getServerAddress() { + // Helper function to get command line parameters + // Assumes that a cmdline parameter is defined with `--key [value]` + function getCommandLineParameter(key, defaultValue = undefined) { + var index = process.argv.indexOf(`--${key}`); + var value = index > -1 ? process.argv[index + 1] : undefined; + return value !== undefined ? String(value) : defaultValue; + } + + // Prefer command line arguments over environment variables + ["address", "port"].forEach((key) => { + config[key] = getCommandLineParameter(key, process.env[key.toUpperCase()]); + }) + } + + function getServerConfig(url) { + // Return new pending promise + return new Promise((resolve, reject) => { + // Select http or https module, depending on reqested url + const lib = url.startsWith("https") ? require("https") : require("http"); + const request = lib.get(url, (response) => { + var configData = ""; + + // Gather incomming data + response.on("data", function(chunk) { + configData += chunk; + }); + // Resolve promise at the end of the HTTP/HTTPS stream + response.on("end", function() { + resolve(JSON.parse(configData)); + }); + }); + + request.on("error", function(error) { + reject(new Error(`Unable to read config from server (${url} (${error.message}`)); + }); + }) + }; + + function fail(message, code = 1) { + if (message !== undefined && typeof message === "string") { + console.log(message); + } else { + console.log("Usage: 'node clientonly --address 192.168.1.10 --port 8080'"); + } + process.exit(code); + } + + getServerAddress(); + + (config.address && config.port) || fail(); + + // Only start the client if a non-local server was provided + if (["localhost", "127.0.0.1", "::1", "::ffff:127.0.0.1", undefined].indexOf(config.address) === -1) { + getServerConfig(`http://${config.address}:${config.port}/config/`) + .then(function (config) { + // Pass along the server config via an environment variable + var env = Object.create(process.env); + var options = { env: env }; + config.address = config.address; + config.port = config.port; + env.config = JSON.stringify(config); + + // Spawn electron application + const electron = require("electron"); + const child = require("child_process").spawn(electron, ["js/electron.js"], options); + + // Pipe all child process output to current stdout + child.stdout.on("data", function (buf) { + process.stdout.write(`Client: ${buf}`); + }); + + // Pipe all child process errors to current stderr + child.stderr.on("data", function (buf) { + process.stderr.write(`Client: ${buf}`); + }); + + child.on("error", function (err) { + process.stdout.write(`Client: ${err}`); + }); + + child.on('close', (code) => { + if (code != 0) { + console.log(`There something wrong. The clientonly is not running code ${code}`); + } + }); + + }) + .catch(function (reason) { + fail(`Unable to connect to server: (${reason})`); + }); + } else { + fail(); + } +}()); diff --git a/config/config.js.sample b/config/config.js.sample index 53677cfa..8294e319 100644 --- a/config/config.js.sample +++ b/config/config.js.sample @@ -2,11 +2,20 @@ * * By Michael Teeuw http://michaelteeuw.nl * MIT Licensed. + * + * For more information how you can configurate this file + * See https://github.com/MichMich/MagicMirror#configuration + * */ var config = { + address: "localhost", port: 8080, - ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses. + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], // Set [] to allow all IP addresses + // or add a specific IPv4 of 192.168.1.5 : + // ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.1.5"], + // or IPv4 range of 192.168.3.0 --> 192.168.3.15 use CIDR format : + // ["127.0.0.1", "::ffff:127.0.0.1", "::1", "::ffff:192.168.3.0/28"], language: "en", timeFormat: 24, diff --git a/css/main.css b/css/main.css index 01d40aec..49bfe611 100644 --- a/css/main.css +++ b/css/main.css @@ -1,6 +1,7 @@ html { cursor: none; overflow: hidden; + background: #000; } ::-webkit-scrollbar { diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh deleted file mode 100644 index 9d91492f..00000000 --- a/docker-entrypoint.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -if [ ! -f /opt/magic_mirror/modules ]; then - cp -R /opt/magic_mirror/unmount_modules/. /opt/magic_mirror/modules -fi - -if [ ! -f /opt/magic_mirror/config ]; then - cp -R /opt/magic_mirror/unmount_config/. /opt/magic_mirror/config -fi - -node serveronly diff --git a/fonts/LICENSE.txt b/fonts/LICENSE.txt deleted file mode 100644 index 75b52484..00000000 --- a/fonts/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/fonts/Roboto-Black/Roboto-Black.ttf b/fonts/Roboto-Black/Roboto-Black.ttf deleted file mode 100644 index fbde625d..00000000 Binary files a/fonts/Roboto-Black/Roboto-Black.ttf and /dev/null differ diff --git a/fonts/Roboto-Black/Roboto-Black.woff b/fonts/Roboto-Black/Roboto-Black.woff deleted file mode 100644 index 94b19305..00000000 Binary files a/fonts/Roboto-Black/Roboto-Black.woff and /dev/null differ diff --git a/fonts/Roboto-Black/Roboto-Black.woff2 b/fonts/Roboto-Black/Roboto-Black.woff2 deleted file mode 100644 index c0cb786e..00000000 Binary files a/fonts/Roboto-Black/Roboto-Black.woff2 and /dev/null differ diff --git a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.ttf b/fonts/Roboto-BlackItalic/Roboto-BlackItalic.ttf deleted file mode 100644 index 60f7782a..00000000 Binary files a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.ttf and /dev/null differ diff --git a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff b/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff deleted file mode 100644 index eb07f101..00000000 Binary files a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff and /dev/null differ diff --git a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff2 b/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff2 deleted file mode 100644 index 6ad4604f..00000000 Binary files a/fonts/Roboto-BlackItalic/Roboto-BlackItalic.woff2 and /dev/null differ diff --git a/fonts/Roboto-Bold/Roboto-Bold.ttf b/fonts/Roboto-Bold/Roboto-Bold.ttf deleted file mode 100644 index a355c27c..00000000 Binary files a/fonts/Roboto-Bold/Roboto-Bold.ttf and /dev/null differ diff --git a/fonts/Roboto-Bold/Roboto-Bold.woff b/fonts/Roboto-Bold/Roboto-Bold.woff deleted file mode 100644 index d1ef48b4..00000000 Binary files a/fonts/Roboto-Bold/Roboto-Bold.woff and /dev/null differ diff --git a/fonts/Roboto-Bold/Roboto-Bold.woff2 b/fonts/Roboto-Bold/Roboto-Bold.woff2 deleted file mode 100644 index 5658e9a7..00000000 Binary files a/fonts/Roboto-Bold/Roboto-Bold.woff2 and /dev/null differ diff --git a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.ttf b/fonts/Roboto-BoldItalic/Roboto-BoldItalic.ttf deleted file mode 100644 index 3c9a7a37..00000000 Binary files a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.ttf and /dev/null differ diff --git a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff b/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff deleted file mode 100644 index 291c89dd..00000000 Binary files a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff and /dev/null differ diff --git a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff2 b/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff2 deleted file mode 100644 index 75123709..00000000 Binary files a/fonts/Roboto-BoldItalic/Roboto-BoldItalic.woff2 and /dev/null differ diff --git a/fonts/Roboto-Italic/Roboto-Italic.ttf b/fonts/Roboto-Italic/Roboto-Italic.ttf deleted file mode 100644 index ff6046d5..00000000 Binary files a/fonts/Roboto-Italic/Roboto-Italic.ttf and /dev/null differ diff --git a/fonts/Roboto-Italic/Roboto-Italic.woff b/fonts/Roboto-Italic/Roboto-Italic.woff deleted file mode 100644 index 3bd43138..00000000 Binary files a/fonts/Roboto-Italic/Roboto-Italic.woff and /dev/null differ diff --git a/fonts/Roboto-Italic/Roboto-Italic.woff2 b/fonts/Roboto-Italic/Roboto-Italic.woff2 deleted file mode 100644 index 77c81227..00000000 Binary files a/fonts/Roboto-Italic/Roboto-Italic.woff2 and /dev/null differ diff --git a/fonts/Roboto-Light/Roboto-Light.ttf b/fonts/Roboto-Light/Roboto-Light.ttf deleted file mode 100644 index 94c6bcc6..00000000 Binary files a/fonts/Roboto-Light/Roboto-Light.ttf and /dev/null differ diff --git a/fonts/Roboto-Light/Roboto-Light.woff b/fonts/Roboto-Light/Roboto-Light.woff deleted file mode 100644 index 1d1ad478..00000000 Binary files a/fonts/Roboto-Light/Roboto-Light.woff and /dev/null differ diff --git a/fonts/Roboto-Light/Roboto-Light.woff2 b/fonts/Roboto-Light/Roboto-Light.woff2 deleted file mode 100644 index 166c8218..00000000 Binary files a/fonts/Roboto-Light/Roboto-Light.woff2 and /dev/null differ diff --git a/fonts/Roboto-LightItalic/Roboto-LightItalic.ttf b/fonts/Roboto-LightItalic/Roboto-LightItalic.ttf deleted file mode 100644 index 04cc0023..00000000 Binary files a/fonts/Roboto-LightItalic/Roboto-LightItalic.ttf and /dev/null differ diff --git a/fonts/Roboto-LightItalic/Roboto-LightItalic.woff b/fonts/Roboto-LightItalic/Roboto-LightItalic.woff deleted file mode 100644 index 3662bf40..00000000 Binary files a/fonts/Roboto-LightItalic/Roboto-LightItalic.woff and /dev/null differ diff --git a/fonts/Roboto-LightItalic/Roboto-LightItalic.woff2 b/fonts/Roboto-LightItalic/Roboto-LightItalic.woff2 deleted file mode 100644 index 9ba7fbd2..00000000 Binary files a/fonts/Roboto-LightItalic/Roboto-LightItalic.woff2 and /dev/null differ diff --git a/fonts/Roboto-Medium/Roboto-Medium.ttf b/fonts/Roboto-Medium/Roboto-Medium.ttf deleted file mode 100644 index 39c63d74..00000000 Binary files a/fonts/Roboto-Medium/Roboto-Medium.ttf and /dev/null differ diff --git a/fonts/Roboto-Medium/Roboto-Medium.woff b/fonts/Roboto-Medium/Roboto-Medium.woff deleted file mode 100644 index 487ea69b..00000000 Binary files a/fonts/Roboto-Medium/Roboto-Medium.woff and /dev/null differ diff --git a/fonts/Roboto-Medium/Roboto-Medium.woff2 b/fonts/Roboto-Medium/Roboto-Medium.woff2 deleted file mode 100644 index 2622b475..00000000 Binary files a/fonts/Roboto-Medium/Roboto-Medium.woff2 and /dev/null differ diff --git a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.ttf b/fonts/Roboto-MediumItalic/Roboto-MediumItalic.ttf deleted file mode 100644 index dc743f0a..00000000 Binary files a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.ttf and /dev/null differ diff --git a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff b/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff deleted file mode 100644 index 70dea35a..00000000 Binary files a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff and /dev/null differ diff --git a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff2 b/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff2 deleted file mode 100644 index 8b111d46..00000000 Binary files a/fonts/Roboto-MediumItalic/Roboto-MediumItalic.woff2 and /dev/null differ diff --git a/fonts/Roboto-Regular/Roboto-Regular.ttf b/fonts/Roboto-Regular/Roboto-Regular.ttf deleted file mode 100644 index 8c082c8d..00000000 Binary files a/fonts/Roboto-Regular/Roboto-Regular.ttf and /dev/null differ diff --git a/fonts/Roboto-Regular/Roboto-Regular.woff b/fonts/Roboto-Regular/Roboto-Regular.woff deleted file mode 100644 index 6ea53c20..00000000 Binary files a/fonts/Roboto-Regular/Roboto-Regular.woff and /dev/null differ diff --git a/fonts/Roboto-Regular/Roboto-Regular.woff2 b/fonts/Roboto-Regular/Roboto-Regular.woff2 deleted file mode 100644 index 10cf92b8..00000000 Binary files a/fonts/Roboto-Regular/Roboto-Regular.woff2 and /dev/null differ diff --git a/fonts/Roboto-Thin/Roboto-Thin.ttf b/fonts/Roboto-Thin/Roboto-Thin.ttf deleted file mode 100644 index d6955502..00000000 Binary files a/fonts/Roboto-Thin/Roboto-Thin.ttf and /dev/null differ diff --git a/fonts/Roboto-Thin/Roboto-Thin.woff b/fonts/Roboto-Thin/Roboto-Thin.woff deleted file mode 100644 index b0e7c557..00000000 Binary files a/fonts/Roboto-Thin/Roboto-Thin.woff and /dev/null differ diff --git a/fonts/Roboto-Thin/Roboto-Thin.woff2 b/fonts/Roboto-Thin/Roboto-Thin.woff2 deleted file mode 100644 index 5eee3b3e..00000000 Binary files a/fonts/Roboto-Thin/Roboto-Thin.woff2 and /dev/null differ diff --git a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.ttf b/fonts/Roboto-ThinItalic/Roboto-ThinItalic.ttf deleted file mode 100644 index 07172ff6..00000000 Binary files a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.ttf and /dev/null differ diff --git a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff b/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff deleted file mode 100644 index 73f10ad4..00000000 Binary files a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff and /dev/null differ diff --git a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff2 b/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff2 deleted file mode 100644 index 292c86f4..00000000 Binary files a/fonts/Roboto-ThinItalic/Roboto-ThinItalic.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.ttf b/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.ttf deleted file mode 100644 index fc28868a..00000000 Binary files a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff b/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff deleted file mode 100644 index cf577ca5..00000000 Binary files a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff2 b/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff2 deleted file mode 100644 index 8b2e28cd..00000000 Binary files a/fonts/RobotoCondensed-Bold/RobotoCondensed-Bold.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.ttf b/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.ttf deleted file mode 100644 index e1a648ff..00000000 Binary files a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff b/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff deleted file mode 100644 index 0b5db116..00000000 Binary files a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff2 b/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff2 deleted file mode 100644 index 5d3f2072..00000000 Binary files a/fonts/RobotoCondensed-BoldItalic/RobotoCondensed-BoldItalic.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.ttf b/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.ttf deleted file mode 100644 index 97ff9f1e..00000000 Binary files a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff b/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff deleted file mode 100644 index 4548bfa9..00000000 Binary files a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff2 b/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff2 deleted file mode 100644 index 04141901..00000000 Binary files a/fonts/RobotoCondensed-Italic/RobotoCondensed-Italic.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.ttf b/fonts/RobotoCondensed-Light/RobotoCondensed-Light.ttf deleted file mode 100644 index 2dae31e2..00000000 Binary files a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff b/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff deleted file mode 100644 index b797af13..00000000 Binary files a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff2 b/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff2 deleted file mode 100644 index 1e3b487a..00000000 Binary files a/fonts/RobotoCondensed-Light/RobotoCondensed-Light.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.ttf b/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.ttf deleted file mode 100644 index da108d3a..00000000 Binary files a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff b/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff deleted file mode 100644 index 8eae55a8..00000000 Binary files a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff2 b/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff2 deleted file mode 100644 index 947a1358..00000000 Binary files a/fonts/RobotoCondensed-LightItalic/RobotoCondensed-LightItalic.woff2 and /dev/null differ diff --git a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.ttf b/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.ttf deleted file mode 100644 index c2304c14..00000000 Binary files a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.ttf and /dev/null differ diff --git a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff b/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff deleted file mode 100644 index 3e25d65d..00000000 Binary files a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff and /dev/null differ diff --git a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff2 b/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff2 deleted file mode 100644 index d7c42c8c..00000000 Binary files a/fonts/RobotoCondensed-Regular/RobotoCondensed-Regular.woff2 and /dev/null differ diff --git a/fonts/package.json b/fonts/package.json new file mode 100644 index 00000000..ad164516 --- /dev/null +++ b/fonts/package.json @@ -0,0 +1,15 @@ +{ + "name": "magicmirror-fonts", + "description": "Package for fonts use by MagicMirror Core.", + "repository": { + "type": "git", + "url": "git+https://github.com/MichMich/MagicMirror.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/MichMich/MagicMirror/issues" + }, + "dependencies": { + "roboto-fontface": "^0.8.0" + } +} diff --git a/fonts/roboto.css b/fonts/roboto.css index ce9099da..fda90cd2 100644 --- a/fonts/roboto.css +++ b/fonts/roboto.css @@ -5,9 +5,9 @@ src: local("Roboto Thin"), local("Roboto-Thin"), - url("Roboto-Thin/Roboto-Thin.woff2") format("woff2"), - url("Roboto-Thin/Roboto-Thin.woff") format("woff"), - url("Roboto-Thin/Roboto-Thin.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Thin.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Thin.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Thin/Roboto-Thin.ttf") format("truetype"); } @font-face { @@ -17,9 +17,9 @@ src: local("Roboto Condensed Light"), local("RobotoCondensed-Light"), - url("RobotoCondensed-Light/RobotoCondensed-Light.woff2") format("woff2"), - url("RobotoCondensed-Light/RobotoCondensed-Light.woff") format("woff"), - url("RobotoCondensed-Light/RobotoCondensed-Light.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Light.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Light.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Light.ttf") format("truetype"); } @font-face { @@ -29,9 +29,9 @@ src: local("Roboto Condensed"), local("RobotoCondensed-Regular"), - url("RobotoCondensed-Regular/RobotoCondensed-Regular.woff2") format("woff2"), - url("RobotoCondensed-Regular/RobotoCondensed-Regular.woff") format("woff"), - url("RobotoCondensed-Regular/RobotoCondensed-Regular.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Regular.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Regular.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Regular.ttf") format("truetype"); } @font-face { @@ -41,9 +41,9 @@ src: local("Roboto Condensed Bold"), local("RobotoCondensed-Bold"), - url("RobotoCondensed-Bold/RobotoCondensed-Bold.woff2") format("woff2"), - url("RobotoCondensed-Bold/RobotoCondensed-Bold.woff") format("woff"), - url("RobotoCondensed-Bold/RobotoCondensed-Bold.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Bold.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Bold.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto-condensed/RobotoCondensed-Bold.ttf") format("truetype"); } @font-face { @@ -53,9 +53,9 @@ src: local("Roboto"), local("Roboto-Regular"), - url("Roboto-Regular/Roboto-Regular.woff2") format("woff2"), - url("Roboto-Regular/Roboto-Regular.woff") format("woff"), - url("Roboto-Regular/Roboto-Regular.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Regular.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Regular.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Regular.ttf") format("truetype"); } @font-face { @@ -65,9 +65,9 @@ src: local("Roboto Medium"), local("Roboto-Medium"), - url("Roboto-Medium/Roboto-Medium.woff2") format("woff2"), - url("Roboto-Medium/Roboto-Medium.woff") format("woff"), - url("Roboto-Medium/Roboto-Medium.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Medium.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Medium.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Medium.ttf") format("truetype"); } @font-face { @@ -77,9 +77,9 @@ src: local("Roboto Bold"), local("Roboto-Bold"), - url("Roboto-Bold/Roboto-Bold.woff2") format("woff2"), - url("Roboto-Bold/Roboto-Bold.woff") format("woff"), - url("Roboto-Bold/Roboto-Bold.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Bold.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Bold.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Bold.ttf") format("truetype"); } @font-face { @@ -89,7 +89,7 @@ src: local("Roboto Light"), local("Roboto-Light"), - url("Roboto-Light/Roboto-Light.woff2") format("woff2"), - url("Roboto-Light/Roboto-Light.woff") format("woff"), - url("Roboto-Light/Roboto-Light.ttf") format("truetype"); + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Light.woff2") format("woff2"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Light.woff") format("woff"), + url("node_modules/roboto-fontface/fonts/roboto/Roboto-Light.ttf") format("truetype"); } diff --git a/index.html b/index.html index 606f5aac..f3e8d12f 100644 --- a/index.html +++ b/index.html @@ -1,9 +1,15 @@ - Magic Mirror + MagicMirror² + + + + + + diff --git a/installers/raspberry.sh b/installers/raspberry.sh index 2df89a5f..ecdcc842 100644 --- a/installers/raspberry.sh +++ b/installers/raspberry.sh @@ -65,7 +65,7 @@ if command_exists node; then fi else - echo -e "\e[92mNo Node.js upgrade nessecery.\e[0m" + echo -e "\e[92mNo Node.js upgrade necessary.\e[0m" fi else @@ -150,8 +150,7 @@ fi # Use pm2 control like a service MagicMirror read -p "Do you want use pm2 for auto starting of your MagicMirror (y/n)?" choice -if [[ $choice =~ ^[Yy]$ ]] -then +if [[ $choice =~ ^[Yy]$ ]]; then sudo npm install -g pm2 sudo su -c "env PATH=$PATH:/usr/bin pm2 startup linux -u pi --hp /home/pi" pm2 start ~/MagicMirror/installers/pm2_MagicMirror.json diff --git a/js/class.js b/js/class.js index 3c44250e..ec75f6f2 100644 --- a/js/class.js +++ b/js/class.js @@ -4,15 +4,15 @@ */ // Inspired by base2 and Prototype -(function() { +(function () { var initializing = false; - var fnTest = /xyz/.test(function() {xyz;}) ? /\b_super\b/ : /.*/; + var fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) - this.Class = function() {}; + this.Class = function () { }; // Create a new Class that inherits from this class - Class.extend = function(prop) { + Class.extend = function (prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, @@ -30,23 +30,23 @@ for (var 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]) ? (function(name, fn) { - return function() { - var tmp = this._super; + typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function (name, fn) { + return function () { + var tmp = this._super; - // Add a new ._super() method that is the same method - // but on the super-class - this._super = _super[name]; + // Add a new ._super() method that is the same method + // but on the super-class + this._super = _super[name]; - // The method only need to be bound temporarily, so we - // remove it when we're done executing - var ret = fn.apply(this, arguments); - this._super = tmp; + // The method only need to be bound temporarily, so we + // remove it when we're done executing + var ret = fn.apply(this, arguments); + this._super = tmp; - return ret; - }; - })(name, prop[name]) : prop[name]; + return ret; + }; + })(name, prop[name]) : prop[name]; } // The dummy class constructor @@ -90,4 +90,9 @@ function cloneObject(obj) { } /*************** DO NOT EDIT THE LINE BELOW ***************/ -if (typeof module !== "undefined") {module.exports = Class;} +if (typeof module !== "undefined") { + module.exports = Class; + module.exports._test = { + cloneObject: cloneObject + } +} diff --git a/js/defaults.js b/js/defaults.js index 66926de7..06ff7b62 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -8,10 +8,12 @@ */ var port = 8080; +var address = ""; // Default to listening on all interfaces if (typeof(mmPort) !== "undefined") { port = mmPort; } var defaults = { + address: address, port: port, kioskmode: false, electronOptions: {}, @@ -21,6 +23,7 @@ var defaults = { timeFormat: 24, units: "metric", zoom: 1, + customCss: "css/custom.css", modules: [ { diff --git a/js/electron.js b/js/electron.js index 1f16092b..84842ed2 100644 --- a/js/electron.js +++ b/js/electron.js @@ -2,12 +2,11 @@ "use strict"; -const Server = require(__dirname + "/server.js"); const electron = require("electron"); const core = require(__dirname + "/app.js"); // Config -var config = {}; +var config = process.env.config ? JSON.parse(process.env.config) : {}; // Module to control application life. const app = electron.app; // Module to create native browser window. @@ -18,7 +17,6 @@ const BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow() { - var electronOptionsDefaults = { width: 800, height: 600, @@ -30,7 +28,7 @@ function createWindow() { zoomFactor: config.zoom }, backgroundColor: "#000000" - } + }; // DEPRECATED: "kioskmode" backwards compatibility, to be removed // settings these options directly instead provides cleaner interface @@ -47,11 +45,12 @@ function createWindow() { mainWindow = new BrowserWindow(electronOptions); // and load the index.html of the app. - //mainWindow.loadURL('file://' + __dirname + '../../index.html'); - mainWindow.loadURL("http://localhost:" + config.port); + // If config.address is not defined or is an empty string (listening on all interfaces), connect to localhost + var address = (config.address === void 0) | (config.address === "") ? (config.address = "localhost") : config.address; + mainWindow.loadURL(`http://${address}:${config.port}`); // Open the DevTools if run with "npm start dev" - if(process.argv[2] == "dev") { + if (process.argv.includes("dev")) { mainWindow.webContents.openDevTools(); } @@ -97,8 +96,10 @@ app.on("activate", function() { } }); -// Start the core application. +// Start the core application if server is run on localhost // This starts all node helpers and starts the webserver. -core.start(function(c) { - config = c; -}); +if (["localhost", "127.0.0.1", "::1", "::ffff:127.0.0.1", undefined].indexOf(config.address) > -1) { + core.start(function(c) { + config = c; + }); +} diff --git a/js/loader.js b/js/loader.js index 42b42952..98db1c25 100644 --- a/js/loader.js +++ b/js/loader.js @@ -32,10 +32,10 @@ var Loader = (function() { }); } else { // All modules loaded. Load custom.css - // This is done after all the moduels so we can - // overwrite all the defined styls. + // This is done after all the modules so we can + // overwrite all the defined styles. - loadFile("css/custom.css", function() { + loadFile(config.customCss, function() { // custom.css loaded. Start all modules. startModules(); }); diff --git a/js/main.js b/js/main.js index 5c8a6737..f499da62 100644 --- a/js/main.js +++ b/js/main.js @@ -165,8 +165,6 @@ var MM = (function() { if( headerWrapper.length > 0 && newHeader) { headerWrapper[0].innerHTML = newHeader; } - - }; /* hideModule(module, speed, callback) @@ -219,7 +217,7 @@ var MM = (function() { // remove lockString if set in options. if (options.lockString) { - var index = module.lockStrings.indexOf(options.lockString) + var index = module.lockStrings.indexOf(options.lockString); if ( index !== -1) { module.lockStrings.splice(index, 1); } diff --git a/js/module.js b/js/module.js index 457b9772..413efa46 100644 --- a/js/module.js +++ b/js/module.js @@ -194,7 +194,7 @@ var Module = Class.extend({ * return string - File path. */ file: function (file) { - return this.data.path + "/" + file; + return (this.data.path + "/" + file).replace("//", "/"); }, /* loadStyles() @@ -272,14 +272,18 @@ var Module = Class.extend({ } }, - /* translate(key, defaultValue) - * Request the translation for a given key. + /* translate(key, defaultValueOrVariables, defaultValue) + * Request the translation for a given key with optional variables and default value. * - * argument key string - The key of the string to translage - * argument defaultValue string - The default value if no translation was found. (Optional) + * argument key string - The key of the string to translate + * argument defaultValueOrVariables string/object - The default value or variables for translating. (Optional) + * argument defaultValue string - The default value with variables. (Optional) */ - translate: function (key, defaultValue) { - return Translator.translate(this, key) || defaultValue || ""; + translate: function (key, defaultValueOrVariables, defaultValue) { + if(typeof defaultValueOrVariables === "object") { + return Translator.translate(this, key, defaultValueOrVariables) || defaultValue || ""; + } + return Translator.translate(this, key) || defaultValueOrVariables || ""; }, /* updateDom(speed) diff --git a/js/server.js b/js/server.js index beb8b84c..fbc51cbc 100644 --- a/js/server.js +++ b/js/server.js @@ -13,18 +13,25 @@ var path = require("path"); var ipfilter = require("express-ipfilter").IpFilter; var fs = require("fs"); var helmet = require("helmet"); +var Utils = require(__dirname + "/utils.js"); var Server = function(config, callback) { - console.log("Starting server op port " + config.port + " ... "); - server.listen(config.port, config.address ? config.address : null); + var port = config.port; + if (process.env.MM_PORT) { + port = process.env.MM_PORT; + } + + console.log("Starting server on port " + port + " ... "); + + server.listen(port, config.address ? config.address : null); if (config.ipWhitelist instanceof Array && config.ipWhitelist.length == 0) { - console.info("You're using a full whitelist configuration to allow for all IPs") + console.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs")) } app.use(function(req, res, next) { - var result = ipfilter(config.ipWhitelist, {mode: "allow", log: false})(req, res, function(err) { + var result = ipfilter(config.ipWhitelist, {mode: config.ipWhitelist.length === 0 ? "deny" : "allow", log: false})(req, res, function(err) { if (err === undefined) { return next(); } @@ -37,7 +44,7 @@ var Server = function(config, callback) { app.use("/js", express.static(__dirname)); var directories = ["/config", "/css", "/fonts", "/modules", "/vendor", "/translations", "/tests/configs"]; var directory; - for (i in directories) { + for (var i in directories) { directory = directories[i]; app.use(directory, express.static(path.resolve(global.root_path + directory))); } @@ -46,6 +53,10 @@ var Server = function(config, callback) { res.send(global.version); }); + app.get("/config", function(req,res) { + res.send(config); + }); + app.get("/", function(req, res) { var html = fs.readFileSync(path.resolve(global.root_path + "/index.html"), {encoding: "utf8"}); html = html.replace("#VERSION#", global.version); diff --git a/js/socketclient.js b/js/socketclient.js index 8ea468a8..baead68e 100644 --- a/js/socketclient.js +++ b/js/socketclient.js @@ -22,7 +22,6 @@ var MMSocket = function(moduleName) { // register catch all. self.socket.on("*", function(notification, payload) { if (notification !== "*") { - //console.log('Received notification: ' + notification +', payload: ' + payload); notificationCallback(notification, payload); } }); diff --git a/js/translator.js b/js/translator.js index d715b383..b82a739e 100644 --- a/js/translator.js +++ b/js/translator.js @@ -111,32 +111,47 @@ var Translator = (function() { translations: {}, translationsFallback: {}, - /* translate(module, key) + /* translate(module, key, variables) * Load a translation for a given key for a given module. * * argument module Module - The module to load the translation for. * argument key string - The key of the text to translate. + * argument variables - The variables to use within the translation template (optional) */ - translate: function(module, key) { + translate: function(module, key, variables) { + variables = variables || {}; //Empty object by default + + // Combines template and variables like: + // template: "Please wait for {timeToWait} before continuing with {work}." + // variables: {timeToWait: "2 hours", work: "painting"} + // to: "Please wait for 2 hours before continuing with painting." + function createStringFromTemplate(template, variables) { + if(variables.fallback && !template.match(new RegExp("\{.+\}"))) { + template = variables.fallback; + } + return template.replace(new RegExp("\{([^\}]+)\}", "g"), function(_unused, varName){ + return variables[varName] || "{"+varName+"}"; + }); + } if(this.translations[module.name] && key in this.translations[module.name]) { // Log.log("Got translation for " + key + " from module translation: "); - return this.translations[module.name][key]; + return createStringFromTemplate(this.translations[module.name][key], variables); } if (key in this.coreTranslations) { // Log.log("Got translation for " + key + " from core translation."); - return this.coreTranslations[key]; + return createStringFromTemplate(this.coreTranslations[key], variables); } if (this.translationsFallback[module.name] && key in this.translationsFallback[module.name]) { // Log.log("Got translation for " + key + " from module translation fallback."); - return this.translationsFallback[module.name][key]; + return createStringFromTemplate(this.translationsFallback[module.name][key], variables); } if (key in this.coreTranslationsFallback) { // Log.log("Got translation for " + key + " from core translation fallback."); - return this.coreTranslationsFallback[key]; + return createStringFromTemplate(this.coreTranslationsFallback[key], variables); } return key; diff --git a/js/utils.js b/js/utils.js index 76eb2703..3f623499 100644 --- a/js/utils.js +++ b/js/utils.js @@ -11,7 +11,8 @@ var colors = require("colors/safe"); var Utils = { colors: { warn: colors.yellow, - error: colors.red + error: colors.red, + info: colors.blue } }; diff --git a/modules/README.md b/modules/README.md index 03664b15..12a42e59 100644 --- a/modules/README.md +++ b/modules/README.md @@ -44,27 +44,27 @@ As you can see, the `Module.register()` method takes two arguments: the name of ### Available module instance properties After the module is initialized, the module instance has a few available module properties: -####`this.name` +#### `this.name` **String** The name of the module. -####`this.identifier` +#### `this.identifier` **String** This is a unique identifier for the module instance. -####`this.hidden` +#### `this.hidden` **Boolean** This represents if the module is currently hidden (faded away). -####`this.config` +#### `this.config` **Boolean** The configuration of the module instance as set in the user's config.js file. This config will also contain the module's defaults if these properties are not over written by the user config. -####`this.data` +#### `this.data` **Object** The data object contains additional metadata about the module instance: @@ -75,10 +75,10 @@ The data object contains additional metadata about the module instance: - `data.position` - The position in which the instance will be shown. -####`defaults: {}` +#### `defaults: {}` Any properties defined in the defaults object, will be merged with the module config as defined in the user's config.js file. This is the best place to set your modules's configuration defaults. Any of the module configuration properties can be accessed using `this.config.propertyName`, but more about that later. -####'requiresVersion:' +#### `requiresVersion:` *Introduced in version: 2.1.0.* @@ -93,10 +93,10 @@ requiresVersion: "2.1.0", ### Subclassable module methods -####`init()` +#### `init()` This method is called when a module gets instantiated. In most cases you do not need to subclass this method. -####`loaded(callback)` +#### `loaded(callback)` *Introduced in version: 2.1.1.* @@ -111,7 +111,7 @@ loaded: function(callback) { } ```` -####`start()` +#### `start()` This method is called when all modules are loaded an the system is ready to boot up. Keep in mind that the dom object for the module is not yet created. The start method is a perfect place to define any additional module properties: **Example:** @@ -122,7 +122,7 @@ start: function() { } ```` -####`getScripts()` +#### `getScripts()` **Should return: Array** The getScripts method is called to request any additional scripts that need to be loaded. This method should therefore return an array with strings. If you want to return a full path to a file in the module folder, use the `this.file('filename.js')` method. In all cases the loader will only load a file once. It even checks if the file is available in the default vendor folder. @@ -142,7 +142,7 @@ getScripts: function() { **Note:** If a file can not be loaded, the boot up of the mirror will stall. Therefore it's advised not to use any external urls. -####`getStyles()` +#### `getStyles()` **Should return: Array** The getStyles method is called to request any additional stylesheets that need to be loaded. This method should therefore return an array with strings. If you want to return a full path to a file in the module folder, use the `this.file('filename.css')` method. In all cases the loader will only load a file once. It even checks if the file is available in the default vendor folder. @@ -161,7 +161,7 @@ getStyles: function() { ```` **Note:** If a file can not be loaded, the boot up of the mirror will stall. Therefore it's advised not to use any external urls. -####`getTranslations()` +#### `getTranslations()` **Should return: Dictionary** The getTranslations method is called to request translation files that need to be loaded. This method should therefore return a dictionary with the files to load, identified by the country's short name. @@ -179,7 +179,7 @@ getTranslations: function() { ```` -####`getDom()` +#### `getDom()` **Should return:** Dom Object Whenever the MagicMirror needs to update the information on screen (because it starts, or because your module asked a refresh using `this.updateDom()`), the system calls the getDom method. This method should therefore return a dom object. @@ -194,7 +194,7 @@ getDom: function() { ```` -####`getHeader()` +#### `getHeader()` **Should return:** String Whenever the MagicMirror needs to update the information on screen (because it starts, or because your module asked a refresh using `this.updateDom()`), the system calls the getHeader method to retrieve the module's header. This method should therefor return a string. If this method is not subclassed, this function will return the user's configured header. @@ -211,7 +211,7 @@ getHeader: function() { ```` -####`notificationReceived(notification, payload, sender)` +#### `notificationReceived(notification, payload, sender)` That MagicMirror core has the ability to send notifications to modules. Or even better: the modules have the possibility to send notifications to other modules. When this module is called, it has 3 arguments: @@ -237,7 +237,7 @@ notificationReceived: function(notification, payload, sender) { - `DOM_OBJECTS_CREATED` - All dom objects are created. The system is now ready to perform visual changes. -####`socketNotificationReceived: function(notification, payload)` +#### `socketNotificationReceived: function(notification, payload)` When using a node_helper, the node helper can send your module notifications. When this module is called, it has 2 arguments: - `notification` - String - The notification identifier. @@ -253,11 +253,11 @@ socketNotificationReceived: function(notification, payload) { }, ```` -####`suspend()` +#### `suspend()` When a module is hidden (using the `module.hide()` method), the `suspend()` method will be called. By subclassing this method you can perform tasks like halting the update timers. -####`resume()` -When a module will be shown after it was previously hidden (using the `module.show()` method), the `resume()` method will be called. By subclassing this method you can perform tasks restarting the update timers. +#### `resume()` +When a module is requested to be shown (using the `module.show()` method), the `resume()` method will be called. By subclassing this method you can perform tasks restarting the update timers. ### Module instance methods @@ -265,13 +265,13 @@ When a module will be shown after it was previously hidden (using the `module.sh Each module instance has some handy methods which can be helpful building your module. -####`this.file(filename)` +#### `this.file(filename)` ***filename* String** - The name of the file you want to create the path for.
**Returns String** If you want to create a path to a file in your module folder, use the `file()` method. It returns the path to the filename given as the attribute. Is method comes in handy when configuring the [getScripts](#getscripts) and [getStyles](#getstyles) methods. -####`this.updateDom(speed)` +#### `this.updateDom(speed)` ***speed* Number** - Optional. Animation speed in milliseconds.
Whenever your module need to be updated, call the `updateDom(speed)` method. It requests the MagicMirror core to update its dom object. If you define the speed, the content update will be animated, but only if the content will really change. @@ -289,7 +289,7 @@ start: function() { ... ```` -####`this.sendNotification(notification, payload)` +#### `this.sendNotification(notification, payload)` ***notification* String** - The notification identifier.
***payload* AnyType** - Optional. A notification payload.
@@ -300,7 +300,7 @@ If you want to send a notification to all other modules, use the `sendNotificati this.sendNotification('MYMODULE_READY_FOR_ACTION', {foo:bar}); ```` -####`this.sendSocketNotification(notification, payload)` +#### `this.sendSocketNotification(notification, payload)` ***notification* String** - The notification identifier.
***payload* AnyType** - Optional. A notification payload.
@@ -311,7 +311,7 @@ If you want to send a notification to the node_helper, use the `sendSocketNotifi this.sendSocketNotification('SET_CONFIG', this.config); ```` -####`this.hide(speed, callback, options)` +#### `this.hide(speed, callback, options)` ***speed* Number** - Optional (Required when setting callback or options), The speed of the hide animation in milliseconds. ***callback* Function** - Optional, The callback after the hide animation is finished. ***options* Function** - Optional, Object with additional options for the hide action (see below). (*Introduced in version: 2.1.0.*) @@ -328,7 +328,7 @@ Possible configurable options: **Note 3:** If the dom is not yet created, the hide method won't work. Wait for the `DOM_OBJECTS_CREATED` [notification](#notificationreceivednotification-payload-sender). -####`this.show(speed, callback, options)` +#### `this.show(speed, callback, options)` ***speed* Number** - Optional (Required when setting callback or options), The speed of the show animation in milliseconds. ***callback* Function** - Optional, The callback after the show animation is finished. ***options* Function** - Optional, Object with additional options for the show action (see below). (*Introduced in version: 2.1.0.*) @@ -344,7 +344,7 @@ Possible configurable options: **Note 2:** If the show animation is hijacked (an other method calls show on the same module), the callback will not be called.
**Note 3:** If the dom is not yet created, the show method won't work. Wait for the `DOM_OBJECTS_CREATED` [notification](#notificationreceivednotification-payload-sender). -####Visibility locking +#### Visibility locking (*Introduced in version: 2.1.0.*) @@ -401,7 +401,7 @@ Use this `force` method with caution. See `show()` method for more information. -####`this.translate(identifier)` +#### `this.translate(identifier)` ***identifier* String** - Identifier of the string that should be translated. The Magic Mirror contains a convenience wrapper for `l18n`. You can use this to automatically serve different translations for your modules based on the user's `language` configuration. @@ -429,6 +429,51 @@ this.translate("INFO") //Will return a translated string for the identifier INFO **Note:** although comments are officially not supported in JSON files, MagicMirror allows it by stripping the comments before parsing the JSON file. Comments in translation files could help other translators. +##### `this.translate(identifier, variables)` +***identifier* String** - Identifier of the string that should be translated. +***variables* Object** - Object of variables to be used in translation. + +This improved and backwards compatible way to handle translations behaves like the normal translation function and follows the rules described above. It's recommended to use this new format for translating everywhere. It allows translator to change the word order in the sentence to be translated. + + +**Example:** +````javascript +var timeUntilEnd = moment(event.endDate, "x").fromNow(true); +this.translate("RUNNING", { "timeUntilEnd": timeUntilEnd) }); // Will return a translated string for the identifier RUNNING, replacing `{timeUntilEnd}` with the contents of the variable `timeUntilEnd` in the order that translator intended. +```` + +**Example English .json file:** +````javascript +{ + "RUNNING": "Ends in {timeUntilEnd}", +} +```` + +**Example Finnish .json file:** +````javascript +{ + "RUNNING": "Päättyy {timeUntilEnd} päästä", +} +```` + +**Note:** The *variables* Object has an special case called `fallback`. It's used to support old translations in translation files that do not have the variables in them. If you are upgrading an old module that had translations that did not support the word order, it is recommended to have the fallback layout. + +**Example:** +````javascript +var timeUntilEnd = moment(event.endDate, "x").fromNow(true); +this.translate("RUNNING", { + "fallback": this.translate("RUNNING") + " {timeUntilEnd}" + "timeUntilEnd": timeUntilEnd +)}); // Will return a translated string for the identifier RUNNING, replacing `{timeUntilEnd}` with the contents of the variable `timeUntilEnd` in the order that translator intended. (has a fallback) +```` + +**Example swedish .json file that does not have the variable in it:** +````javascript +{ + "RUNNING": "Slutar", +} +```` +In this case the `translate`-function will not find any variables in the translation, will look for `fallback` variable and use that if possible to create the translation. ## The Node Helper: node_helper.js @@ -447,17 +492,17 @@ Of course, the above helper would not do anything useful. So with the informatio ### Available module instance properties -####`this.name` +#### `this.name` **String** The name of the module -####`this.path` +#### `this.path` **String** The path of the module -####`this.expressApp` +#### `this.expressApp` **Express App Instance** This is a link to the express instance. It will allow you to define extra routes. @@ -476,13 +521,13 @@ start: function() { this.expressApp.use("/" + this.name, express.static(this.path + "/public")); ```` -####`this.io` +#### `this.io` **Socket IO Instance** This is a link to the IO instance. It will allow you to do some Socket.IO magic. In most cases you won't need this, since the Node Helper has a few convenience methods to make this simple. -####'requiresVersion:' +#### `requiresVersion:` *Introduced in version: 2.1.0.* A string that defines the minimum version of the MagicMirror framework. If it is set, the system compares the required version with the users version. If the version of the user is out of date, it won't run the module. @@ -496,10 +541,10 @@ requiresVersion: "2.1.0", ### Subclassable module methods -####`init()` +#### `init()` This method is called when a node helper gets instantiated. In most cases you do not need to subclass this method. -####`start()` +#### `start()` This method is called when all node helpers are loaded and the system is ready to boot up. The start method is a perfect place to define any additional module properties: **Example:** @@ -510,7 +555,7 @@ start: function() { } ```` -####`socketNotificationReceived: function(notification, payload)` +#### `socketNotificationReceived: function(notification, payload)` With this method, your node helper can receive notifications from your modules. When this method is called, it has 2 arguments: - `notification` - String - The notification identifier. @@ -529,7 +574,7 @@ socketNotificationReceived: function(notification, payload) { Each node helper has some handy methods which can be helpful building your module. -####`this.sendSocketNotification(notification, payload)` +#### `this.sendSocketNotification(notification, payload)` ***notification* String** - The notification identifier.
***payload* AnyType** - Optional. A notification payload.
@@ -549,7 +594,7 @@ The core Magic Mirror object: `MM` has some handy method that will help you in c ### Module selection The only additional method available for your module, is the feature to retrieve references to other modules. This can be used to hide and show other modules. -####`MM.getModules()` +#### `MM.getModules()` **Returns Array** - An array with module instances.
To make a selection of all currently loaded module instances, run the `MM.getModules()` method. It will return an array with all currently loaded module instances. The returned array has a lot of filtering methods. See below for more info. @@ -557,7 +602,7 @@ To make a selection of all currently loaded module instances, run the `MM.getMod **Note:** This method returns an empty array if not all modules are started yet. Wait for the `ALL_MODULES_STARTED` [notification](#notificationreceivednotification-payload-sender). -#####`.withClass(classnames)` +##### `.withClass(classnames)` ***classnames* String or Array** - The class names on which you want to filter. **Returns Array** - An array with module instances.
@@ -570,7 +615,7 @@ var modules = MM.getModules().withClass('classname1 classname2'); var modules = MM.getModules().withClass(['classname1','classname2']); ```` -#####`.exceptWithClass(classnames)` +##### `.exceptWithClass(classnames)` ***classnames* String or Array** - The class names of the modules you want to remove from the results. **Returns Array** - An array with module instances.
@@ -583,7 +628,7 @@ var modules = MM.getModules().exceptWithClass('classname1 classname2'); var modules = MM.getModules().exceptWithClass(['classname1','classname2']); ```` -#####`.exceptModule(module)` +##### `.exceptModule(module)` ***module* Module Object** - The reference to a module you want to remove from the results. **Returns Array** - An array with module instances.
@@ -601,7 +646,7 @@ Of course, you can combine all of the above filters: var modules = MM.getModules().withClass('classname1').exceptwithClass('classname2').exceptModule(aModule); ```` -#####`.enumerate(callback)` +##### `.enumerate(callback)` ***callback* Function(module)** - The callback run on every instance. If you want to perform an action on all selected modules, you can use the `enumerate` function: diff --git a/modules/default/alert/alert.js b/modules/default/alert/alert.js index 787a0b4a..c5d3e650 100644 --- a/modules/default/alert/alert.js +++ b/modules/default/alert/alert.js @@ -30,7 +30,8 @@ Module.register("alert",{ getTranslations: function() { return { en: "translations/en.json", - de: "translations/de.json" + de: "translations/de.json", + nl: "translations/nl.json", }; }, show_notification: function(message) { diff --git a/modules/default/alert/translations/nl.json b/modules/default/alert/translations/nl.json new file mode 100644 index 00000000..9cda9089 --- /dev/null +++ b/modules/default/alert/translations/nl.json @@ -0,0 +1,4 @@ +{ + "sysTitle": "MagicMirror Notificatie", + "welcome": "Welkom, Succesvol gestart!" +} diff --git a/modules/default/calendar/README.md b/modules/default/calendar/README.md index 470560ba..8ce9608b 100644 --- a/modules/default/calendar/README.md +++ b/modules/default/calendar/README.md @@ -31,6 +31,7 @@ The following properties can be configured: | `displaySymbol` | Display a symbol in front of an entry.

**Possible values:** `true` or `false`
**Default value:** `true` | `defaultSymbol` | The default symbol.

**Possible values:** See [Font Awsome](http://fontawesome.io/icons/) website.
**Default value:** `calendar` | `maxTitleLength` | The maximum title length.

**Possible values:** `10` - `50`
**Default value:** `25` +| `wrapEvents` | Wrap event titles to multiple lines. Breaks lines at the length defined by `maxTitleLength`.

**Possible values:** `true` or `false`
**Default value:** `false` | `fetchInterval` | How often does the content needs to be fetched? (Milliseconds)

**Possible values:** `1000` - `86400000`
**Default value:** `300000` (5 minutes) | `animationSpeed` | Speed of the update animation. (Milliseconds)

**Possible values:**`0` - `5000`
**Default value:** `2000` (2 seconds) | `fade` | Fade the future events to black. (Gradient)

**Possible values:** `true` or `false`
**Default value:** `true` @@ -39,6 +40,7 @@ The following properties can be configured: | `titleReplace` | An object of textual replacements applied to the tile of the event. This allow to remove or replace certains words in the title.

**Example:** `{'Birthday of ' : '', 'foo':'bar'}`
**Default value:** `{ "De verjaardag van ": "", "'s birthday": "" }` | `displayRepeatingCountTitle` | Show count title for yearly repeating events (e.g. "X. Birthday", "X. Anniversary")

**Possible values:** `true` or `false`
**Default value:** `false` | `dateFormat` | Format to use for the date of events (when using absolute dates)

**Possible values:** See [Moment.js formats](http://momentjs.com/docs/#/parsing/string-format/)
**Default value:** `MMM Do` (e.g. Jan 18th) +| `fullDayEventDateFormat` | Format to use for the date of full day events (when using absolute dates)

**Possible values:** See [Moment.js formats](http://momentjs.com/docs/#/parsing/string-format/)
**Default value:** `MMM Do` (e.g. Jan 18th) | `timeFormat` | Display event times as absolute dates, or relative time

**Possible values:** `absolute` or `relative`
**Default value:** `relative` | `getRelative` | How much time (in hours) should be left until calendar events start getting relative?

**Possible values:** `0` (events stay absolute) - `48` (48 hours before the event starts)
**Default value:** `6` | `urgency` | When using a timeFormat of `absolute`, the `urgency` setting allows you to display events within a specific time frame as `relative`. This allows events within a certain time frame to be displayed as relative (in xx days) while others are displayed as absolute dates

**Possible values:** a positive integer representing the number of days for which you want a relative date, for example `7` (for 7 days)

**Default value:** `7` diff --git a/modules/default/calendar/calendar.css b/modules/default/calendar/calendar.css index 26b1e93d..6bc5762d 100644 --- a/modules/default/calendar/calendar.css +++ b/modules/default/calendar/calendar.css @@ -2,6 +2,7 @@ padding-left: 0; padding-right: 10px; font-size: 80%; + vertical-align: top; } .calendar .symbol span { @@ -19,4 +20,5 @@ .calendar .time { padding-left: 30px; text-align: right; + vertical-align: top; } diff --git a/modules/default/calendar/calendar.js b/modules/default/calendar/calendar.js index d2e64cc7..ad3be8ce 100644 --- a/modules/default/calendar/calendar.js +++ b/modules/default/calendar/calendar.js @@ -18,12 +18,14 @@ Module.register("calendar", { displayRepeatingCountTitle: false, defaultRepeatingCountTitle: "", maxTitleLength: 25, + wrapEvents: false, // wrap events to multiple lines breaking at maxTitleLength fetchInterval: 5 * 60 * 1000, // Update every 5 minutes. animationSpeed: 2000, fade: true, urgency: 7, timeFormat: "relative", dateFormat: "MMM Do", + fullDayEventDateFormat: "MMM Do", getRelative: 6, fadePoint: 0.25, // Start on 1/4th of the list. hidePrivate: false, @@ -54,8 +56,8 @@ Module.register("calendar", { // Define required translations. getTranslations: function () { - // The translations for the defaut modules are defined in the core translation files. - // Therefor we can just return false. Otherwise we should have returned a dictionairy. + // 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. return false; }, @@ -65,7 +67,7 @@ Module.register("calendar", { Log.log("Starting module: " + this.name); // Set locale. - moment.locale(config.language); + moment.updateLocale(config.language, this.getLocaleSpecification(config.timeFormat)); for (var c in this.config.calendars) { var calendar = this.config.calendars[c]; @@ -77,7 +79,9 @@ Module.register("calendar", { }; // we check user and password here for backwards compatibility with old configs - if(calendar.user && calendar.pass){ + 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"); calendar.auth = { user: calendar.user, pass: calendar.pass @@ -128,20 +132,6 @@ Module.register("calendar", { for (var e in events) { var event = events[e]; - - var excluded = false; - for (var f in this.config.excludedEvents) { - var filter = this.config.excludedEvents[f]; - if (event.title.toLowerCase().includes(filter.toLowerCase())) { - excluded = true; - break; - } - } - - if (excluded) { - continue; - } - var eventWrapper = document.createElement("tr"); if (this.config.colored) { @@ -172,7 +162,6 @@ Module.register("calendar", { var titleWrapper = document.createElement("td"), repeatingCountTitle = ""; - if (this.config.displayRepeatingCountTitle) { repeatingCountTitle = this.countTitleForUrl(event.url); @@ -227,7 +216,7 @@ Module.register("calendar", { // This event falls within the config.urgency period that the user has set timeWrapper.innerHTML = this.capFirst(moment(event.startDate, "x").fromNow()); } else { - timeWrapper.innerHTML = this.capFirst(moment(event.startDate, "x").format(this.config.dateFormat)); + timeWrapper.innerHTML = this.capFirst(moment(event.startDate, "x").format(this.config.fullDayEventDateFormat)); } } else { timeWrapper.innerHTML = this.capFirst(moment(event.startDate, "x").fromNow()); @@ -264,7 +253,12 @@ Module.register("calendar", { } } } else { - timeWrapper.innerHTML = this.capFirst(this.translate("RUNNING")) + " " + moment(event.endDate, "x").fromNow(true); + timeWrapper.innerHTML = this.capFirst( + this.translate("RUNNING", { + fallback: this.translate("RUNNING") + " {timeUntilEnd}", + timeUntilEnd: moment(event.endDate, "x").fromNow(true) + }) + ); } } //timeWrapper.innerHTML += ' - '+ moment(event.startDate,'x').format('lll'); @@ -291,6 +285,31 @@ Module.register("calendar", { return wrapper; }, + /** + * This function accepts a number (either 12 or 24) and returns a moment.js LocaleSpecification with the + * corresponding timeformat to be used in the calendar display. If no number is given (or otherwise invalid input) + * it will a localeSpecification object with the system locale time format. + * + * @param {number} timeFormat Specifies either 12 or 24 hour time format + * @returns {moment.LocaleSpecification} + */ + getLocaleSpecification: function(timeFormat) { + switch (timeFormat) { + case 12: { + return { longDateFormat: {LT: "h:mm A"} }; + break; + } + case 24: { + return { longDateFormat: {LT: "HH:mm"} }; + break; + } + default: { + return { longDateFormat: {LT: moment.localeData().longDateFormat("LT")} }; + break; + } + } + }, + /* hasCalendarURL(url) * Check if this config contains the calendar url. * @@ -337,7 +356,7 @@ Module.register("calendar", { return a.startDate - b.startDate; }); - return events.slice(0, this.config.maximumEntries); + return events; }, /* createEventList(url) @@ -348,6 +367,7 @@ Module.register("calendar", { addCalendar: function (url, auth, calendarConfig) { this.sendSocketNotification("ADD_CALENDAR", { url: url, + excludedEvents: calendarConfig.excludedEvents || this.config.excludedEvents, maximumEntries: calendarConfig.maximumEntries || this.config.maximumEntries, maximumNumberOfDays: calendarConfig.maximumNumberOfDays || this.config.maximumNumberOfDays, fetchInterval: this.config.fetchInterval, @@ -408,21 +428,46 @@ Module.register("calendar", { return defaultValue; }, - /* shorten(string, maxLength) - * Shortens a string if it's longer than maxLenthg. - * Adds an ellipsis to the end. - * - * argument string string - The string to shorten. - * argument maxLength number - The max lenth of the string. - * - * return string - The shortened string. + /** + * Shortens a string if it's longer than maxLength and add a ellipsis to the end + * + * @param {string} string Text string to shorten + * @param {number} maxLength The max length of the string + * @param {boolean} wrapEvents Wrap the text after the line has reached maxLength + * @returns {string} The shortened string */ - shorten: function (string, maxLength) { - if (string.length > maxLength) { - return string.slice(0, maxLength) + "…"; + shorten: function (string, maxLength, wrapEvents) { + if (typeof string !== "string") { + return ""; } - return string; + if (wrapEvents === true) { + var temp = ""; + var currentLine = ""; + var words = string.split(" "); + + for (var i = 0; i < words.length; i++) { + var word = words[i]; + if (currentLine.length + word.length < (typeof maxLength === "number" ? maxLength : 25) - 1) { // max - 1 to account for a space + currentLine += (word + " "); + } else { + if (currentLine.length > 0) { + temp += (currentLine + "
" + word + " "); + } else { + temp += (word + "
"); + } + currentLine = ""; + } + } + + return (temp + currentLine).trim(); + } else { + if (maxLength && typeof maxLength === "number" && string.length > maxLength) { + return string.trim().slice(0, maxLength) + "…"; + } else { + return string.trim(); + } + } }, /* capFirst(string) @@ -437,7 +482,7 @@ Module.register("calendar", { /* titleTransform(title) * Transforms the title of an event for usage. * Replaces parts of the text as defined in config.titleReplace. - * Shortens title based on config.maxTitleLength + * Shortens title based on config.maxTitleLength and config.wrapEvents * * argument title string - The title to transform. * @@ -456,7 +501,7 @@ Module.register("calendar", { title = title.replace(needle, replacement); } - title = this.shorten(title, this.config.maxTitleLength); + title = this.shorten(title, this.config.maxTitleLength, this.config.wrapEvents); return title; }, @@ -466,10 +511,12 @@ Module.register("calendar", { */ broadcastEvents: function () { var eventList = []; - for (url in this.calendarData) { + for (var url in this.calendarData) { var calendar = this.calendarData[url]; - for (e in calendar) { + for (var e in calendar) { var event = cloneObject(calendar[e]); + event.symbol = this.symbolsForUrl(url); + event.color = this.colorForUrl(url); delete event.url; eventList.push(event); } diff --git a/modules/default/calendar/calendarfetcher.js b/modules/default/calendar/calendarfetcher.js index 9655f21e..12495f78 100644 --- a/modules/default/calendar/calendarfetcher.js +++ b/modules/default/calendar/calendarfetcher.js @@ -8,7 +8,7 @@ var ical = require("./vendor/ical.js"); var moment = require("moment"); -var CalendarFetcher = function(url, reloadInterval, maximumEntries, maximumNumberOfDays, auth) { +var CalendarFetcher = function(url, reloadInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth) { var self = this; var reloadTimer = null; @@ -113,6 +113,19 @@ var CalendarFetcher = function(url, reloadInterval, maximumEntries, maximumNumbe title = event.description; } + var excluded = false; + for (var f in excludedEvents) { + var filter = excludedEvents[f]; + if (title.toLowerCase().includes(filter.toLowerCase())) { + excluded = true; + break; + } + } + + if (excluded) { + continue; + } + var location = event.location || false; var geo = event.geo || false; var description = event.description || false; diff --git a/modules/default/calendar/node_helper.js b/modules/default/calendar/node_helper.js index 90c286c8..25e7f1f7 100644 --- a/modules/default/calendar/node_helper.js +++ b/modules/default/calendar/node_helper.js @@ -24,7 +24,7 @@ module.exports = NodeHelper.create({ socketNotificationReceived: function(notification, payload) { if (notification === "ADD_CALENDAR") { //console.log('ADD_CALENDAR: '); - this.createFetcher(payload.url, payload.fetchInterval, payload.maximumEntries, payload.maximumNumberOfDays, payload.auth); + this.createFetcher(payload.url, payload.fetchInterval, payload.excludedEvents, payload.maximumEntries, payload.maximumNumberOfDays, payload.auth); } }, @@ -36,7 +36,7 @@ module.exports = NodeHelper.create({ * attribute reloadInterval number - Reload interval in milliseconds. */ - createFetcher: function(url, fetchInterval, maximumEntries, maximumNumberOfDays, auth) { + createFetcher: function(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth) { var self = this; if (!validUrl.isUri(url)) { @@ -47,7 +47,7 @@ module.exports = NodeHelper.create({ var fetcher; if (typeof self.fetchers[url] === "undefined") { console.log("Create new calendar fetcher for url: " + url + " - Interval: " + fetchInterval); - fetcher = new CalendarFetcher(url, fetchInterval, maximumEntries, maximumNumberOfDays, auth); + fetcher = new CalendarFetcher(url, fetchInterval, excludedEvents, maximumEntries, maximumNumberOfDays, auth); fetcher.onReceive(function(fetcher) { //console.log('Broadcast events.'); diff --git a/modules/default/clock/README.md b/modules/default/clock/README.md index f518a2b2..a231d73c 100644 --- a/modules/default/clock/README.md +++ b/modules/default/clock/README.md @@ -30,6 +30,7 @@ The following properties can be configured: | `showPeriodUpper` | Show the period (AM/PM) with 12 hour format as uppercase.

**Possible values:** `true` or `false`
**Default value:** `false` | `clockBold` | Remove the colon and bold the minutes to make a more modern look.

**Possible values:** `true` or `false`
**Default value:** `false` | `showDate` | Turn off or on the Date section.

**Possible values:** `true` or `false`
**Default value:** `true` +| `showWeek` | Turn off or on the Week section.

**Possible values:** `true` or `false`
**Default value:** `false` | `dateFormat` | Configure the date format as you like.

**Possible values:** [Docs](http://momentjs.com/docs/#/displaying/format/)
**Default value:** `"dddd, LL"` | `displayType` | Display a digital clock, analog clock, or both together.

**Possible values:** `digital`, `analog`, or `both`
**Default value:** `digital` | `analogSize` | **Specific to the analog clock.** Defines how large the analog display is.

**Possible values:** A positive number of pixels`
**Default value:** `200px` @@ -37,4 +38,4 @@ The following properties can be configured: | `secondsColor` | **Specific to the analog clock.** Specifies what color to make the 'seconds' hand.

**Possible values:** `any HTML RGB Color`
**Default value:** `#888888` | `analogPlacement` | **Specific to the analog clock. _(requires displayType set to `'both'`)_** Specifies where the analog clock is in relation to the digital clock

**Possible values:** `top`, `right`, `bottom`, or `left`
**Default value:** `bottom` | `analogShowDate` | **Specific to the analog clock.** If the clock is used as a separate module and set to analog only, this configures whether a date is also displayed with the clock.

**Possible values:** `false`, `top`, or `bottom`
**Default value:** `top` -| `timezone` | Specific a timezone to show clock.

**Possible examples values:** `America/New_York`, `America/Santiago`, `Etc/GMT+10`
**Default value:** `none` +| `timezone` | Specific a timezone to show clock.

**Possible examples values:** `America/New_York`, `America/Santiago`, `Etc/GMT+10`
**Default value:** `none`. See more informations about configuration value [here](https://momentjs.com/timezone/docs/#/data-formats/packed-format/) diff --git a/modules/default/clock/clock.js b/modules/default/clock/clock.js index 21e665e7..9a0f57d7 100644 --- a/modules/default/clock/clock.js +++ b/modules/default/clock/clock.js @@ -16,6 +16,7 @@ Module.register("clock",{ showPeriodUpper: false, clockBold: false, showDate: true, + showWeek: false, dateFormat: "dddd, LL", /* specific to the analog clock */ @@ -61,10 +62,12 @@ Module.register("clock",{ var timeWrapper = document.createElement("div"); var secondsWrapper = document.createElement("sup"); var periodWrapper = document.createElement("span"); + var weekWrapper = document.createElement("div") // Style Wrappers dateWrapper.className = "date normal medium"; timeWrapper.className = "time bright large light"; secondsWrapper.className = "dimmed"; + weekWrapper.className = "week dimmed medium" // Set content of wrappers. // The moment().format("h") method has a bug on the Raspberry Pi. @@ -90,6 +93,9 @@ Module.register("clock",{ if(this.config.showDate){ dateWrapper.innerHTML = now.format(this.config.dateFormat); } + if (this.config.showWeek) { + weekWrapper.innerHTML = this.translate("WEEK") + " " + now.week(); + } timeWrapper.innerHTML = timeString; secondsWrapper.innerHTML = now.format("ss"); if (this.config.showPeriodUpper) { @@ -121,7 +127,6 @@ Module.register("clock",{ hour = ((now.hours() % 12) / 12) * 360 + 90 + minute / 12; // Create wrappers - var wrapper = document.createElement("div"); var clockCircle = document.createElement("div"); clockCircle.className = "clockCircle"; clockCircle.style.width = this.config.analogSize; @@ -172,16 +177,24 @@ Module.register("clock",{ // Display only a digital clock wrapper.appendChild(dateWrapper); wrapper.appendChild(timeWrapper); + wrapper.appendChild(weekWrapper); } else if (this.config.displayType === "analog") { // Display only an analog clock - dateWrapper.style.textAlign = "center"; - dateWrapper.style.paddingBottom = "15px"; + + if (this.config.showWeek) { + weekWrapper.style.paddingBottom = "15px"; + } else { + dateWrapper.style.paddingBottom = "15px"; + } + if (this.config.analogShowDate === "top") { wrapper.appendChild(dateWrapper); + wrapper.appendChild(weekWrapper); wrapper.appendChild(clockCircle); } else if (this.config.analogShowDate === "bottom") { wrapper.appendChild(clockCircle); wrapper.appendChild(dateWrapper); + wrapper.appendChild(weekWrapper); } else { wrapper.appendChild(clockCircle); } @@ -198,6 +211,7 @@ Module.register("clock",{ digitalWrapper.style.cssFloat = "none"; digitalWrapper.appendChild(dateWrapper); digitalWrapper.appendChild(timeWrapper); + digitalWrapper.appendChild(weekWrapper); var appendClocks = function(condition, pos1, pos2) { var padding = [0,0,0,0]; diff --git a/modules/default/compliments/README.md b/modules/default/compliments/README.md index 171c86c0..10a45b8f 100644 --- a/modules/default/compliments/README.md +++ b/modules/default/compliments/README.md @@ -13,7 +13,7 @@ modules: [ // Best results in one of the middle regions like: lower_third config: { // The config property is optional. - // If no config is set, an example calendar is shown. + // If no config is set, the default compliments are shown. // See 'Configuration options' for more information. } } @@ -31,6 +31,7 @@ The following properties can be configured: | `fadeSpeed` | Speed of the update animation. (Milliseconds)

**Possible values:**`0` - `5000`
**Default value:** `4000` (4 seconds) | `compliments` | The list of compliments.

**Possible values:** An object with four arrays: `morning`, `afternoon`, `evening` and `anytime`. See _compliment configuration_ below.
**Default value:** See _compliment configuration_ below. | `remoteFile` | External file from which to load the compliments

**Possible values:** Path to a JSON file containing compliments, configured as per the value of the _compliments configuration_ (see below). An object with four arrays: `morning`, `afternoon`, `evening` and `anytime`. - `compliments.json`
**Default value:** `null` (Do not load from file) +| `classes` | Override the CSS classes of the div showing the compliments

**Default value:** `thin xlarge bright` ### Compliment configuration @@ -88,7 +89,7 @@ config: { ], afternoon: [ "Hello, beauty!", - 'You look sexy!', + "You look sexy!", "Looking good today!" ], evening: [ @@ -110,9 +111,9 @@ around them ("morning", "afternoon", "evening", "snow", "rain", etc.). #### Example compliments.json file: ````json { - "anytime" : [ - "Hey there sexy!" - ], + "anytime" : [ + "Hey there sexy!" + ], "morning" : [ "Good morning, sunshine!", "Who needs coffee when you have your smile?", diff --git a/modules/default/compliments/compliments.js b/modules/default/compliments/compliments.js index b9f2011e..a0af458d 100644 --- a/modules/default/compliments/compliments.js +++ b/modules/default/compliments/compliments.js @@ -96,14 +96,14 @@ Module.register("compliments", { */ complimentArray: function() { var hour = moment().hour(); - var compliments = null; + var compliments; - if (hour >= 3 && hour < 12) { - compliments = this.config.compliments.morning; - } else if (hour >= 12 && hour < 17) { - compliments = this.config.compliments.afternoon; - } else { - compliments = this.config.compliments.evening; + if (hour >= 3 && hour < 12 && this.config.compliments.hasOwnProperty("morning")) { + compliments = this.config.compliments.morning.slice(0); + } else if (hour >= 12 && hour < 17 && this.config.compliments.hasOwnProperty("afternoon")) { + compliments = this.config.compliments.afternoon.slice(0); + } else if(this.config.compliments.hasOwnProperty("evening")) { + compliments = this.config.compliments.evening.slice(0); } if (typeof compliments === "undefined") { @@ -117,7 +117,6 @@ Module.register("compliments", { compliments.push.apply(compliments, this.config.compliments.anytime); return compliments; - }, /* complimentFile(callback) diff --git a/modules/default/currentweather/README.md b/modules/default/currentweather/README.md index d70ec297..c5ba6108 100644 --- a/modules/default/currentweather/README.md +++ b/modules/default/currentweather/README.md @@ -40,7 +40,9 @@ The following properties can be configured: | `showPeriod` | Show the period (am/pm) with 12 hour format

**Possible values:** `true` or `false`
**Default value:** `true` | `showPeriodUpper` | Show the period (AM/PM) with 12 hour format as uppercase

**Possible values:** `true` or `false`
**Default value:** `false` | `showWindDirection` | Show the wind direction next to the wind speed.

**Possible values:** `true` or `false`
**Default value:** `true` +| `showWindDirectionAsArrow` | Show the wind direction as an arrow instead of abbreviation

**Possible values:** `true` or `false`
**Default value:** `false` | `showHumidity` | Show the current humidity

**Possible values:** `true` or `false`
**Default value:** `false` +| `showIndoorTemperature` | If you have another module that emits the INDOOR_TEMPERATURE notification, the indoor temperature will be displayed
**Default value:** `false` | `onlyTemp` | Show only current Temperature and weather icon.

**Possible values:** `true` or `false`
**Default value:** `false` | `useBeaufort` | Pick between using the Beaufort scale for wind speed or using the default units.

**Possible values:** `true` or `false`
**Default value:** `true` | `lang` | The language of the days.

**Possible values:** `en`, `nl`, `ru`, etc ...
**Default value:** uses value of _config.language_ diff --git a/modules/default/currentweather/currentweather.css b/modules/default/currentweather/currentweather.css index a40be878..b7669bda 100644 --- a/modules/default/currentweather/currentweather.css +++ b/modules/default/currentweather/currentweather.css @@ -1,4 +1,5 @@ -.currentweather .weathericon { +.currentweather .weathericon, +.currentweather .fa-home { font-size: 75%; line-height: 65px; display: inline-block; diff --git a/modules/default/currentweather/currentweather.js b/modules/default/currentweather/currentweather.js index 1b55e255..95c9a3ad 100644 --- a/modules/default/currentweather/currentweather.js +++ b/modules/default/currentweather/currentweather.js @@ -21,10 +21,12 @@ Module.register("currentweather",{ showPeriod: true, showPeriodUpper: false, showWindDirection: true, + showWindDirectionAsArrow: false, useBeaufort: true, lang: config.language, showHumidity: false, degreeLabel: false, + showIndoorTemperature: false, initialLoadDelay: 0, // 0 seconds delay retryDelay: 2500, @@ -79,8 +81,8 @@ Module.register("currentweather",{ // Define required translations. getTranslations: function() { - // The translations for the defaut modules are defined in the core translation files. - // Therefor we can just return false. Otherwise we should have returned a dictionairy. + // 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 yiur own module including translations, check out the documentation. return false; }, @@ -94,9 +96,11 @@ Module.register("currentweather",{ this.windSpeed = null; this.windDirection = null; + this.windDeg = null; this.sunriseSunsetTime = null; this.sunriseSunsetIcon = null; this.temperature = null; + this.indoorTemperature = null; this.weatherType = null; this.loaded = false; @@ -111,7 +115,6 @@ Module.register("currentweather",{ var small = document.createElement("div"); small.className = "normal medium"; - var windIcon = document.createElement("span"); windIcon.className = "wi wi-strong-wind dimmed"; small.appendChild(windIcon); @@ -122,7 +125,13 @@ Module.register("currentweather",{ if (this.config.showWindDirection) { var windDirection = document.createElement("sup"); - windDirection.innerHTML = " " + this.translate(this.windDirection); + if (this.config.showWindDirectionAsArrow) { + if(this.windDeg !== null) { + windDirection.innerHTML = "   "; + } + } else { + windDirection.innerHTML = " " + this.translate(this.windDirection); + } small.appendChild(windDirection); } var spacer = document.createElement("span"); @@ -203,6 +212,17 @@ Module.register("currentweather",{ temperature.innerHTML = " " + this.temperature + "°" + degreeLabel; large.appendChild(temperature); + if (this.config.showIndoorTemperature && this.indoorTemperature) { + var indoorIcon = document.createElement("span"); + indoorIcon.className = "fa fa-home"; + large.appendChild(indoorIcon); + + var indoorTemperatureElem = document.createElement("span"); + indoorTemperatureElem.className = "bright"; + indoorTemperatureElem.innerHTML = " " + this.indoorTemperature + "°" + degreeLabel; + large.appendChild(indoorTemperatureElem); + } + wrapper.appendChild(large); return wrapper; }, @@ -226,10 +246,9 @@ Module.register("currentweather",{ if (notification === "CALENDAR_EVENTS") { var senderClasses = sender.data.classes.toLowerCase().split(" "); if (senderClasses.indexOf(this.config.calendarClass.toLowerCase()) !== -1) { - var lastEvent = this.firstEvent; this.firstEvent = false; - for (e in payload) { + for (var e in payload) { var event = payload[e]; if (event.location || event.geo) { this.firstEvent = event; @@ -239,6 +258,10 @@ Module.register("currentweather",{ } } } + if (notification === "INDOOR_TEMPERATURE") { + this.indoorTemperature = this.roundValue(payload); + this.updateDom(self.config.animationSpeed); + } }, /* updateWeather(compliments) @@ -323,12 +346,12 @@ Module.register("currentweather",{ if (this.config.useBeaufort){ this.windSpeed = this.ms2Beaufort(this.roundValue(data.wind.speed)); - }else { + } else { this.windSpeed = parseFloat(data.wind.speed).toFixed(0); } - this.windDirection = this.deg2Cardinal(data.wind.deg); + this.windDeg = data.wind.deg; this.weatherType = this.config.iconTable[data.weather[0].icon]; var now = new Date(); @@ -359,7 +382,6 @@ Module.register("currentweather",{ this.sunriseSunsetTime = timeString; this.sunriseSunsetIcon = (sunrise < now && sunset > now) ? "wi-sunset" : "wi-sunrise"; - this.show(this.config.animationSpeed, {lockString:this.identifier}); this.loaded = true; this.updateDom(this.config.animationSpeed); @@ -386,6 +408,10 @@ Module.register("currentweather",{ /* ms2Beaufort(ms) * Converts m2 to beaufort (windspeed). * + * see: + * http://www.spc.noaa.gov/faq/tornado/beaufort.html + * https://en.wikipedia.org/wiki/Beaufort_scale#Modern_scale + * * argument ms number - Windspeed in m/s. * * return number - Windspeed in beaufort. @@ -443,7 +469,7 @@ Module.register("currentweather",{ * * argument temperature number - Temperature. * - * return number - Rounded Temperature. + * return string - Rounded Temperature. */ roundValue: function(temperature) { var decimals = this.config.roundTemp ? 0 : 1; diff --git a/modules/default/newsfeed/README.md b/modules/default/newsfeed/README.md index 9f7b2e7d..7c4ad48d 100644 --- a/modules/default/newsfeed/README.md +++ b/modules/default/newsfeed/README.md @@ -70,6 +70,8 @@ The following properties can be configured: | `updateInterval` | How often do you want to display a new headline? (Milliseconds)

**Possible values:**`1000` - `60000`
**Default value:** `10000` (10 seconds) | `animationSpeed` | Speed of the update animation. (Milliseconds)

**Possible values:**`0` - `5000`
**Default value:** `2500` (2.5 seconds) | `maxNewsItems` | Total amount of news items to cycle through. (0 for unlimited)

**Possible values:**`0` - `...`
**Default value:** `0` +| `ignoreOldItems` | Ignore news items that are outdated.

**Possible values:**`true` or `false
**Default value:** `false` +| `ignoreOlderThan` | How old should news items be before they are considered outdated? (Milliseconds)

**Possible values:**`1` - `...`
**Default value:** `86400000` (1 day) | `removeStartTags` | Some newsfeeds feature tags at the **beginning** of their titles or descriptions, such as _[VIDEO]_. This setting allows for the removal of specified tags from the beginning of an item's description and/or title.

**Possible values:**`'title'`, `'description'`, `'both'` | `startTags` | List the tags you would like to have removed at the beginning of the feed item

**Possible values:** `['TAG']` or `['TAG1','TAG2',...]` | `removeEndTags` | Remove specified tags from the **end** of an item's description and/or title.

**Possible values:**`'title'`, `'description'`, `'both'` diff --git a/modules/default/newsfeed/newsfeed.js b/modules/default/newsfeed/newsfeed.js index 5094355e..b230fdb1 100644 --- a/modules/default/newsfeed/newsfeed.js +++ b/modules/default/newsfeed/newsfeed.js @@ -28,6 +28,8 @@ Module.register("newsfeed",{ updateInterval: 10 * 1000, animationSpeed: 2.5 * 1000, maxNewsItems: 0, // 0 for unlimited + ignoreOldItems: false, + ignoreOlderThan: 24 * 60 * 60 * 1000, // 1 day removeStartTags: "", removeEndTags: "", startTags: [], @@ -42,9 +44,9 @@ Module.register("newsfeed",{ // Define required translations. getTranslations: function() { - // The translations for the defaut modules are defined in the core translation files. - // Therefor we can just return false. Otherwise we should have returned a dictionairy. - // If you're trying to build yiur own module including translations, check out the documentation. + // 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. return false; }, @@ -202,7 +204,6 @@ Module.register("newsfeed",{ /* registerFeeds() * registers the feeds to be used by the backend. */ - registerFeeds: function() { for (var f in this.config.feeds) { var feed = this.config.feeds[f]; @@ -213,10 +214,10 @@ Module.register("newsfeed",{ } }, - /* registerFeeds() + /* generateFeed() * Generate an ordered list of items for this configured module. * - * attribute feeds object - An object with feeds returned by the nod helper. + * attribute feeds object - An object with feeds returned by the node helper. */ generateFeed: function(feeds) { var newsItems = []; @@ -226,7 +227,9 @@ Module.register("newsfeed",{ for (var i in feedItems) { var item = feedItems[i]; item.sourceTitle = this.titleForFeed(feed); - newsItems.push(item); + if (!(this.config.ignoreOldItems && ((Date.now() - new Date(item.pubdate)) > this.config.ignoreOlderThan))) { + newsItems.push(item); + } } } } @@ -258,7 +261,7 @@ Module.register("newsfeed",{ return false; }, - /* subscribedToFeed(feedUrl) + /* titleForFeed(feedUrl) * Returns title for a specific feed Url. * * attribute feedUrl string - Url of the feed to check. diff --git a/modules/default/newsfeed/node_helper.js b/modules/default/newsfeed/node_helper.js index e5243304..af1d32b8 100644 --- a/modules/default/newsfeed/node_helper.js +++ b/modules/default/newsfeed/node_helper.js @@ -24,14 +24,13 @@ module.exports = NodeHelper.create({ } }, - /* createFetcher(url, reloadInterval) - * Creates a fetcher for a new url if it doesn't exist yet. - * Otherwise it reoses the existing one. + /* createFetcher(feed, config) + * Creates a fetcher for a new feed if it doesn't exist yet. + * Otherwise it reuses the existing one. * - * attribute url string - URL of the news feed. - * attribute reloadInterval number - Reload interval in milliseconds. + * attribute feed object - A feed object. + * attribute config object - A configuration object containing reload interval in milliseconds. */ - createFetcher: function(feed, config) { var self = this; diff --git a/modules/default/updatenotification/updatenotification.js b/modules/default/updatenotification/updatenotification.js index f663f593..bf7ec2c1 100644 --- a/modules/default/updatenotification/updatenotification.js +++ b/modules/default/updatenotification/updatenotification.js @@ -11,11 +11,11 @@ Module.register("updatenotification", { }, - notificationReceived: function(notification, payload, sender) { + notificationReceived: function (notification, payload, sender) { if (notification === "DOM_OBJECTS_CREATED") { this.sendSocketNotification("CONFIG", this.config); this.sendSocketNotification("MODULES", Module.definitions); - this.hide(0,{lockString: self.identifier}); + this.hide(0, { lockString: self.identifier }); } }, @@ -26,11 +26,11 @@ Module.register("updatenotification", { } }, - updateUI: function() { + updateUI: function () { var self = this; if (this.status && this.status.behind > 0) { self.updateDom(0); - self.show(1000, {lockString: self.identifier}); + self.show(1000, { lockString: self.identifier }); } }, @@ -59,8 +59,8 @@ Module.register("updatenotification", { var subtext = document.createElement("div"); subtext.innerHTML = this.translate("UPDATE_INFO") - .replace("COMMIT_COUNT", this.status.behind + " " + ((this.status.behind == 1)? "commit" : "commits")) - .replace("BRANCH_NAME", this.status.current); + .replace("COMMIT_COUNT", this.status.behind + " " + ((this.status.behind == 1) ? "commit" : "commits")) + .replace("BRANCH_NAME", this.status.current); subtext.className = "xsmall dimmed"; wrapper.appendChild(subtext); } diff --git a/modules/default/weatherforecast/weatherforecast.js b/modules/default/weatherforecast/weatherforecast.js index b269a44a..1972fac0 100644 --- a/modules/default/weatherforecast/weatherforecast.js +++ b/modules/default/weatherforecast/weatherforecast.js @@ -63,7 +63,7 @@ Module.register("weatherforecast",{ firstEvent: false, // create a variable to hold the location name based on the API result. - fetchedLocatioName: "", + fetchedLocationName: "", // Define required scripts. getScripts: function() { @@ -77,8 +77,8 @@ Module.register("weatherforecast",{ // Define required translations. getTranslations: function() { - // The translations for the defaut modules are defined in the core translation files. - // Therefor we can just return false. Otherwise we should have returned a dictionairy. + // 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 yiur own module including translations, check out the documentation. return false; }, @@ -175,7 +175,6 @@ Module.register("weatherforecast",{ row.style.opacity = 1 - (1 / steps * currentStep); } } - } return table; @@ -184,7 +183,7 @@ Module.register("weatherforecast",{ // Override getHeader method. getHeader: function() { if (this.config.appendLocationNameToHeader) { - return this.data.header + " " + this.fetchedLocatioName; + return this.data.header + " " + this.fetchedLocationName; } return this.data.header; @@ -200,10 +199,9 @@ Module.register("weatherforecast",{ if (notification === "CALENDAR_EVENTS") { var senderClasses = sender.data.classes.toLowerCase().split(" "); if (senderClasses.indexOf(this.config.calendarClass.toLowerCase()) !== -1) { - var lastEvent = this.firstEvent; this.firstEvent = false; - for (e in payload) { + for (var e in payload) { var event = payload[e]; if (event.location || event.geo) { this.firstEvent = event; @@ -291,7 +289,7 @@ Module.register("weatherforecast",{ * argument data object - Weather information received form openweather.org. */ processWeather: function(data) { - this.fetchedLocatioName = data.city.name + ", " + data.city.country; + this.fetchedLocationName = data.city.name + ", " + data.city.country; this.forecast = []; for (var i = 0, count = data.list.length; i < count; i++) { @@ -335,6 +333,10 @@ Module.register("weatherforecast",{ /* ms2Beaufort(ms) * Converts m2 to beaufort (windspeed). * + * see: + * http://www.spc.noaa.gov/faq/tornado/beaufort.html + * https://en.wikipedia.org/wiki/Beaufort_scale#Modern_scale + * * argument ms number - Windspeed in m/s. * * return number - Windspeed in beaufort. @@ -356,7 +358,7 @@ Module.register("weatherforecast",{ * * argument temperature number - Temperature. * - * return number - Rounded Temperature. + * return string - Rounded Temperature. */ roundValue: function(temperature) { var decimals = this.config.roundTemp ? 0 : 1; diff --git a/modules/node_modules/node_helper/index.js b/modules/node_modules/node_helper/index.js index 8d0372bd..37c3e2cb 100644 --- a/modules/node_modules/node_helper/index.js +++ b/modules/node_modules/node_helper/index.js @@ -20,7 +20,7 @@ NodeHelper = Class.extend({ }, start: function() { - console.log("Staring module helper: " + this.name); + console.log("Starting module helper: " + this.name); }, /* socketNotificationReceived(notification, payload) @@ -45,7 +45,7 @@ NodeHelper = Class.extend({ /* setPath(path) * Set the module path. * - * argument name string - Module name. + * argument path string - Module path. */ setPath: function(path) { this.path = path; @@ -98,9 +98,10 @@ NodeHelper = Class.extend({ // register catch all. socket.on("*", function(notification, payload) { - if (notification !== "*") - //console.log('received message in namespace: ' + namespace); - self.socketNotificationReceived(notification, payload); + if (notification !== "*") { + //console.log('received message in namespace: ' + namespace); + self.socketNotificationReceived(notification, payload); + } }); }); diff --git a/package.json b/package.json index 7a1e7641..1fb21a9d 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,17 @@ { "name": "magicmirror", - "version": "2.1.1", - "description": "A modular interface for smart mirrors.", + "version": "2.1.3-dev", + "description": "The open source modular smart mirror platform.", "main": "js/electron.js", "scripts": { "start": "sh run-start.sh", "install": "cd vendor && npm install", - "postinstall": "sh installers/postinstall/postinstall.sh", - "test": "./node_modules/mocha/bin/mocha tests --recursive", - "test:unit": "./node_modules/mocha/bin/mocha tests/unit --recursive", - "test:e2e": "./node_modules/mocha/bin/mocha tests/e2e --recursive" + "install-fonts": "cd fonts && npm install", + "postinstall": "sh installers/postinstall/postinstall.sh && npm run install-fonts", + "test": "NODE_ENV=test ./node_modules/mocha/bin/mocha tests --recursive", + "test:unit": "NODE_ENV=test ./node_modules/mocha/bin/mocha tests/unit --recursive", + "test:e2e": "NODE_ENV=test ./node_modules/mocha/bin/mocha tests/e2e --recursive", + "config:check": "node tests/configs/check_config.js" }, "repository": { "type": "git", @@ -29,35 +31,39 @@ "bugs": { "url": "https://github.com/MichMich/MagicMirror/issues" }, - "homepage": "https://github.com/MichMich/MagicMirror#readme", + "homepage": "https://magicmirror.builders", "devDependencies": { "chai": "^3.5.0", "chai-as-promised": "^6.0.0", + "current-week-number": "^1.0.7", "grunt": "latest", "grunt-eslint": "latest", "grunt-jsonlint": "latest", - "grunt-markdownlint": "^1.0.13", + "grunt-markdownlint": "^1.0.39", "grunt-stylelint": "latest", "grunt-yamllint": "latest", "http-auth": "^3.1.3", - "mocha": "^3.2.0", - "spectron": "^3.4.1", + "jshint": "^2.9.4", + "mocha": "^3.4.2", + "stylelint": "^8.0.0", + "spectron": "3.6.x", "stylelint-config-standard": "latest", "time-grunt": "latest" }, "dependencies": { + "body-parser": "^1.17.2", "colors": "^1.1.2", - "electron": "^1.4.7", - "express": "^4.14.0", + "electron": "^1.6.10", + "express": "^4.15.3", "express-ipfilter": "latest", "feedme": "latest", - "helmet": "^3.1.0", + "helmet": "^3.6.1", "iconv-lite": "latest", "moment": "latest", - "request": "^2.78.0", - "rrule-alt": "^2.2.3", - "simple-git": "^1.62.0", - "socket.io": "^1.7.3", + "request": "^2.81.0", + "rrule-alt": "^2.2.5", + "simple-git": "^1.73.0", + "socket.io": "^2.0.2", "valid-url": "latest", "walk": "latest" } diff --git a/tests/configs/check_config.js b/tests/configs/check_config.js new file mode 100644 index 00000000..f5ad61c1 --- /dev/null +++ b/tests/configs/check_config.js @@ -0,0 +1,66 @@ +/* Magic Mirror + * + * Checker configuration file + * + * By Rodrigo Ramírez Norambuena + * https://rodrigoramirez.com + * + * MIT Licensed. + * + */ + +var v = require("jshint"); +var path = require("path"); +var fs = require("fs"); +var Utils = require(__dirname + "/../../js/utils.js"); + +if (process.env.NODE_ENV == "test") { return 0 }; + +/* getConfigFile() + * Return string with path of configuration file + * Check if set by enviroment variable MM_CONFIG_FILE + */ +function getConfigFile() { + // FIXME: This function should be in core. Do you want refactor me ;) ?, be good! + rootPath = path.resolve(__dirname + "/../../"); + var configFileName = path.resolve(rootPath + "/config/config.js"); + if (process.env.MM_CONFIG_FILE) { + configFileName = path.resolve(process.env.MM_CONFIG_FILE); + } + return configFileName; +} + +var configFileName = getConfigFile(); +// Check if file is present +if (fs.existsSync(configFileName) === false) { + console.error(Utils.colors.error("File not found: "), configFileName); + return; +} +// check permision +try { + fs.accessSync(configFileName, fs.F_OK); +} catch (e) { + console.log(Utils.colors.error(e)); + return; +} + +// Validate syntax of the configuration file. +// In case the there errors show messages and +// return +console.info(Utils.colors.info("Checking file... ", configFileName)); +// I'm not sure if all ever is utf-8 +fs.readFile(configFileName, "utf-8", function (err, data) { + if (err) { throw err; } + v.JSHINT(data); // Parser by jshint + + if (v.JSHINT.errors.length == 0) { + console.log("Your configuration file don't containt syntax error :)"); + return true; + } else { + errors = v.JSHINT.data().errors; + for (idx in errors) { + error = errors[idx]; + console.log("Line", error.line, "col", error.character, error.reason); + } + } +}); diff --git a/tests/configs/data/feed_test_rodrigoramirez.xml b/tests/configs/data/feed_test_rodrigoramirez.xml new file mode 100644 index 00000000..e4d3730f --- /dev/null +++ b/tests/configs/data/feed_test_rodrigoramirez.xml @@ -0,0 +1,410 @@ + + + + Rodrigo Ramírez Norambuena + + https://rodrigoramirez.com + Temas sobre Linux, VoIP, Open Source, tecnología y lo relacionado. + Fri, 21 Oct 2016 21:30:22 +0000 + es-ES + hourly + 1 + https://wordpress.org/?v=4.7.3 + + QPanel 0.13.0 + https://rodrigoramirez.com/qpanel-0-13-0/ + https://rodrigoramirez.com/qpanel-0-13-0/#comments + Tue, 20 Sep 2016 11:16:08 +0000 + + + + + + + + + + + + + https://rodrigoramirez.com/?p=1299 + Ya está disponible la versión 0.13.0 de QPanel Para instalar esta nueva versión, la debes descargar de https://github.com/roramirez/qpanel/tree/0.13.0 En al README.md puedes encontrar las instrucciones para hacer que funcione en tu sistema. En esta nueva versión cuenta con los siguientes cambios: Se establece un limite para el reciclado del tiempo de conexión a la base […]

+

La entrada QPanel 0.13.0 aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Panel monitor callcenter | Qpanel Monitor ColasYa está disponible la versión 0.13.0 de QPanel

+

Para instalar esta nueva versión, la debes descargar de

+ +

En al README.md puedes encontrar las instrucciones para hacer que funcione en tu sistema.

+

En esta nueva versión cuenta con los siguientes cambios:

+
    +
  • Se establece un limite para el reciclado del tiempo de conexión a la base de datos que contenga QueueLog. Esto evita problemas en bases de datos como MySQL que finaliza o da timeout a las conexiones.
  • +
  • Ahora la py-asterisk va dentro del archivo requirements.txt y no como submodulo del proyecto.
  • +
  • Se remueven la mayoría de las libs externas para Javascript y CSS para manejarlos desde ahora con Bower.
  • +
  • Se incluye un script para WSGI que permite su utilización con Apache.
  • +
  • Actualización para los idiomas Ruso y Portugues.
  • +
+

Si deseas colaborar con el proyecto puedes agregar nuevas sugerencias mediante un issue ó colaborar mediante mediante un Pull Request.

+

Ahora si necesitas soporte comercial para instalaciones, personalizaciones o nuevas características  lo puedes solicitar en https://boxtub.com/qpanel/

+

 

+

La entrada QPanel 0.13.0 aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/qpanel-0-13-0/feed/ + 3 +
+ + Problema VirtualBox “starting virtual machine” … + https://rodrigoramirez.com/problema-virtualbox-starting-virtual-machine/ + https://rodrigoramirez.com/problema-virtualbox-starting-virtual-machine/#respond + Sat, 10 Sep 2016 22:50:13 +0000 + + + + + + + https://rodrigoramirez.com/?p=1284 + Después de una actualización de Debian, de la rama stretch/sid, tuve un problema con VirtualBox.  La versión que se actualizó fue a la virtualbox 5.1.4-dfsg-1+b1. El gran problema era que ninguna maquina virtual quería arrancar, se quedaba en un largo limbo con el mensaje “starting virtual machine”, como el de la imagen de a continuación. […]

+

La entrada Problema VirtualBox “starting virtual machine” … aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Después de una actualización de Debian, de la rama stretch/sid, tuve un problema con VirtualBox.  La versión que se actualizó fue a la virtualbox 5.1.4-dfsg-1+b1. El gran problema era que ninguna maquina virtual quería arrancar, se quedaba en un largo limbo con el mensaje “starting virtual machine”, como el de la imagen de a continuación.

+

Starting virtual machine ... VirtualBox

+

Ninguna, pero ninguna maquina arrancó, se quedaban en ese mensaje. Fue de esos instantes en que sudas helado … 😉

+

Con un poco de investigación fue a parar al archivo ~/.VirtualBox/VBoxSVC.log que indicaba

+
$ tail -f ~/.VirtualBox/VBoxSVC.log
+ 00:08:32.932717 nspr-7 Failed to open "/dev/vboxdrvu", errno=13, rc=VERR_VM_DRIVER_NOT_ACCESSIBLE
+ 00:08:33.555836 nspr-6 Failed to open "/dev/vboxdrvu", errno=13, rc=VERR_VM_DRIVER_NOT_ACCESSIBLE
+

 

+

Fui… algo de donde agarrarse. Mirando un poco mas se trataba de problemas con los permisos al vboxdrvu, mirando indicaba que tenía 0600.

+

 

+
$ ls -lh /dev/vboxdrvu 
+ crw------- 1 root root 10, 56 Sep 10 12:47 /dev/vboxdrvu
+

 

+

El tema es que deben estar en 0666,  le cambias los permisos y eso soluciona el problema 🙂

+
+$ sudo chmod 0666 /dev/vboxdrvu
+$ ls -lh /dev/vboxdrvu
+ crw-rw-rw- 1 root root 10, 56 Sep 10 12:47 /dev/vboxdrvu
+

La entrada Problema VirtualBox “starting virtual machine” … aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/problema-virtualbox-starting-virtual-machine/feed/ + 0 +
+ + Mejorando la consola interactiva de Python + https://rodrigoramirez.com/mejorando-la-consola-interactiva-python/ + https://rodrigoramirez.com/mejorando-la-consola-interactiva-python/#comments + Tue, 06 Sep 2016 04:24:43 +0000 + + + + + + https://rodrigoramirez.com/?p=1247 + Cuando estás desarrollando en Python es muy cool estar utilizando la consola interactiva para ir probando cosas antes de ponerlas dentro del archivo de código fuente. La consola de Python funciona y cumple su cometido. Solo al tipear  python  te permite entrar en modo interactivo e ir probando cosas. El punto es que a veces […]

+

La entrada Mejorando la consola interactiva de Python aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Cuando estás desarrollando en Python es muy cool estar utilizando la consola interactiva para ir probando cosas antes de ponerlas dentro del archivo de código fuente.

+

La consola de Python funciona y cumple su cometido. Solo al tipear  python  te permite entrar en modo interactivo e ir probando cosas.

+

El punto es que a veces uno necesita ir un poco más allá. Como autocomentado de código o resaltado de sintaxis, para eso tengo dos truco que utilizo generalmente.

+

Truco a)

+

Este permite añadirle algunos esteriodes a la consolta, en realidad uno, el autocompletado. Esto es de gran ayuda para ir conociendo los metodo que puede tener un objecto, funciones u operaciones.

+

Para esto se ocupo rlcompleterreadline.

+

 

+

Lo que hace que hacer luego de tipear python es agregar lo siguiente dentro de la consola interativa

+

import rlcompleter, readline
+readline.parse_and_bind(‘tab:complete’)

+

Ya con esto te permite autocomentar código 🙂

+

+

 

+

Truco b)

+

Esto es mejorar un poco más. Es utilizar embed de IPython,  ya en la consola digita (copias o pegas) lo siguiente

+

from IPython import embed
+embed()

+

Y el resultado será lo que se ve a continuación… bueno, no?

+

 

+

+

 

+

Si no quieres estar escribiendo cada vez que entras, agregas estas instrucciones en tu archivo  ~/.pythonrc.py  y lo hará cada vez que entras en el modo interactivo de la consola de Python. Lo que si, tu archivo pythonrc.py debe estar seteado en variable de entorno PYTHONSTARTUP

+

ejemplo

+

export  PYTHONSTARTUP=~/.pythonrc.py

+

O lo agregas a un bashrc, zshrc o la shell que ocupes.

+

La entrada Mejorando la consola interactiva de Python aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/mejorando-la-consola-interactiva-python/feed/ + 4 +
+ + QPanel 0.12.0 con estadísticas + https://rodrigoramirez.com/qpanel-0-12-0-estadisticas/ + https://rodrigoramirez.com/qpanel-0-12-0-estadisticas/#respond + Mon, 22 Aug 2016 04:19:03 +0000 + + + + + + + + + + + + + https://rodrigoramirez.com/?p=1268 + Ya está disponible una nueva versión de QPanel, esta es la 0.12.0 Para instalar esta nueva versión, debes visitar la siguiente URL https://github.com/roramirez/qpanel/tree/0.12.0 En esta nueva versión las funcionalidades agregadas son: Permite remover los agentes de las cola Posibilidad de cancelar llamadas que están en espera de atención Estadísticas por rango de fecha obtenidas desde […]

+

La entrada QPanel 0.12.0 con estadísticas aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Panel monitor callcenter | Qpanel Monitor ColasYa está disponible una nueva versión de QPanel, esta es la 0.12.0

+

Para instalar esta nueva versión, debes visitar la siguiente URL

+ +

En esta nueva versión las funcionalidades agregadas son:

+
    +
  • Permite remover los agentes de las cola
  • +
  • Posibilidad de cancelar llamadas que están en espera de atención
  • +
  • Estadísticas por rango de fecha obtenidas desde el queue_log de Asterisk
  • +
  • Se actualiza a Flask 0.11
  • +
+

Si deseas colaborar con el proyecto puedes agregar nuevas sugerencias mediante un issue ó colaborar mediante mediante un Pull Request

+

La entrada QPanel 0.12.0 con estadísticas aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/qpanel-0-12-0-estadisticas/feed/ + 0 +
+ + QPanel 0.11.0 con Spy, Whisper y mas + https://rodrigoramirez.com/qpanel-spy-supervisor/ + https://rodrigoramirez.com/qpanel-spy-supervisor/#comments + Thu, 21 Jul 2016 01:53:21 +0000 + + + + + + + + + + + + + https://rodrigoramirez.com/?p=1245 + Ya está disponible una nueva versión de QPanel, esta es la 0.11.0 Para instalar esta nueva versión, debes visitar la siguiente URL https://github.com/roramirez/qpanel/tree/0.11.0 Esta versión hemos agregado  algunas funcionalidades que los usuarios  han ido solicitando. Para esta versión es posible realizar Spy, Whisper o Barge a un canal para la supervisión de los miembros que […]

+

La entrada QPanel 0.11.0 con Spy, Whisper y mas aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Panel monitor callcenter | Qpanel Monitor ColasYa está disponible una nueva versión de QPanel, esta es la 0.11.0

+

Para instalar esta nueva versión, debes visitar la siguiente URL

+ +

Esta versión hemos agregado  algunas funcionalidades que los usuarios  han ido solicitando.

+

Para esta versión es posible realizar Spy, Whisper o Barge a un canal para la supervisión de los miembros que están en una cola.

+

También el sistema de plantillas se hecho una refactorización para eliminar exceso de codigo HTML usando uno de base.

+

Se han agregado una suite de tests unitarios que al contar del avance del proyecto deberían ir incrementando.

+

Se ha solucionado un bug con la actualización del color del estado del agente cuando es uno nuevo agregado a la cola.

+

 

+

El proyecto siempre está abierto a nuevas sugerencias las cuales puedes agregar mediante un issue.

+

La entrada QPanel 0.11.0 con Spy, Whisper y mas aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/qpanel-spy-supervisor/feed/ + 4 +
+ + Añadir Swap a un sistema + https://rodrigoramirez.com/crear-swap/ + https://rodrigoramirez.com/crear-swap/#respond + Fri, 15 Jul 2016 05:07:43 +0000 + + + + https://rodrigoramirez.com/?p=1234 + Algo que me toma generalmente hacer es cuando trabajo con maquina virtuales es asignar una cantidad determinada de Swap. La  memoria swap es un espacio de intercambio en disco para cuando el sistema ya no puede utilizar más memoria RAM. El problema para mi es que algunos sistemas de maquinas virtuales no asignan por defecto […]

+

La entrada Añadir Swap a un sistema aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Algo que me toma generalmente hacer es cuando trabajo con maquina virtuales es asignar una cantidad determinada de Swap.

+

La  memoria swap es un espacio de intercambio en disco para cuando el sistema ya no puede utilizar más memoria RAM.

+

El problema para mi es que algunos sistemas de maquinas virtuales no asignan por defecto un espacio para la Swap, lo que te lleva a que el sistema pueda tener crash durante la ejecución.

+

Para comprobar la asignación de memoria, al ejecutar el comando free nos debería mostrar como algo similar a lo siguiente

+

 

+
$  free -m
+             total       used       free     shared    buffers     cached
+Mem:           494        488          6          1         54         75
+-/+ buffers/cache:        357        136
+Swap:            0          0          0
+

En la zona de swap indica que no asignada, valor 0.

+

Para asignar swap al sistema se debe  un archivo en disco para que sea utilizado como espacio de intercambio, en este caso lo vamos  crear uno  de 3GB en la raíz del sistema

+
fallocate -l 3G /swapfile
+

Comprobamos que ha sido creado

+
$ ls -lh /swapfile
+-rw-r--r-- 1 root root 3.0G Jul 11 13:10 /swapfile
+
+

Habilitación del archivo Swap

+

Ahora nos toca habilitar el archivo creado. Para eso le asignaremos los permisos

+
chmod 600 /swapfile
+

Lo siguiente es para convertir el  archivo para swap

+
mkswap /swapfile
+

Para habilitar y asignarla eso como memoria swap al sistema usamos

+
swapon /swapfile
+

Ya con esto podrémos ver en nuestro sistema la memoria asignada para swap

+
$ free -m
+             total       used       free     shared    buffers     cached
+Mem:           494        486          7          1         51         77
+-/+ buffers/cache:        358        136
+Swap:         3071          0       3071
+

 

+

Para que al reiniciar el sistema esto se mantenga, debemos agregar la siguiente línea al archivo /etc/fstab

+
/swapfile none swap sw 0 0
+

 

+

Podemos editar /etc/fstab con algún editor como vim, nano o podemos agregar la linea directamente en la desde la cli de la siguiente manera

+
echo "/swapfile none swap sw 0 0" >> /etc/fstab
+

 

+

 

+

La entrada Añadir Swap a un sistema aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/crear-swap/feed/ + 0 +
+ + QPanel 0.10.0 con vista consolidada + https://rodrigoramirez.com/qpanel-0-10-0-vista-consolidada/ + https://rodrigoramirez.com/qpanel-0-10-0-vista-consolidada/#respond + Mon, 20 Jun 2016 19:32:55 +0000 + + + + + + + + + https://rodrigoramirez.com/?p=1227 + Ya con la release numero 28 la nueva versión 0.10.0 de QPanel ya está disponible. Para instalar esta nueva versión, debes visitar la siguiente URL https://github.com/roramirez/qpanel/tree/0.10.0 Esta versión versión nos preocupamos de realizar mejoras, refactorizaciones y agregamos una nueva funcionalidad. La nueva funcionalidad incluida es  que ahora es posible contar con una vista consolidada para […]

+

La entrada QPanel 0.10.0 con vista consolidada aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Panel monitor callcenter | Qpanel Monitor ColasYa con la release numero 28 la nueva versión 0.10.0 de QPanel ya está disponible.

+

Para instalar esta nueva versión, debes visitar la siguiente URL

+ +

Esta versión versión nos preocupamos de realizar mejoras, refactorizaciones y agregamos una nueva funcionalidad.

+

La nueva funcionalidad incluida es  que ahora es posible contar con una vista consolidada para la información de todas las colas. Que hace tener un mejor control y visualización de lo que está pasando en las colas.

+

El proyecto siempre está abierto a nuevas sugerencias las cuales puedes agregar mediante un issue.

+

La entrada QPanel 0.10.0 con vista consolidada aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/qpanel-0-10-0-vista-consolidada/feed/ + 0 +
+ + Nerdearla 2016, WebRTC Glue + https://rodrigoramirez.com/nerdearla-2016/ + https://rodrigoramirez.com/nerdearla-2016/#respond + Wed, 15 Jun 2016 17:55:41 +0000 + + + + + + + + + + + https://rodrigoramirez.com/?p=1218 + Días atrás estuve participando en el evento llamado Nerdearla en Buenos Aires.  El ambiente era genial si eres de esas personas que desde niño sintio curiosidad por ver como funcionan las cosas, donde desarmabas para volver armar lo juguetes. Habían muchas cosas interesantes tanto en las presentaciones, co-working y workshop que se hubieron. Si te […]

+

La entrada Nerdearla 2016, WebRTC Glue aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Días atrás estuve participando en el evento llamado Nerdearla en Buenos Aires.  El ambiente era genial si eres de esas personas que desde niño sintio curiosidad por ver como funcionan las cosas, donde desarmabas para volver armar lo juguetes.

+

Habían muchas cosas interesantes tanto en las presentaciones, co-working y workshop que se hubieron. Si te lo perdiste te recomiendo que estés pendiente para el proximo año.

+

 

+

Te podias encontrar con una nuestra como estaKaypro II

+

Puedes dar un vistaso a lo registrado por algunos usuarios en Twitter

+

El primer día hice un workshop denominado WebRTC Glue, donde muestra como hacer como unificar la experiencia de atención del centro de contacto directamente en la web. Es una presentación práctica donde puedes ver los ejemplos y usarlos como gustes. Están en el repositorio en Gitlab. La presentación la puedes ver aquí

+

 

+

WebRTC Glue

+

Haber si nos vemos el próximo año.

+

 

+

Update: Puedes ver una parte sin la demostración del workshop

+


+

La entrada Nerdearla 2016, WebRTC Glue aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/nerdearla-2016/feed/ + 0 +
+ + QPanel 0.9.0 + https://rodrigoramirez.com/qpanel-0-9-0/ + https://rodrigoramirez.com/qpanel-0-9-0/#respond + Mon, 09 May 2016 18:40:23 +0000 + + + + + + + + + + + + http://rodrigoramirez.com/?p=1206 + El Panel monitor callcenter para colas de Asterisk ya cuenta con una nueva versión, la 0.9.0 Para instalar esta nueva versión, debes visitar la siguiente URL https://github.com/roramirez/qpanel/tree/0.9.0 Esta versión versión nos preocupamos de realizar mejoras y refactorizaciones en el codigo para dar un mejor rendimiento, como también de la compatibilidad con la versión 11 de […]

+

La entrada QPanel 0.9.0 aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Panel monitor callcenter | Qpanel Monitor ColasEl Panel monitor callcenter para colas de Asterisk ya cuenta con una nueva versión, la 0.9.0

+

Para instalar esta nueva versión, debes visitar la siguiente URL

+ +

Esta versión versión nos preocupamos de realizar mejoras y refactorizaciones en el codigo para dar un mejor rendimiento, como también de la compatibilidad con la versión 11 de Asterisk.

+

Dentro de las cosas que podamos mencionar:

+
    +
  •  Actualización del repositorio y versión de py-asterisk, biblioteca para trabajar con Asterisk. Acá la ocupamos principalmente para uso del Manager.
  • +
  • Portación de parche de funcionalidades como pausa, tiempo, razón de una pausa para Asterisk 11.
  • +
  • Cambio del comportamiento en el conteo cuando el participante en una cola está ocupado (busy)
  • +
+

El proyecto siempre está abierto a nuevas sugerencias las cuales puedes agregar mediante un issue.

+

La entrada QPanel 0.9.0 aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/qpanel-0-9-0/feed/ + 0 +
+ + Mandar un email desde la shell + https://rodrigoramirez.com/mandar-un-email-desde-la-shell/ + https://rodrigoramirez.com/mandar-un-email-desde-la-shell/#comments + Wed, 13 Apr 2016 13:05:13 +0000 + + + + + + + + + + + http://rodrigoramirez.com/?p=1172 + Dejo esto por acá ya que es algo que siempre me olvido como es. El tema es enviar un email mediante el comando mail en un servidor con Linux. Si usas mail a secas te va pidiendo los datos para crear el correo, principalmente el body del correo. Para automatizar esto a través de un […]

+

La entrada Mandar un email desde la shell aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ Dejo esto por acá ya que es algo que siempre me olvido como es. El tema es enviar un email mediante el comando mail en un servidor con Linux.

+

Si usas mail a secas te va pidiendo los datos para crear el correo, principalmente el body del correo. Para automatizar esto a través de un echo le pasas por pipe a mail

+
echo "Cuerpo del mensaje" | mail -s Asunto a@rodrigoramirez.com
+

La entrada Mandar un email desde la shell aparece primero en Rodrigo Ramírez Norambuena.

+]]>
+ https://rodrigoramirez.com/mandar-un-email-desde-la-shell/feed/ + 4 +
+
+
diff --git a/tests/configs/modules/clock/clock_showWeek.js b/tests/configs/modules/clock/clock_showWeek.js new file mode 100644 index 00000000..8a5f305a --- /dev/null +++ b/tests/configs/modules/clock/clock_showWeek.js @@ -0,0 +1,32 @@ +/* Magic Mirror Test config for default clock module + * + * By Johan Hammar + * MIT Licensed. + */ + +var config = { + port: 8080, + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], + + language: "en", + timeFormat: 12, + units: "metric", + electronOptions: { + webPreferences: { + nodeIntegration: true, + }, + }, + + modules: [ + { + module: "clock", + position: "middle_center", + config: { + showWeek: true + } + } + ] +}; + +/*************** DO NOT EDIT THE LINE BELOW ***************/ +if (typeof module !== "undefined") {module.exports = config;} diff --git a/tests/configs/modules/clock/es/clock_showWeek.js b/tests/configs/modules/clock/es/clock_showWeek.js new file mode 100644 index 00000000..29550f04 --- /dev/null +++ b/tests/configs/modules/clock/es/clock_showWeek.js @@ -0,0 +1,38 @@ + +/* Magic Mirror + * + * Test config for default clock module + * Language es for showWeek feature + * + * By Rodrigo Ramírez Norambuena + * https://rodrigoramirez.com + * + * MIT Licensed. + */ + +var config = { + port: 8080, + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], + + language: "es", + timeFormat: 12, + units: "metric", + electronOptions: { + webPreferences: { + nodeIntegration: true, + }, + }, + + modules: [ + { + module: "clock", + position: "middle_center", + config: { + showWeek: true + } + } + ] +}; + +/*************** DO NOT EDIT THE LINE BELOW ***************/ +if (typeof module !== "undefined") {module.exports = config;} diff --git a/tests/configs/modules/compliments/compliments_parts_day.js b/tests/configs/modules/compliments/compliments_parts_day.js index 8d47fe22..b4443567 100644 --- a/tests/configs/modules/compliments/compliments_parts_day.js +++ b/tests/configs/modules/compliments/compliments_parts_day.js @@ -1,4 +1,4 @@ -/* Magic Mirror Test config for default compliments +/* Magic Mirror Test config for default compliments * * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com * MIT Licensed. diff --git a/tests/configs/modules/newsfeed/default.js b/tests/configs/modules/newsfeed/default.js new file mode 100644 index 00000000..5cb9d311 --- /dev/null +++ b/tests/configs/modules/newsfeed/default.js @@ -0,0 +1,38 @@ +/* Magic Mirror Test config newsfeed module + * + * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com + * MIT Licensed. + */ + +var config = { + port: 8080, + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], + + language: "en", + timeFormat: 12, + units: "metric", + electronOptions: { + webPreferences: { + nodeIntegration: true, + }, + }, + + modules: [ + { + + module: "newsfeed", + position: "bottom_bar", + config: { + feeds: [ + { + title: "Rodrigo Ramirez Blog", + url: "http://localhost:8080/tests/configs/data/feed_test_rodrigoramirez.xml" + }, + ] + } + } + ] +}; + +/*************** DO NOT EDIT THE LINE BELOW ***************/ +if (typeof module !== "undefined") {module.exports = config;} diff --git a/tests/configs/modules/positions.js b/tests/configs/modules/positions.js new file mode 100644 index 00000000..60e6dd04 --- /dev/null +++ b/tests/configs/modules/positions.js @@ -0,0 +1,43 @@ +/* Magic Mirror Test config for position setters module + * + * For this case is using helloworld module + * + * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com + * MIT Licensed. + */ + + +var config = { + port: 8080, + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], + ipWhitelist: [], + + language: "en", + timeFormat: 24, + units: "metric", + electronOptions: { + webPreferences: { + nodeIntegration: true, + }, + }, + modules: + // Using exotic content. This is why dont accept go to JSON configuration file + (function() { + var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", + "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", + "bottom_bar", "fullscreen_above", "fullscreen_below"]; + var modules = Array(); + for (idx in positions) { + modules.push({ + module: "helloworld", + position: positions[idx], + config: { + text: "Text in " + positions[idx] + } + }); + } + return modules; + })(), +}; +/*************** DO NOT EDIT THE LINE BELOW ***************/ +if (typeof module !== "undefined") {module.exports = config;} diff --git a/tests/configs/port_8090.js b/tests/configs/port_8090.js new file mode 100644 index 00000000..6646dff7 --- /dev/null +++ b/tests/configs/port_8090.js @@ -0,0 +1,25 @@ +/* Magic Mirror Test config sample enviroment set por 8090 + * + * By Rodrigo Ramírez Norambuena https://rodrigoramirez.com + * MIT Licensed. + */ + +var config = { + port: 8090, + ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"], + + language: "en", + timeFormat: 24, + units: "metric", + electronOptions: { + webPreferences: { + nodeIntegration: true, + }, + }, + + modules: [ + ] +}; + +/*************** DO NOT EDIT THE LINE BELOW ***************/ +if (typeof module !== "undefined") {module.exports = config;} diff --git a/tests/e2e/dev_console.js b/tests/e2e/dev_console.js index b430e9e4..42530a38 100644 --- a/tests/e2e/dev_console.js +++ b/tests/e2e/dev_console.js @@ -1,50 +1,65 @@ -const Application = require("spectron").Application; +const helpers = require("./global-setup"); const path = require("path"); -const chai = require("chai"); -const expect = chai.expect; -const chaiAsPromised = require("chai-as-promised"); +const request = require("request"); -var electronPath = path.join(__dirname, "../../", "node_modules", ".bin", "electron"); +const expect = require("chai").expect; -if (process.platform === "win32") { - electronPath += ".cmd"; -} +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; -var appPath = path.join(__dirname, "../../js/electron.js"); +describe("Development console tests", function() { + // This tests fail and crash another tests + // Suspect problem with window focus + // FIXME + return false; -var app = new Application({ - path: electronPath -}); + helpers.setupTimeout(this); -global.before(function () { - chai.should(); - chai.use(chaiAsPromised); -}); - -describe("Argument 'dev'", function () { - this.timeout(20000); + var app = null; before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/env.js"; }); - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); + describe("Without 'dev' commandline argument", function() { + before(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); + }); - it("should not open dev console when absent", function () { - app.args = [appPath]; + after(function() { + return helpers.stopApplication(app); + }); - return app.start().then(function() { + it("should not open dev console when absent", function() { return expect(app.browserWindow.isDevToolsOpened()).to.eventually.equal(false); }); }); - it("should open dev console when provided", function () { - app.args = [appPath, "dev"]; + describe("With 'dev' commandline argument", function() { + before(function() { + return helpers + .startApplication({ + args: ["js/electron.js", "dev"] + }) + .then(function(startedApp) { + app = startedApp; + }); + }); - return app.start().then(function() { + after(function() { + return helpers.stopApplication(app); + }); + + it("should open dev console when provided", function() { return expect(app.browserWindow.isDevToolsOpened()).to.eventually.equal(true); }); }); diff --git a/tests/e2e/env_spec.js b/tests/e2e/env_spec.js index 04bb5542..9454b92e 100644 --- a/tests/e2e/env_spec.js +++ b/tests/e2e/env_spec.js @@ -1,40 +1,69 @@ -const globalSetup = require("./global-setup"); -const app = globalSetup.app; +const helpers = require("./global-setup"); +const path = require("path"); const request = require("request"); -const chai = require("chai"); -const expect = chai.expect; -describe("Electron app environment", function () { - this.timeout(20000); +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("Electron app environment", function() { + helpers.setupTimeout(this); + + var app = null; before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/env.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); }); - afterEach(function (done) { - app.stop().then(function() { done(); }); + afterEach(function() { + return helpers.stopApplication(app); }); - it("is set to open new app window", function () { - return app.client.waitUntilWindowLoaded() - .getWindowCount().should.eventually.equal(1); + it("should open a browserwindow", function() { + return app.client + .waitUntilWindowLoaded() + .browserWindow.focus() + .getWindowCount() + .should.eventually.equal(1) + .browserWindow.isMinimized() + .should.eventually.be.false.browserWindow.isDevToolsOpened() + .should.eventually.be.false.browserWindow.isVisible() + .should.eventually.be.true.browserWindow.isFocused() + .should.eventually.be.true.browserWindow.getBounds() + .should.eventually.have.property("width") + .and.be.above(0) + .browserWindow.getBounds() + .should.eventually.have.property("height") + .and.be.above(0) + .browserWindow.getTitle() + .should.eventually.equal("MagicMirror²"); }); - it("sets correct window title", function () { - return app.client.waitUntilWindowLoaded() - .getTitle().should.eventually.equal("Magic Mirror"); - }); - - it("get request from http://localhost:8080 should return 200", function (done) { - request.get("http://localhost:8080", function (err, res, body) { + it("get request from http://localhost:8080 should return 200", function(done) { + request.get("http://localhost:8080", function(err, res, body) { expect(res.statusCode).to.equal(200); done(); }); }); + it("get request from http://localhost:8080/nothing should return 404", function(done) { + request.get("http://localhost:8080/nothing", function(err, res, body) { + expect(res.statusCode).to.equal(404); + done(); + }); + }); }); diff --git a/tests/e2e/global-setup.js b/tests/e2e/global-setup.js index 7b94ec40..6bfe11d0 100644 --- a/tests/e2e/global-setup.js +++ b/tests/e2e/global-setup.js @@ -9,26 +9,54 @@ */ const Application = require("spectron").Application; -const path = require("path"); +const assert = require("assert"); const chai = require("chai"); const chaiAsPromised = require("chai-as-promised"); -var electronPath = path.join(__dirname, "../../", "node_modules", ".bin", "electron"); +const path = require("path"); -if (process.platform === "win32") { - electronPath += ".cmd"; -} - -var appPath = path.join(__dirname, "../../js/electron.js"); - -var app = new Application({ - path: electronPath, - args: [appPath] -}); - -global.before(function () { +global.before(function() { chai.should(); chai.use(chaiAsPromised); }); -exports.app = app; +exports.getElectronPath = function() { + var electronPath = path.join(__dirname, "..", "..", "node_modules", ".bin", "electron"); + if (process.platform === "win32") { + electronPath += ".cmd"; + } + return electronPath; +}; + +// Set timeout - if this is run within Travis, increase timeout +exports.setupTimeout = function(test) { + if (process.env.CI) { + test.timeout(30000); + } else { + test.timeout(10000); + } +}; + +exports.startApplication = function(options) { + options.path = exports.getElectronPath(); + if (process.env.CI) { + options.startTimeout = 30000; + } + + var app = new Application(options); + return app.start().then(function() { + assert.equal(app.isRunning(), true); + chaiAsPromised.transferPromiseness = app.transferPromiseness; + return app; + }); +}; + +exports.stopApplication = function(app) { + if (!app || !app.isRunning()) { + return; + } + + return app.stop().then(function() { + assert.equal(app.isRunning(), false); + }); +}; diff --git a/tests/e2e/ipWhistlist_spec.js b/tests/e2e/ipWhistlist_spec.js index 46fc4cff..ef89aa24 100644 --- a/tests/e2e/ipWhistlist_spec.js +++ b/tests/e2e/ipWhistlist_spec.js @@ -1,24 +1,31 @@ -const globalSetup = require("./global-setup"); -const app = globalSetup.app; +const helpers = require("./global-setup"); +const path = require("path"); const request = require("request"); -const chai = require("chai"); -const expect = chai.expect; +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; describe("ipWhitelist directive configuration", function () { + helpers.setupTimeout(this); - this.timeout(20000); + var app = null; - beforeEach(function (done) { - app.start().then(function() { done(); } ); + beforeEach(function () { + return helpers.startApplication({ + args: ["js/electron.js"] + }).then(function (startedApp) { app = startedApp; }) }); - afterEach(function (done) { - app.stop().then(function() { done(); }); + afterEach(function () { + return helpers.stopApplication(app); }); describe("Set ipWhitelist without access", function () { - before(function() { + before(function () { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/noIpWhiteList.js"; }); @@ -31,7 +38,7 @@ describe("ipWhitelist directive configuration", function () { }); describe("Set ipWhitelist []", function () { - before(function() { + before(function () { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/empty_ipWhiteList.js"; }); diff --git a/tests/e2e/modules/calendar_spec.js b/tests/e2e/modules/calendar_spec.js index c701ed3c..e989cb17 100644 --- a/tests/e2e/modules/calendar_spec.js +++ b/tests/e2e/modules/calendar_spec.js @@ -1,19 +1,32 @@ -const globalSetup = require("../global-setup"); -const serverBasicAuth = require("../../servers/basic-auth.js"); -const app = globalSetup.app; -const chai = require("chai"); -const expect = chai.expect; +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); +const serverBasicAuth = require("../../servers/basic-auth.js"); -describe("Calendar module", function () { +const expect = require("chai").expect; - this.timeout(20000); +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; - beforeEach(function (done) { - app.start().then(function() { done(); } ); +describe("Calendar module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); }); - afterEach(function (done) { - app.stop().then(function() { done(); }); + afterEach(function() { + return helpers.stopApplication(app); }); describe("Default configuration", function() { @@ -22,12 +35,11 @@ describe("Calendar module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/calendar/default.js"; }); - it("Should return TestEvents", function () { + it("Should return TestEvents", function() { return app.client.waitUntilTextExists(".calendar", "TestEvent", 10000); }); }); - describe("Basic auth", function() { before(function() { serverBasicAuth.listen(8010); @@ -35,12 +47,15 @@ describe("Calendar module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/calendar/basic-auth.js"; }); - it("Should return TestEvents", function () { + after(function(done) { + serverBasicAuth.close(done()); + }); + + it("Should return TestEvents", function() { return app.client.waitUntilTextExists(".calendar", "TestEvent", 10000); }); }); - describe("Basic auth by default", function() { before(function() { serverBasicAuth.listen(8011); @@ -48,19 +63,27 @@ describe("Calendar module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/calendar/auth-default.js"; }); - it("Should return TestEvents", function () { + after(function(done) { + serverBasicAuth.close(done()); + }); + + it("Should return TestEvents", function() { return app.client.waitUntilTextExists(".calendar", "TestEvent", 10000); }); }); - describe("Basic auth backward compatibilty configuration", function() { + describe("Basic auth backward compatibilty configuration: DEPRECATED", function() { before(function() { serverBasicAuth.listen(8012); // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/calendar/old-basic-auth.js"; }); - it("Should return TestEvents", function () { + after(function(done) { + serverBasicAuth.close(done()); + }); + + it("Should return TestEvents", function() { return app.client.waitUntilTextExists(".calendar", "TestEvent", 10000); }); }); @@ -72,10 +95,12 @@ describe("Calendar module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/calendar/fail-basic-auth.js"; }); - it("Should return No upcoming events", function () { + after(function(done) { + serverBasicAuth.close(done()); + }); + + it("Should return No upcoming events", function() { return app.client.waitUntilTextExists(".calendar", "No upcoming events.", 10000); }); }); - - }); diff --git a/tests/e2e/modules/clock_es_spec.js b/tests/e2e/modules/clock_es_spec.js index f90263cf..455f3bed 100644 --- a/tests/e2e/modules/clock_es_spec.js +++ b/tests/e2e/modules/clock_es_spec.js @@ -1,8 +1,32 @@ -const globalSetup = require("../global-setup"); -const app = globalSetup.app; +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); -describe("Clock set to spanish language module", function () { - this.timeout(20000); +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("Clock set to spanish language module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); + }); + + afterEach(function() { + return helpers.stopApplication(app); + }); describe("with default 24hr clock config", function() { before(function() { @@ -10,24 +34,14 @@ describe("Clock set to spanish language module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/es/clock_24hr.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - - it("shows date with correct format", function () { + it("shows date with correct format", function() { 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}$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .date").should.eventually.match(dateRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 24hr format", function() { - const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/ - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/; + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); @@ -37,24 +51,14 @@ describe("Clock set to spanish language module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/es/clock_12hr.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - - it("shows date with correct format", function () { + it("shows date with correct format", function() { 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}$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .date").should.eventually.match(dateRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 12hr format", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[ap]m$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); @@ -64,18 +68,23 @@ describe("Clock set to spanish language module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/es/clock_showPeriodUpper.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - it("shows 12hr time with upper case AM/PM", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[AP]M$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); + + describe("with showWeek config enabled", function() { + before(function() { + // Set config sample for use in test + process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/es/clock_showWeek.js"; + }); + + it("shows week with correct format", function() { + const weekRegex = /^Semana [0-9]{1,2}$/; + return app.client.waitUntilWindowLoaded() + .getText(".clock .week").should.eventually.match(weekRegex); + }); + }); + }); diff --git a/tests/e2e/modules/clock_spec.js b/tests/e2e/modules/clock_spec.js index 8c6d9ff6..e342242c 100644 --- a/tests/e2e/modules/clock_spec.js +++ b/tests/e2e/modules/clock_spec.js @@ -1,8 +1,32 @@ -const globalSetup = require("../global-setup"); -const app = globalSetup.app; +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); -describe("Clock module", function () { - this.timeout(20000); +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("Clock module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); + }); + + afterEach(function() { + return helpers.stopApplication(app); + }); describe("with default 24hr clock config", function() { before(function() { @@ -10,24 +34,14 @@ describe("Clock module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_24hr.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - - it("shows date with correct format", function () { + it("shows date with correct format", function() { 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}$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .date").should.eventually.match(dateRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 24hr format", function() { - const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/ - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + const timeRegex = /^(?:2[0-3]|[01]\d):[0-5]\d[0-5]\d$/; + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); @@ -37,24 +51,14 @@ describe("Clock module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_12hr.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - - it("shows date with correct format", function () { + it("shows date with correct format", function() { 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}$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .date").should.eventually.match(dateRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .date").should.eventually.match(dateRegex); }); it("shows time in 12hr format", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[ap]m$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); @@ -64,18 +68,9 @@ describe("Clock module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_showPeriodUpper.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - it("shows 12hr time with upper case AM/PM", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[0-5]\d[AP]M$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); @@ -85,19 +80,29 @@ describe("Clock module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_displaySeconds_false.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - it("shows 12hr time without seconds am/pm", function() { const timeRegex = /^(?:1[0-2]|[1-9]):[0-5]\d[ap]m$/; - return app.client.waitUntilWindowLoaded() - .getText(".clock .time").should.eventually.match(timeRegex); + return app.client.waitUntilWindowLoaded().getText(".clock .time").should.eventually.match(timeRegex); }); }); + describe("with showWeek config enabled", function() { + before(function() { + // Set config sample for use in test + process.env.MM_CONFIG_FILE = "tests/configs/modules/clock/clock_showWeek.js"; + }); + + it("shows week with correct format", function() { + const weekRegex = /^Week [0-9]{1,2}$/; + return app.client.waitUntilWindowLoaded().getText(".clock .week").should.eventually.match(weekRegex); + }); + + it("shows week with correct number of week of year", function() { + it("FIXME: if the day is a sunday this not match"); + // const currentWeekNumber = require("current-week-number")(); + // const weekToShow = "Week " + currentWeekNumber; + // return app.client.waitUntilWindowLoaded() + // .getText(".clock .week").should.eventually.equal(weekToShow); + }); + }); }); diff --git a/tests/e2e/modules/compliments_spec.js b/tests/e2e/modules/compliments_spec.js index 0dd2c411..a840981e 100644 --- a/tests/e2e/modules/compliments_spec.js +++ b/tests/e2e/modules/compliments_spec.js @@ -1,77 +1,81 @@ -const globalSetup = require("../global-setup"); -const app = globalSetup.app; -const chai = require("chai"); -const expect = chai.expect; +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); -describe("Compliments module", function () { - this.timeout(20000); +const expect = require("chai").expect; +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; - beforeEach(function (done) { - app.start().then(function() { done(); } ); +describe("Compliments module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); }); - afterEach(function (done) { - app.stop().then(function() { done(); }); + afterEach(function() { + return helpers.stopApplication(app); }); - describe("parts of days", function() { - before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/compliments/compliments_parts_day.js"; }); - it("if Morning compliments for that part of day", function () { + it("if Morning compliments for that part of day", function() { var hour = new Date().getHours(); if (hour >= 3 && hour < 12) { // if morning check - return app.client.waitUntilWindowLoaded() - .getText(".compliments").then(function (text) { - expect(text).to.be.oneOf(["Hi", "Good Morning", "Morning test"]); - }) + return app.client.waitUntilWindowLoaded().getText(".compliments").then(function(text) { + expect(text).to.be.oneOf(["Hi", "Good Morning", "Morning test"]); + }); } }); - it("if Afternoon show Compliments for that part of day", function () { + it("if Afternoon show Compliments for that part of day", function() { var hour = new Date().getHours(); if (hour >= 12 && hour < 17) { // if morning check - return app.client.waitUntilWindowLoaded() - .getText(".compliments").then(function (text) { - expect(text).to.be.oneOf(["Hello", "Good Afternoon", "Afternoon test"]); - }) + return app.client.waitUntilWindowLoaded().getText(".compliments").then(function(text) { + expect(text).to.be.oneOf(["Hello", "Good Afternoon", "Afternoon test"]); + }); } }); - it("if Evening show Compliments for that part of day", function () { + it("if Evening show Compliments for that part of day", function() { var hour = new Date().getHours(); if (!(hour >= 3 && hour < 12) && !(hour >= 12 && hour < 17)) { // if evening check - return app.client.waitUntilWindowLoaded() - .getText(".compliments").then(function (text) { - expect(text).to.be.oneOf(["Hello There", "Good Evening", "Evening test"]); - }) + return app.client.waitUntilWindowLoaded().getText(".compliments").then(function(text) { + expect(text).to.be.oneOf(["Hello There", "Good Evening", "Evening test"]); + }); } }); - }); - describe("Feature anytime in compliments module", function() { - describe("Set anytime and empty compliments for morning, evening and afternoon ", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/compliments/compliments_anytime.js"; }); - it("Show anytime because if configure empty parts of day compliments and set anytime compliments", function () { - return app.client.waitUntilWindowLoaded() - .getText(".compliments").then(function (text) { - expect(text).to.be.oneOf(["Anytime here"]); - }) + it("Show anytime because if configure empty parts of day compliments and set anytime compliments", function() { + return app.client.waitUntilWindowLoaded().getText(".compliments").then(function(text) { + expect(text).to.be.oneOf(["Anytime here"]); + }); }); }); @@ -81,15 +85,11 @@ describe("Compliments module", function () { process.env.MM_CONFIG_FILE = "tests/configs/modules/compliments/compliments_only_anytime.js"; }); - it("Show anytime compliments", function () { - return app.client.waitUntilWindowLoaded() - .getText(".compliments").then(function (text) { - expect(text).to.be.oneOf(["Anytime here"]); - }) + it("Show anytime compliments", function() { + return app.client.waitUntilWindowLoaded().getText(".compliments").then(function(text) { + expect(text).to.be.oneOf(["Anytime here"]); + }); }); }); - - }); - }); diff --git a/tests/e2e/modules/helloworld_spec.js b/tests/e2e/modules/helloworld_spec.js index 8053373e..655594b0 100644 --- a/tests/e2e/modules/helloworld_spec.js +++ b/tests/e2e/modules/helloworld_spec.js @@ -1,16 +1,32 @@ -const globalSetup = require("../global-setup"); -const app = globalSetup.app; +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); -describe("Test helloworld module", function () { - this.timeout(20000); +const expect = require("chai").expect; +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; - beforeEach(function (done) { - app.start().then(function() { done(); } ); +describe("Test helloworld module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); }); - afterEach(function (done) { - app.stop().then(function() { done(); }); + + afterEach(function() { + return helpers.stopApplication(app); }); describe("helloworld set config text", function () { diff --git a/tests/e2e/modules/newsfeed_spec.js b/tests/e2e/modules/newsfeed_spec.js new file mode 100644 index 00000000..e062121c --- /dev/null +++ b/tests/e2e/modules/newsfeed_spec.js @@ -0,0 +1,40 @@ +const helpers = require("../global-setup"); +const path = require("path"); +const request = require("request"); + +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("Newsfeed module", function() { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function() { + return helpers + .startApplication({ + args: ["js/electron.js"] + }) + .then(function(startedApp) { + app = startedApp; + }); + }); + + afterEach(function() { + return helpers.stopApplication(app); + }); + + describe("Default configuration", function() { + before(function() { + process.env.MM_CONFIG_FILE = "tests/configs/modules/newsfeed/default.js"; + }); + + it("show title newsfeed", function() { + return app.client.waitUntilTextExists(".newsfeed .small", "Rodrigo Ramirez Blog", 10000).should.be.fulfilled; + }); + }); +}); diff --git a/tests/e2e/modules_position_spec.js b/tests/e2e/modules_position_spec.js new file mode 100644 index 00000000..d3091cad --- /dev/null +++ b/tests/e2e/modules_position_spec.js @@ -0,0 +1,50 @@ +const helpers = require("./global-setup"); +const path = require("path"); +const request = require("request"); + +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("Position of modules", function () { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function () { + return helpers.startApplication({ + args: ["js/electron.js"] + }).then(function (startedApp) { app = startedApp; }) + }); + + afterEach(function () { + return helpers.stopApplication(app); + }); + + describe("Using helloworld", function () { + + before(function () { + // Set config sample for use in test + process.env.MM_CONFIG_FILE = "tests/configs/modules/positions.js"; + }); + + var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", + "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", + "bottom_bar", "fullscreen_above", "fullscreen_below"]; + + var position; + var className; + for (idx in positions) { + position = positions[idx]; + className = position.replace("_", "."); + it("show text in " + position, function () { + return app.client.waitUntilWindowLoaded() + .getText("." + className).should.eventually.equal("Text in " + position); + }); + } + }); + +}); diff --git a/tests/e2e/port_config.js b/tests/e2e/port_config.js new file mode 100644 index 00000000..00964d53 --- /dev/null +++ b/tests/e2e/port_config.js @@ -0,0 +1,60 @@ +const helpers = require("./global-setup"); +const path = require("path"); +const request = require("request"); + +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; + +describe("port directive configuration", function () { + helpers.setupTimeout(this); + + var app = null; + + beforeEach(function () { + return helpers.startApplication({ + args: ["js/electron.js"] + }).then(function (startedApp) { app = startedApp; }) + }); + + afterEach(function () { + return helpers.stopApplication(app); + }); + + describe("Set port 8090", function () { + before(function () { + // Set config sample for use in this test + process.env.MM_CONFIG_FILE = "tests/configs/port_8090.js"; + }); + + it("should return 200", function (done) { + request.get("http://localhost:8090", function (err, res, body) { + expect(res.statusCode).to.equal(200); + done(); + }); + }); + }); + + describe("Set port 8100 on enviroment variable MM_PORT", function () { + before(function () { + process.env.MM_PORT = 8100; + // Set config sample for use in this test + process.env.MM_CONFIG_FILE = "tests/configs/port_8090.js"; + }); + + after(function () { + delete process.env.MM_PORT; + }); + + it("should return 200", function (done) { + request.get("http://localhost:8100", function (err, res, body) { + expect(res.statusCode).to.equal(200); + done(); + }); + }); + }); + +}); diff --git a/tests/e2e/vendor_spec.js b/tests/e2e/vendor_spec.js new file mode 100644 index 00000000..0d9751f1 --- /dev/null +++ b/tests/e2e/vendor_spec.js @@ -0,0 +1,46 @@ +const helpers = require("./global-setup"); +const path = require("path"); +const request = require("request"); + +const expect = require("chai").expect; + +const describe = global.describe; +const it = global.it; +const before = global.before; +const after = global.after; + +describe("Vendors", function () { + + return; // Test still getting failed in Travis + + helpers.setupTimeout(this); + + var app = null; + + before(function () { + return helpers.startApplication({ + args: ["js/electron.js"] + }).then(function (startedApp) { app = startedApp; }) + }); + + after(function () { + return helpers.stopApplication(app); + }); + + describe("Get list vendors", function () { + + before(function () { + process.env.MM_CONFIG_FILE = "tests/configs/env.js"; + }); + + var vendors = require(__dirname + "/../../vendor/vendor.js"); + Object.keys(vendors).forEach(vendor => { + it(`should return 200 HTTP code for vendor "${vendor}"`, function () { + urlVendor = "http://localhost:8080/vendor/" + vendors[vendor]; + request.get(urlVendor, function (err, res, body) { + expect(res.statusCode).to.equal(200); + }); + }); + }); + }); +}); diff --git a/tests/e2e/without_modules.js b/tests/e2e/without_modules.js index 73e845f8..e0eda168 100644 --- a/tests/e2e/without_modules.js +++ b/tests/e2e/without_modules.js @@ -1,44 +1,34 @@ -const Application = require("spectron").Application; +const helpers = require("./global-setup"); const path = require("path"); -const chai = require("chai"); -const chaiAsPromised = require("chai-as-promised"); - -var electronPath = path.join(__dirname, "../../", "node_modules", ".bin", "electron"); - -if (process.platform === "win32") { - electronPath += ".cmd"; -} - -var appPath = path.join(__dirname, "../../js/electron.js"); - -var app = new Application({ - path: electronPath, - args: [appPath] -}); - -global.before(function () { - chai.should(); - chai.use(chaiAsPromised); -}); +const request = require("request"); +const expect = require("chai").expect; +const describe = global.describe; +const it = global.it; +const beforeEach = global.beforeEach; +const afterEach = global.afterEach; describe("Check configuration without modules", function () { - this.timeout(20000); + helpers.setupTimeout(this); - before(function() { - // Set config sample for use in test + var app = null; + + beforeEach(function () { + return helpers.startApplication({ + args: ["js/electron.js"] + }).then(function (startedApp) { app = startedApp; }) + }); + + afterEach(function () { + return helpers.stopApplication(app); + }); + + before(function () { + // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/without_modules.js"; }); - beforeEach(function (done) { - app.start().then(function() { done(); } ); - }); - - afterEach(function (done) { - app.stop().then(function() { done(); }); - }); - it("Show the message MagicMirror title", function () { return app.client.waitUntilWindowLoaded() .getText("#module_1_helloworld .module-content").should.eventually.equal("Magic Mirror2") diff --git a/tests/servers/basic-auth.js b/tests/servers/basic-auth.js index 238bdc26..c409ad2d 100644 --- a/tests/servers/basic-auth.js +++ b/tests/servers/basic-auth.js @@ -1,16 +1,21 @@ var http = require("http"); var path = require("path"); var auth = require("http-auth"); -var express = require("express") +var express = require("express"); +var app = express(); -var basic = auth.basic({ - realm: "MagicMirror Area restricted." -}, (username, password, callback) => { - callback(username === "MagicMirror" && password === "CallMeADog"); -}); +var server; -this.server = express(); -this.server.use(auth.connect(basic)); +var basic = auth.basic( + { + realm: "MagicMirror Area restricted." + }, + (username, password, callback) => { + callback(username === "MagicMirror" && password === "CallMeADog"); + } +); + +app.use(auth.connect(basic)); // Set directories availables var directories = ["/tests/configs"]; @@ -18,13 +23,13 @@ var directory; rootPath = path.resolve(__dirname + "/../../"); for (i in directories) { directory = directories[i]; - this.server.use(directory, express.static(path.resolve(rootPath + directory))); + app.use(directory, express.static(path.resolve(rootPath + directory))); } -exports.listen = function () { - this.server.listen.apply(this.server, arguments); +exports.listen = function() { + server = app.listen.apply(app, arguments); }; -exports.close = function (callback) { - this.server.close(callback); +exports.close = function(callback) { + server.close(callback); }; diff --git a/tests/unit/functions/calendar_spec.js b/tests/unit/functions/calendar_spec.js new file mode 100644 index 00000000..d4035f33 --- /dev/null +++ b/tests/unit/functions/calendar_spec.js @@ -0,0 +1,128 @@ +const expect = require("chai").expect; + +global.moment = require("moment"); + +describe("Functions into modules/default/calendar/calendar.js", function() { + + // Fake for use by calendar.js + Module = {} + Module.definitions = {}; + Module.register = function (name, moduleDefinition) { + Module.definitions[name] = moduleDefinition; + }; + + before(function() { + // load calendar.js + require("../../../modules/default/calendar/calendar.js"); + }); + + describe("capFirst", function() { + words = { + "rodrigo": "Rodrigo", + "123m": "123m", + "magic mirror": "Magic mirror", + ",a": ",a", + "ñandú": "Ñandú" + }; + + Object.keys(words).forEach(word => { + it(`for '${word}' should return '${words[word]}'`, function() { + expect(Module.definitions.calendar.capFirst(word)).to.equal(words[word]); + }); + }); + }); + + describe("getLocaleSpecification", function() { + it("Should return a valid moment.LocaleSpecification for a 12-hour format", function() { + expect(Module.definitions.calendar.getLocaleSpecification(12)).to.deep.equal({ longDateFormat: {LT: "h:mm A"} }); + }); + + it("Should return a valid moment.LocaleSpecification for a 24-hour format", function() { + expect(Module.definitions.calendar.getLocaleSpecification(24)).to.deep.equal({ longDateFormat: {LT: "HH:mm"} }); + }); + + it("Should return the current system locale when called without timeFormat number", function() { + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: moment.localeData().longDateFormat("LT")} } ); + }); + + it("Should return a 12-hour longDateFormat when using the 'en' locale", function() { + var localeBackup = moment.locale(); + moment.locale("en"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "h:mm A"} }); + moment.locale(localeBackup); + }); + + it("Should return a 12-hour longDateFormat when using the 'au' locale", function() { + var localeBackup = moment.locale(); + moment.locale("au"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "h:mm A"} }); + moment.locale(localeBackup); + }); + + it("Should return a 12-hour longDateFormat when using the 'eg' locale", function() { + var localeBackup = moment.locale(); + moment.locale("eg"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "h:mm A"} }); + moment.locale(localeBackup); + }); + + it("Should return a 24-hour longDateFormat when using the 'nl' locale", function() { + var localeBackup = moment.locale(); + moment.locale("nl"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "HH:mm"} }); + moment.locale(localeBackup); + }); + + it("Should return a 24-hour longDateFormat when using the 'fr' locale", function() { + var localeBackup = moment.locale(); + moment.locale("fr"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "HH:mm"} }); + moment.locale(localeBackup); + }); + + it("Should return a 24-hour longDateFormat when using the 'uk' locale", function() { + var localeBackup = moment.locale(); + moment.locale("uk"); + expect(Module.definitions.calendar.getLocaleSpecification()).to.deep.equal({ longDateFormat: {LT: "HH:mm"} }); + moment.locale(localeBackup); + }); + }); + + describe("shorten", function() { + strings = { + " String with whitespace at the beginning that needs trimming" : { length: 16, return: "String with whit…" }, + "long string that needs shortening": { length: 16, return: "long string that…" }, + "short string": { length: 16, return: "short string" }, + "long string with no maxLength defined": { return: "long string with no maxLength defined" }, + }; + + Object.keys(strings).forEach(string => { + it(`for '${string}' should return '${strings[string].return}'`, function() { + expect(Module.definitions.calendar.shorten(string, strings[string].length)).to.equal(strings[string].return); + }); + }); + + it("should return an empty string if shorten is called with a non-string", function () { + expect(Module.definitions.calendar.shorten(100)).to.equal(""); + }); + + it("should not shorten the string if shorten is called with a non-number maxLength", function () { + expect(Module.definitions.calendar.shorten("This is a test string", "This is not a number")).to.equal("This is a test string"); + }); + + it("should wrap the string instead of shorten it if shorten is called with wrapEvents = true (with maxLength defined as 20)", function () { + expect(Module.definitions.calendar.shorten( + "This is a wrapEvent test. Should wrap the string instead of shorten it if called with wrapEvent = true", + 20, + true)).to.equal("This is a
wrapEvent test. Should wrap
the string instead of
shorten it if called with
wrapEvent = true"); + }); + + it("should wrap the string instead of shorten it if shorten is called with wrapEvents = true (without maxLength defined, default 25)", function () { + expect(Module.definitions.calendar.shorten( + "This is a wrapEvent test. Should wrap the string instead of shorten it if called with wrapEvent = true", + undefined, + true)).to.equal("This is a wrapEvent
test. Should wrap the string
instead of shorten it if called
with wrapEvent = true"); + }); + }); +}); + diff --git a/tests/unit/functions/class_spec.js b/tests/unit/functions/class_spec.js new file mode 100644 index 00000000..e2e6d521 --- /dev/null +++ b/tests/unit/functions/class_spec.js @@ -0,0 +1,51 @@ +var chai = require("chai"); +var expect = chai.expect; +var jsClass = require("../../../js/class.js"); + +describe("File js/class", function() { + describe("Test function cloneObject", function() { + var cloneObject = jsClass._test.cloneObject; + + it("should be return equals object", function() { + var expected = {name: "Rodrigo", web: "https://rodrigoramirez.com", project: "MagicMirror"}; + var obj = {}; + obj = cloneObject(expected); + expect(expected).to.deep.equal(obj); + }); + + it("should be return equals int", function() { + var expected = 1; + var obj = {}; + obj = cloneObject(expected); + expect(expected).to.equal(obj); + }); + + it("should be return equals string", function() { + var expected = "Perfect stranger"; + var obj = {}; + obj = cloneObject(expected); + expect(expected).to.equal(obj); + }); + + it("should be return equals undefined", function() { + var expected = undefined; + var obj = {}; + obj = cloneObject(expected); + expect(undefined).to.equal(obj); + }); + + // CoverageME + /* + context("Test lockstring code", function() { + it("should be return equals object", function() { + var expected = {name: "Module", lockStrings: "stringLock"}; + var obj = {}; + obj = cloneObject(expected); + expect(expected).to.deep.equal(obj); + }); + }); + */ + + }); +}); + diff --git a/tests/unit/functions/currentweather_spec.js b/tests/unit/functions/currentweather_spec.js new file mode 100644 index 00000000..18b52c81 --- /dev/null +++ b/tests/unit/functions/currentweather_spec.js @@ -0,0 +1,78 @@ +var fs = require("fs"); +var path = require("path"); +var chai = require("chai"); +var expect = chai.expect; +var vm = require("vm"); + + +describe("Functions module currentweather", function() { + + + // Fake for use by currentweather.js + Module = {}; + config = {}; + Module.definitions = {}; + Module.register = function (name, moduleDefinition) { + Module.definitions[name] = moduleDefinition; + }; + + + before(function(){ + require("../../../modules/default/currentweather/currentweather.js"); + Module.definitions.currentweather.config = {}; + }); + + describe("roundValue", function() { + + describe("this.config.roundTemp is true", function() { + before(function(){ + Module.definitions.currentweather.config.roundTemp = true; + }); + + var values = [ + // index 0 value + // index 1 expect + [1 , "1"], + [1.0 , "1"], + [1.02 , "1"], + [10.12 , "10"], + [2.0 , "2"], + ["2.12" , "2"], + [10.1 , "10"] + ] + + values.forEach(value => { + it(`for ${value[0]} should be return ${value[1]}`, function() { + expect(Module.definitions.currentweather.roundValue(value[0])).to.equal(value[1]); + }); + }); + }); + + + describe("this.config.roundTemp is false", function() { + + before(function(){ + Module.definitions.currentweather.config.roundTemp = false; + }); + + var values = [ + // index 0 value + // index 1 expect + [1 , "1.0"], + [1.0 , "1.0"], + [1.02 , "1.0"], + [10.12 , "10.1"], + [2.0 , "2.0"], + ["2.12" , "2.1"], + [10.1 , "10.1"], + [10.10 , "10.1"] + ] + + values.forEach(value => { + it(`for ${value[0]} should be return ${value[1]}`, function() { + expect(Module.definitions.currentweather.roundValue(value[0])).to.equal(value[1]); + }); + }); + }); + }); +}); diff --git a/tests/unit/functions/newsfeed_spec.js b/tests/unit/functions/newsfeed_spec.js new file mode 100644 index 00000000..583d696a --- /dev/null +++ b/tests/unit/functions/newsfeed_spec.js @@ -0,0 +1,37 @@ +var fs = require("fs"); +var path = require("path"); +var chai = require("chai"); +var expect = chai.expect; +var vm = require("vm"); + + +describe("Functions into modules/default/newsfeed/newsfeed.js", function() { + + Module = {} + Module.definitions = {}; + Module.register = function (name, moduleDefinition) { + Module.definitions[name] = moduleDefinition; + }; + + // load newsfeed.js + require("../../../modules/default/newsfeed/newsfeed.js"); + + describe("capitalizeFirstLetter", function() { + words = { + "rodrigo": "Rodrigo", + "123m": "123m", + "magic mirror": "Magic mirror", + ",a": ",a", + "ñandú": "Ñandú", + ".!": ".!" + }; + + Object.keys(words).forEach(word => { + it(`for ${word} should return ${words[word]}`, function() { + expect(Module.definitions.newsfeed.capitalizeFirstLetter(word)).to.equal(words[word]); + }); + }); + }); + +}); + diff --git a/tests/unit/global_vars/defaults_modules_spec.js b/tests/unit/global_vars/defaults_modules_spec.js new file mode 100644 index 00000000..8df0d073 --- /dev/null +++ b/tests/unit/global_vars/defaults_modules_spec.js @@ -0,0 +1,66 @@ +var fs = require("fs"); +var path = require("path"); +var chai = require("chai"); +var expect = chai.expect; +var vm = require("vm"); + +before(function() { + var basedir = path.join(__dirname, "../../.."); + + var fileName = "js/app.js"; + var filePath = path.join(basedir, fileName); + var code = fs.readFileSync(filePath); + + this.sandbox = { + module: {}, + __dirname: path.dirname(filePath), + global: {}, + console: { + log: function() { /*console.log("console.log(", arguments, ")");*/ } + }, + process: { + on: function() { /*console.log("process.on called with: ", arguments);*/ }, + env: {} + } + }; + + this.sandbox.require = function(filename) { + // This modifies the global slightly, + // but supplies vm with essential code + return require(filename); + }; + + vm.runInNewContext(code, this.sandbox, fileName); +}); + +after(function() { + //console.log(global); +}); + +describe("Default modules set in modules/default/defaultmodules.js", function() { + + var expectedDefaultModules = [ + "alert", + "calendar", + "clock", + "compliments", + "currentweather", + "helloworld", + "newsfeed", + "weatherforecast", + "updatenotification" + ]; + + expectedDefaultModules.forEach(defaultModule => { + it(`contains default module "${defaultModule}"`, function() { + expect(this.sandbox.defaultModules).to.include(defaultModule); + }); + }); + + expectedDefaultModules.forEach(defaultModule => { + it(`contains a folder for modules/default/${defaultModule}"`, function() { + expect(fs.existsSync(path.join(this.sandbox.global.root_path, "modules/default", defaultModule))).to.equal(true); + }); + }); + +}); diff --git a/tests/unit/global_vars/root_path_spec.js b/tests/unit/global_vars/root_path_spec.js index 197ee6a7..ef7ce3e9 100644 --- a/tests/unit/global_vars/root_path_spec.js +++ b/tests/unit/global_vars/root_path_spec.js @@ -63,8 +63,8 @@ describe("'global.root_path' set in js/app.js", function() { }); it("should expect the global.version equals package.json file", function() { - version_package = JSON.parse(fs.readFileSync("package.json", "utf8")).version; - expect(this.sandbox.global.version).to.equal(version_package); + versionPackage = JSON.parse(fs.readFileSync("package.json", "utf8")).version; + expect(this.sandbox.global.version).to.equal(versionPackage); }); }); diff --git a/translations/de.json b/translations/de.json index eb67d41a..2723bf86 100644 --- a/translations/de.json +++ b/translations/de.json @@ -7,6 +7,8 @@ "RUNNING": "noch", "EMPTY": "Keine Termine.", + "WEEK": "Woche", + "N": "N", "NNE": "NNO", "NE": "NO", diff --git a/translations/en.json b/translations/en.json index 46061738..a1472cf1 100644 --- a/translations/en.json +++ b/translations/en.json @@ -7,6 +7,8 @@ "RUNNING": "Ends in", "EMPTY": "No upcoming events.", + "WEEK": "Week", + "N": "N", "NNE": "NNE", "NE": "NE", diff --git a/translations/es.json b/translations/es.json index 914a72ce..adee4dfc 100644 --- a/translations/es.json +++ b/translations/es.json @@ -7,6 +7,8 @@ "RUNNING": "Termina en", "EMPTY": "No hay eventos programados.", + "WEEK": "Semana", + "N": "N", "NNE": "NNE", "NE": "NE", diff --git a/translations/fi.json b/translations/fi.json index 08bc4060..c013e310 100644 --- a/translations/fi.json +++ b/translations/fi.json @@ -4,7 +4,7 @@ "TODAY": "Tänään", "TOMORROW": "Huomenna", "DAYAFTERTOMORROW": "Ylihuomenna", - "RUNNING": "Meneillään", + "RUNNING": "Päättyy {timeUntilEnd} päästä", "EMPTY": "Ei tulevia tapahtumia.", "N": "P", diff --git a/translations/nb.json b/translations/nb.json index 9a3060be..3aad4263 100644 --- a/translations/nb.json +++ b/translations/nb.json @@ -7,6 +7,8 @@ "RUNNING": "Slutter om", "EMPTY": "Ingen kommende arrangementer.", + "WEEK": "Uke", + "N": "N", "NNE": "NNØ", "NE": "NØ", @@ -24,7 +26,7 @@ "NW": "NV", "NNW": "NNV", - "UPDATE_NOTIFICATION": "MagicMirror² oppdatering er tilgjengelig.", + "UPDATE_NOTIFICATION": "MagicMirror²-oppdatering er tilgjengelig.", "UPDATE_NOTIFICATION_MODULE": "Oppdatering tilgjengelig for modulen MODULE_NAME.", "UPDATE_INFO": "Nåværende installasjon er COMMIT_COUNT bak BRANCH_NAME grenen." } diff --git a/translations/pl.json b/translations/pl.json index 0c79835f..1d30e395 100644 --- a/translations/pl.json +++ b/translations/pl.json @@ -3,9 +3,12 @@ "TODAY": "Dziś", "TOMORROW": "Jutro", + "DAYAFTERTOMORROW": "Pojutrze", "RUNNING": "Koniec za", "EMPTY": "Brak wydarzeń.", + "WEEK": "Tydzień", + "N": "N", "NNE": "NNE", "NE": "NE", diff --git a/translations/ro.json b/translations/ro.json new file mode 100644 index 00000000..4105763e --- /dev/null +++ b/translations/ro.json @@ -0,0 +1,32 @@ +{ + "LOADING": "Se încarcă …", + + "TODAY": "Astăzi", + "TOMORROW": "Mâine", + "DAYAFTERTOMORROW": "Poimâine", + "RUNNING": "Se termină în", + "EMPTY": "Nici un eveniment.", + + "WEEK": "Săptămâna", + + "N": "N", + "NNE": "NNE", + "NE": "NE", + "ENE": "ENE", + "E": "E", + "ESE": "ESE", + "SE": "SE", + "SSE": "SSE", + "S": "S", + "SSW": "SSW", + "SW": "SW", + "WSW": "WSW", + "W": "W", + "WNW": "WNW", + "NW": "NW", + "NNW": "NNW", + + "UPDATE_NOTIFICATION": "Un update este disponibil pentru MagicMirror².", + "UPDATE_NOTIFICATION_MODULE": "Un update este disponibil pentru modulul MODULE_NAME.", + "UPDATE_INFO": "Există COMMIT_COUNT commit-uri noi pe branch-ul BRANCH_NAME." +} diff --git a/translations/ru.json b/translations/ru.json index 48c49fd9..c919af50 100644 --- a/translations/ru.json +++ b/translations/ru.json @@ -7,6 +7,8 @@ "RUNNING": "Заканчивается через", "EMPTY": "Нет предстоящих событий", + "WEEK": "Неделя", + "N": "С", "NNE": "ССВ", "NE": "СВ", diff --git a/translations/sv.json b/translations/sv.json index 1fe3d48d..13288ec3 100644 --- a/translations/sv.json +++ b/translations/sv.json @@ -1,12 +1,14 @@ { "LOADING": "Laddar …", - "TODAY": "Idag", - "TOMORROW": "Imorgon", - "DAYAFTERTOMORROW": "Iövermorgon", + "TODAY": "I dag", + "TOMORROW": "I morgon", + "DAYAFTERTOMORROW": "I övermorgon", "RUNNING": "Slutar", "EMPTY": "Inga kommande händelser.", + "WEEK": "Vecka", + "N": "N", "NNE": "NNO", "NE": "NO", diff --git a/translations/translations.js b/translations/translations.js index 61701ab9..ad40652c 100644 --- a/translations/translations.js +++ b/translations/translations.js @@ -33,6 +33,7 @@ var translations = { "is" : "translations/is.json", // Icelandic "et" : "translations/et.json", // Estonian "kr" : "translations/kr.json", // Korean + "ro" : "translations/ro.json", // Romanian }; if (typeof module !== "undefined") {module.exports = translations;} diff --git a/translations/zh_cn.json b/translations/zh_cn.json index e7f69616..5efbb691 100644 --- a/translations/zh_cn.json +++ b/translations/zh_cn.json @@ -3,6 +3,7 @@ "TODAY": "今天", "TOMORROW": "明天", + "DAYAFTERTOMORROW": "后天", "RUNNING": "结束日期", "EMPTY": "没有更多的活动。", @@ -21,5 +22,9 @@ "W": "西风", "WNW": "西偏北风", "NW": "西北风", - "NNW": "北偏西风" + "NNW": "北偏西风", + + "UPDATE_NOTIFICATION": "MagicMirror² 有新的更新", + "UPDATE_NOTIFICATION_MODULE": "模块 MODULE_NAME 可更新", + "UPDATE_INFO": "当前已安装版本为 COMMIT_COUNT 落后于分支 BRANCH_NAME " } diff --git a/vendor/vendor.js b/vendor/vendor.js index 7076cc45..c191ce90 100644 --- a/vendor/vendor.js +++ b/vendor/vendor.js @@ -9,8 +9,10 @@ var vendor = { "moment.js" : "node_modules/moment/min/moment-with-locales.js", - "moment-timezone.js" : "node_modules/moment-timezone/moment-timezone.js", + "moment-timezone.js" : "node_modules/moment-timezone/builds/moment-timezone-with-data.js", "weather-icons.css": "node_modules/weathericons/css/weather-icons.css", "weather-icons-wind.css": "node_modules/weathericons/css/weather-icons-wind.css", "font-awesome.css": "node_modules/font-awesome/css/font-awesome.min.css" }; + +if (typeof module !== "undefined"){module.exports = vendor;}