Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

module.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /* global Class, cloneObject, Loader, MMSocket, nunjucks, Translator */
  2. /* Magic Mirror
  3. * Module Blueprint.
  4. * @typedef {Object} Module
  5. *
  6. * By Michael Teeuw https://michaelteeuw.nl
  7. * MIT Licensed.
  8. */
  9. const Module = Class.extend({
  10. /*********************************************************
  11. * All methods (and properties) below can be subclassed. *
  12. *********************************************************/
  13. // Set the minimum MagicMirror module version for this module.
  14. requiresVersion: "2.0.0",
  15. // Module config defaults.
  16. defaults: {},
  17. // Timer reference used for showHide animation callbacks.
  18. showHideTimer: null,
  19. // Array to store lockStrings. These strings are used to lock
  20. // visibility when hiding and showing module.
  21. lockStrings: [],
  22. // Storage of the nunjuck Environment,
  23. // This should not be referenced directly.
  24. // Use the nunjucksEnvironment() to get it.
  25. _nunjucksEnvironment: null,
  26. /**
  27. * Called when the module is instantiated.
  28. */
  29. init: function () {
  30. //Log.log(this.defaults);
  31. },
  32. /**
  33. * Called when the module is started.
  34. */
  35. start: function () {
  36. Log.info("Starting module: " + this.name);
  37. },
  38. /**
  39. * Returns a list of scripts the module requires to be loaded.
  40. *
  41. * @returns {string[]} An array with filenames.
  42. */
  43. getScripts: function () {
  44. return [];
  45. },
  46. /**
  47. * Returns a list of stylesheets the module requires to be loaded.
  48. *
  49. * @returns {string[]} An array with filenames.
  50. */
  51. getStyles: function () {
  52. return [];
  53. },
  54. /**
  55. * Returns a map of translation files the module requires to be loaded.
  56. *
  57. * return Map<String, String> -
  58. *
  59. * @returns {*} A map with langKeys and filenames.
  60. */
  61. getTranslations: function () {
  62. return false;
  63. },
  64. /**
  65. * Generates the dom which needs to be displayed. This method is called by the Magic Mirror core.
  66. * This method can to be subclassed if the module wants to display info on the mirror.
  67. * Alternatively, the getTemplate method could be subclassed.
  68. *
  69. * @returns {HTMLElement|Promise} The dom or a promise with the dom to display.
  70. */
  71. getDom: function () {
  72. return new Promise((resolve) => {
  73. const div = document.createElement("div");
  74. const template = this.getTemplate();
  75. const templateData = this.getTemplateData();
  76. // Check to see if we need to render a template string or a file.
  77. if (/^.*((\.html)|(\.njk))$/.test(template)) {
  78. // the template is a filename
  79. this.nunjucksEnvironment().render(template, templateData, function (err, res) {
  80. if (err) {
  81. Log.error(err);
  82. }
  83. div.innerHTML = res;
  84. resolve(div);
  85. });
  86. } else {
  87. // the template is a template string.
  88. div.innerHTML = this.nunjucksEnvironment().renderString(template, templateData);
  89. resolve(div);
  90. }
  91. });
  92. },
  93. /**
  94. * Generates the header string which needs to be displayed if a user has a header configured for this module.
  95. * This method is called by the Magic Mirror core, but only if the user has configured a default header for the module.
  96. * This method needs to be subclassed if the module wants to display modified headers on the mirror.
  97. *
  98. * @returns {string} The header to display above the header.
  99. */
  100. getHeader: function () {
  101. return this.data.header;
  102. },
  103. /**
  104. * Returns the template for the module which is used by the default getDom implementation.
  105. * This method needs to be subclassed if the module wants to use a template.
  106. * It can either return a template sting, or a template filename.
  107. * If the string ends with '.html' it's considered a file from within the module's folder.
  108. *
  109. * @returns {string} The template string of filename.
  110. */
  111. getTemplate: function () {
  112. return '<div class="normal">' + this.name + '</div><div class="small dimmed">' + this.identifier + "</div>";
  113. },
  114. /**
  115. * Returns the data to be used in the template.
  116. * This method needs to be subclassed if the module wants to use a custom data.
  117. *
  118. * @returns {object} The data for the template
  119. */
  120. getTemplateData: function () {
  121. return {};
  122. },
  123. /**
  124. * Called by the Magic Mirror core when a notification arrives.
  125. *
  126. * @param {string} notification The identifier of the notification.
  127. * @param {*} payload The payload of the notification.
  128. * @param {Module} sender The module that sent the notification.
  129. */
  130. notificationReceived: function (notification, payload, sender) {
  131. if (sender) {
  132. // Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
  133. } else {
  134. // Log.log(this.name + " received a system notification: " + notification);
  135. }
  136. },
  137. /**
  138. * Returns the nunjucks environment for the current module.
  139. * The environment is checked in the _nunjucksEnvironment instance variable.
  140. *
  141. * @returns {object} The Nunjucks Environment
  142. */
  143. nunjucksEnvironment: function () {
  144. if (this._nunjucksEnvironment !== null) {
  145. return this._nunjucksEnvironment;
  146. }
  147. this._nunjucksEnvironment = new nunjucks.Environment(new nunjucks.WebLoader(this.file(""), { async: true }), {
  148. trimBlocks: true,
  149. lstripBlocks: true
  150. });
  151. this._nunjucksEnvironment.addFilter("translate", (str, variables) => {
  152. return nunjucks.runtime.markSafe(this.translate(str, variables));
  153. });
  154. return this._nunjucksEnvironment;
  155. },
  156. /**
  157. * Called when a socket notification arrives.
  158. *
  159. * @param {string} notification The identifier of the notification.
  160. * @param {*} payload The payload of the notification.
  161. */
  162. socketNotificationReceived: function (notification, payload) {
  163. Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
  164. },
  165. /**
  166. * Called when the module is hidden.
  167. */
  168. suspend: function () {
  169. Log.log(this.name + " is suspended.");
  170. },
  171. /**
  172. * Called when the module is shown.
  173. */
  174. resume: function () {
  175. Log.log(this.name + " is resumed.");
  176. },
  177. /*********************************************
  178. * The methods below don"t need subclassing. *
  179. *********************************************/
  180. /**
  181. * Set the module data.
  182. *
  183. * @param {object} data The module data
  184. */
  185. setData: function (data) {
  186. this.data = data;
  187. this.name = data.name;
  188. this.identifier = data.identifier;
  189. this.hidden = false;
  190. this.setConfig(data.config, data.configDeepMerge);
  191. },
  192. /**
  193. * Set the module config and combine it with the module defaults.
  194. *
  195. * @param {object} config The combined module config.
  196. * @param {boolean} deep Merge module config in deep.
  197. */
  198. setConfig: function (config, deep) {
  199. this.config = deep ? configMerge({}, this.defaults, config) : Object.assign({}, this.defaults, config);
  200. },
  201. /**
  202. * Returns a socket object. If it doesn't exist, it's created.
  203. * It also registers the notification callback.
  204. *
  205. * @returns {MMSocket} a socket object
  206. */
  207. socket: function () {
  208. if (typeof this._socket === "undefined") {
  209. this._socket = new MMSocket(this.name);
  210. }
  211. this._socket.setNotificationCallback((notification, payload) => {
  212. this.socketNotificationReceived(notification, payload);
  213. });
  214. return this._socket;
  215. },
  216. /**
  217. * Retrieve the path to a module file.
  218. *
  219. * @param {string} file Filename
  220. * @returns {string} the file path
  221. */
  222. file: function (file) {
  223. return (this.data.path + "/" + file).replace("//", "/");
  224. },
  225. /**
  226. * Load all required stylesheets by requesting the MM object to load the files.
  227. *
  228. * @param {Function} callback Function called when done.
  229. */
  230. loadStyles: function (callback) {
  231. this.loadDependencies("getStyles", callback);
  232. },
  233. /**
  234. * Load all required scripts by requesting the MM object to load the files.
  235. *
  236. * @param {Function} callback Function called when done.
  237. */
  238. loadScripts: function (callback) {
  239. this.loadDependencies("getScripts", callback);
  240. },
  241. /**
  242. * Helper method to load all dependencies.
  243. *
  244. * @param {string} funcName Function name to call to get scripts or styles.
  245. * @param {Function} callback Function called when done.
  246. */
  247. loadDependencies: function (funcName, callback) {
  248. let dependencies = this[funcName]();
  249. const loadNextDependency = () => {
  250. if (dependencies.length > 0) {
  251. const nextDependency = dependencies[0];
  252. Loader.loadFile(nextDependency, this, () => {
  253. dependencies = dependencies.slice(1);
  254. loadNextDependency();
  255. });
  256. } else {
  257. callback();
  258. }
  259. };
  260. loadNextDependency();
  261. },
  262. /**
  263. * Load all translations.
  264. *
  265. * @param {Function} callback Function called when done.
  266. */
  267. loadTranslations(callback) {
  268. const translations = this.getTranslations() || {};
  269. const language = config.language.toLowerCase();
  270. const languages = Object.keys(translations);
  271. const fallbackLanguage = languages[0];
  272. if (languages.length === 0) {
  273. callback();
  274. return;
  275. }
  276. const translationFile = translations[language];
  277. const translationsFallbackFile = translations[fallbackLanguage];
  278. if (!translationFile) {
  279. Translator.load(this, translationsFallbackFile, true, callback);
  280. return;
  281. }
  282. Translator.load(this, translationFile, false, () => {
  283. if (translationFile !== translationsFallbackFile) {
  284. Translator.load(this, translationsFallbackFile, true, callback);
  285. } else {
  286. callback();
  287. }
  288. });
  289. },
  290. /**
  291. * Request the translation for a given key with optional variables and default value.
  292. *
  293. * @param {string} key The key of the string to translate
  294. * @param {string|object} [defaultValueOrVariables] The default value or variables for translating.
  295. * @param {string} [defaultValue] The default value with variables.
  296. * @returns {string} the translated key
  297. */
  298. translate: function (key, defaultValueOrVariables, defaultValue) {
  299. if (typeof defaultValueOrVariables === "object") {
  300. return Translator.translate(this, key, defaultValueOrVariables) || defaultValue || "";
  301. }
  302. return Translator.translate(this, key) || defaultValueOrVariables || "";
  303. },
  304. /**
  305. * Request an (animated) update of the module.
  306. *
  307. * @param {number} [speed] The speed of the animation.
  308. */
  309. updateDom: function (speed) {
  310. MM.updateDom(this, speed);
  311. },
  312. /**
  313. * Send a notification to all modules.
  314. *
  315. * @param {string} notification The identifier of the notification.
  316. * @param {*} payload The payload of the notification.
  317. */
  318. sendNotification: function (notification, payload) {
  319. MM.sendNotification(notification, payload, this);
  320. },
  321. /**
  322. * Send a socket notification to the node helper.
  323. *
  324. * @param {string} notification The identifier of the notification.
  325. * @param {*} payload The payload of the notification.
  326. */
  327. sendSocketNotification: function (notification, payload) {
  328. this.socket().sendNotification(notification, payload);
  329. },
  330. /**
  331. * Hide this module.
  332. *
  333. * @param {number} speed The speed of the hide animation.
  334. * @param {Function} callback Called when the animation is done.
  335. * @param {object} [options] Optional settings for the hide method.
  336. */
  337. hide: function (speed, callback, options) {
  338. if (typeof callback === "object") {
  339. options = callback;
  340. callback = function () {};
  341. }
  342. callback = callback || function () {};
  343. options = options || {};
  344. MM.hideModule(
  345. this,
  346. speed,
  347. () => {
  348. this.suspend();
  349. callback();
  350. },
  351. options
  352. );
  353. },
  354. /**
  355. * Show this module.
  356. *
  357. * @param {number} speed The speed of the show animation.
  358. * @param {Function} callback Called when the animation is done.
  359. * @param {object} [options] Optional settings for the show method.
  360. */
  361. show: function (speed, callback, options) {
  362. if (typeof callback === "object") {
  363. options = callback;
  364. callback = function () {};
  365. }
  366. callback = callback || function () {};
  367. options = options || {};
  368. MM.showModule(
  369. this,
  370. speed,
  371. () => {
  372. this.resume();
  373. callback();
  374. },
  375. options
  376. );
  377. }
  378. });
  379. /**
  380. * Merging MagicMirror (or other) default/config script by @bugsounet
  381. * Merge 2 objects or/with array
  382. *
  383. * Usage:
  384. * -------
  385. * this.config = configMerge({}, this.defaults, this.config)
  386. * -------
  387. * arg1: initial object
  388. * arg2: config model
  389. * arg3: config to merge
  390. * -------
  391. * why using it ?
  392. * Object.assign() function don't to all job
  393. * it don't merge all thing in deep
  394. * -> object in object and array is not merging
  395. * -------
  396. *
  397. * Todo: idea of Mich determinate what do you want to merge or not
  398. *
  399. * @param {object} result the initial object
  400. * @returns {object} the merged config
  401. */
  402. function configMerge(result) {
  403. const stack = Array.prototype.slice.call(arguments, 1);
  404. let item, key;
  405. while (stack.length) {
  406. item = stack.shift();
  407. for (key in item) {
  408. if (item.hasOwnProperty(key)) {
  409. if (typeof result[key] === "object" && result[key] && Object.prototype.toString.call(result[key]) !== "[object Array]") {
  410. if (typeof item[key] === "object" && item[key] !== null) {
  411. result[key] = configMerge({}, result[key], item[key]);
  412. } else {
  413. result[key] = item[key];
  414. }
  415. } else {
  416. result[key] = item[key];
  417. }
  418. }
  419. }
  420. }
  421. return result;
  422. }
  423. Module.definitions = {};
  424. Module.create = function (name) {
  425. // Make sure module definition is available.
  426. if (!Module.definitions[name]) {
  427. return;
  428. }
  429. const moduleDefinition = Module.definitions[name];
  430. const clonedDefinition = cloneObject(moduleDefinition);
  431. // Note that we clone the definition. Otherwise the objects are shared, which gives problems.
  432. const ModuleClass = Module.extend(clonedDefinition);
  433. return new ModuleClass();
  434. };
  435. Module.register = function (name, moduleDefinition) {
  436. if (moduleDefinition.requiresVersion) {
  437. Log.log("Check MagicMirror version for module '" + name + "' - Minimum version: " + moduleDefinition.requiresVersion + " - Current version: " + window.mmVersion);
  438. if (cmpVersions(window.mmVersion, moduleDefinition.requiresVersion) >= 0) {
  439. Log.log("Version is ok!");
  440. } else {
  441. Log.warn("Version is incorrect. Skip module: '" + name + "'");
  442. return;
  443. }
  444. }
  445. Log.log("Module registered: " + name);
  446. Module.definitions[name] = moduleDefinition;
  447. };
  448. window.Module = Module;
  449. /**
  450. * Compare two semantic version numbers and return the difference.
  451. *
  452. * @param {string} a Version number a.
  453. * @param {string} b Version number b.
  454. * @returns {number} A positive number if a is larger than b, a negative
  455. * number if a is smaller and 0 if they are the same
  456. */
  457. function cmpVersions(a, b) {
  458. const regExStrip0 = /(\.0+)+$/;
  459. const segmentsA = a.replace(regExStrip0, "").split(".");
  460. const segmentsB = b.replace(regExStrip0, "").split(".");
  461. const l = Math.min(segmentsA.length, segmentsB.length);
  462. for (let i = 0; i < l; i++) {
  463. let diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
  464. if (diff) {
  465. return diff;
  466. }
  467. }
  468. return segmentsA.length - segmentsB.length;
  469. }