-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_helper.js
89 lines (76 loc) · 3.15 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* Magic Mirror
* Node Helper: MMM-ImageFileWacther
*
* By Bas Knol
* MIT Licensed.
*
* Chokidar - https://github.com/paulmillr/chokidar
* MIT Licensed.
* Copyright (c) 2016 Paul Miller (http://paulmillr.com) & Elan Shanker
*
*/
var NodeHelper = require("node_helper");
var chokidar = require('chokidar');
module.exports = NodeHelper.create({
start: function () {
this.watching = false;
},
// Override socketNotificationReceived method.
/* socketNotificationReceived(notification, payload)
* This method is called when a socket notification arrives.
*
* argument notification string - The identifier of the noitication.
* argument payload mixed - The payload of the notification.
*/
socketNotificationReceived: function(notification, payload) {
if (notification == "START") {
this.watchFiles(payload);
}
},
//Watch if files are added to given paths
watchFiles: function (config) {
var self = this;
//Check if we are already watching, avoid double events because of mirror refresh
if (this.watching === false) {
//Check if image paths are specified
if (config.imagePaths.length > 0) {
console.log("Start watching: " + config.imagePaths);
// Initialize watcher passing array of paths
var watcher = chokidar.watch(config.imagePaths, {
ignored: /(^|[\/\\])\../, //ignore .dotfiles
ignoreInitial: true,
persistent: true
});
//Watch if files are added
watcher
.on('add', (path, stats) => {
console.log(`File ${path} has been added`);
//if (stats) console.log(`File ${path} changed size to ${stats.size}`);
//Check if the file extension is valid
if (self.checkValidImageFileExtension(path, config.validImageFileExtensions)) {
//Wait a bit to avoid message: Error: EBUSY: resource busy or locked, open... o_O
setTimeout(function () {
self.sendSocketNotification("FILE_ADDED", path);
}, 1000);
}
})
.on('error', error => console.log(`MMM-ImageFileWacther error: ${error}`)); //Log errow
//Watching is set
this.watching = true;
}
else {
console.log("MMM-ImageFileWatcher: no image path(s) configured, no watcher active, no images will be shown. Please fill in an image path in the config of this module");
}
}
},
//Check if we can handle this type of file based on extension, is it an image?
checkValidImageFileExtension: function (filename, extensions) {
var extList = extensions.split(',');
for (var extIndex = 0; extIndex < extList.length; extIndex++) {
if (filename.toLowerCase().endsWith(extList[extIndex])) {
return true;
}
}
return false;
},
});