forked from skuethe/MMM-RandomPhoto
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
191 lines (164 loc) · 6.79 KB
/
node_helper.js
File metadata and controls
191 lines (164 loc) · 6.79 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
require("url"); // for nextcloud
const https = require("https"); // for nextcloud
const fs = require("fs"); // for localdirectory
const {XMLParser} = require('fast-xml-parser'); //for nextcloud response parsing
const NodeHelper = require("node_helper");
module.exports = NodeHelper.create({
start: function() {
var self = this;
this.nextcloud = false;
this.localdirectory = false;
this.imageList = [];
this.expressApp.get("/" + this.name + "/images/:randomImageName(*)", async function(request, response) {
var imageBase64Encoded = await self.fetchEncodedImage(request.params.randomImageName);
response.send(imageBase64Encoded);
});
},
socketNotificationReceived: function(notification, payload) {
//console.log("["+ this.name + "] received a '" + notification + "' with payload: " + payload);
if (notification === "SET_CONFIG") {
this.config = payload;
if (this.config.imageRepository === "nextcloud") {
this.nextcloud = true;
} else if (this.config.imageRepository === "localdirectory") {
this.localdirectory = true;
}
}
if (notification === "FETCH_IMAGE_LIST") {
if (this.config.imageRepository === "nextcloud") {
this.fetchNextcloudImageList();
}
if (this.config.imageRepository === "localdirectory") {
this.fetchLocalImageList();
}
}
},
fetchLocalImageDirectory: function(path) {
var self = this;
// Validate path
if (!fs.existsSync(path)) {
console.log("["+ self.name + "] ERROR - specified path does not exist: " + path);
return false;
}
var fileList = fs.readdirSync(path, { withFileTypes: true });
if (fileList.length > 0) {
for (var f = 0; f < fileList.length; f++) {
if (fileList[f].isFile()) {
//TODO: add mime type check here
self.imageList.push(path + "/" + fileList[f].name);
}
if ((self.config.repositoryConfig.recursive === true) && fileList[f].isDirectory()) {
self.fetchLocalImageDirectory(path + "/" + fileList[f].name);
}
}
return;
}
},
fetchLocalImageList: function() {
var self = this;
var path = self.config.repositoryConfig.path;
self.imageList = [];
self.fetchLocalImageDirectory(path);
self.sendSocketNotification("IMAGE_LIST", self.imageList);
return false;
},
fetchNextcloudImageList: function() {
var self = this;
var imageList = [];
var path = self.config.repositoryConfig.path;
const urlParts = new URL(path);
const requestOptions = {
method: "PROPFIND",
headers: {
"Authorization": "Basic " + new Buffer.from(this.config.repositoryConfig.username + ":" + this.config.repositoryConfig.password).toString("base64")
}
};
https.get(path, requestOptions, function(response) {
var body = "";
response.on("data", function(data) {
body += data;
});
response.on("end", function() {
imageList = self.extractImagesFromResponse(body, urlParts);
if (imageList && imageList.length > 0) {
self.sendSocketNotification("IMAGE_LIST", imageList);
return;
} else {
console.log("[" + this.name + "] WARNING: did not get any images from nextcloud url");
return false;
}
});
})
.on("error", function(err) {
console.log("[" + this.name + "] ERROR: " + err);
return false;
});
},
extractImagesFromResponse: function(body, urlParts) {
var imageList = [];
const options = {
ignoreDeclaration: true,
processEntities: false,
removeNSPrefix: true,
};
const parser = new XMLParser(options);
let jObj = parser.parse(body).multistatus.response;
for (const item in jObj) {
if (Object.hasOwnProperty.call(jObj, item)) {
const element = jObj[item];
if (element.propstat[0]) {
if (element.propstat[0].prop) {
if (element.propstat[0].prop.getcontenttype && element.propstat[0].prop.getcontenttype.startsWith('image/')) {
imageList.push(element.href.replace(urlParts.pathname, ''));
}
}
}
}
}
return imageList;
},
fetchEncodedImage: async function(passedImageName) {
var self = this;
return new Promise(function(resolve, reject) {
var fullImagePath = passedImageName;
// Local files
if (self.localdirectory) {
var fileEncoded = "data:image/jpeg;base64," + fs.readFileSync(fullImagePath, { encoding: 'base64' });
resolve(fileEncoded);
}
// Nextcloud
else if (self.nextcloud) {
const requestOptions = {
method: "GET",
headers: {
"Authorization": "Basic " + new Buffer.from(self.config.repositoryConfig.username + ":" + self.config.repositoryConfig.password).toString("base64")
}
};
https.get(self.config.repositoryConfig.path + fullImagePath, requestOptions, (response) => {
response.setEncoding('base64');
var fileEncoded = "data:" + response.headers["content-type"] + ";base64,";
response.on("data", (data) => { fileEncoded += data; });
response.on("end", () => {
resolve(fileEncoded);
});
})
.on("error", function(err) {
console.log("[" + this.name + "] ERROR: " + err);
return false;
});
}
})
/**
var getMimeObject = spawn("file", ["-b", "--mime-type", "-0", "-0", file]);
getMimeObject.stdout.on('data', (data) => {
var mimeType = data.toString().replace("\0", "");
//console.log("mime type is: '" + mimeType + "'");
var fileEncoded = "data:" + mimeType + ";base64,";
fileEncoded += fs.readFileSync(file, { encoding: 'base64' });
//console.log("base64:");
console.log("<img src='" + fileEncoded + "' />");
//return fileEncoded;
});
**/
},
});