forked from clegallic/MMM-GoogleDriveSlideShow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
453 lines (403 loc) · 13.5 KB
/
Copy pathnode_helper.js
File metadata and controls
453 lines (403 loc) · 13.5 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
var NodeHelper = require("node_helper");
const { google } = require("googleapis");
const promisify = require("util").promisify;
const fs = require("fs");
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const unlink = promisify(fs.unlink);
const https = require("https");
const CACHE_FILE_PATH = ".cache";
const G_CREDENTIALS_FILE_PATH = "./secrets/credentials.json";
const G_TOKEN_FILE_PATH = "./secrets/token.json";
/** @typedef {import("google-auth-library").OAuth2ClientOptions} OAuth2ClientOptions */
/** @typedef {import("google-auth-library").OAuth2Client} OAuth2Client */
/** @typedef {import("google-auth-library").Credentials} Credentials */
/**
* @typedef {Object} CredentialsInstalled
* @property {OAuth2ClientOptions['clientId']} client_id - The client ID.
* @property {OAuth2ClientOptions['projectId']} project_id - The project ID.
* @property {string|null|undefined} auth_uri - The authorization URI.
* @property {string|null|undefined} token_uri - The token URI.
* @property {string|null|undefined} auth_provider_x509_cert_url - The auth provider x509 cert URL.
* @property {OAuth2ClientOptions['clientSecret']} client_secret - The client secret.
* @property {Array<string>|null|undefined} redirect_uris - The redirect URIs.
*/
/**
* @typedef {Object} CredentialsFileData
* @property {CredentialsInstalled} installed - The installed credentials.
*/
module.exports = NodeHelper.create({
config: {
rootFolderId: null,
maxFolders: 30,
maxResults: 10,
refreshDriveDelayInSeconds: 24 * 3600,
refreshSlideShowIntervalInSeconds: 10,
debug: false,
},
alreadySentPhotoIds: [], // Array of images already sent to the MM
cache: {
created: null,
photos: [],
},
gDriveService: null, // Google Drive API Service
broadcastTimer: null, // Timer for next image broadcast
lastBroadcastDate: null,
refreshCacheInProgress: false, // Is the cache currently refreshing ?
suspended: false, // Is the module suspended
start: async function () {
await this.setupGoogleApiService();
this.expressApp.use("/" + this.name + "/next", async (req, res, next) => {
await this.broadcastRandomPhoto();
res.send("Next photo requested");
});
this.expressApp.use("/" + this.name + "/stop", async (req, res, next) => {
await this.stopSlideShow();
res.send("Slideshow stopped");
});
this.expressApp.use("/" + this.name + "/play", async (req, res, next) => {
this.startSlideShow();
res.send("Slideshow started");
});
this.expressApp.use(
"/" + this.name + "/cache/reset",
async (req, res, next) => {
await this.resetCache();
await this.getPhotos();
res.send({
cache: this.cache,
});
},
);
this.expressApp.use(
"/" + this.name + "/file/:photoId",
async (req, res, next) => {
let photoId = req.params.photoId;
if ("random" === photoId) {
photo = await this.getRandomPhoto();
if (!photo) {
next();
return;
}
photoId = photo.id;
}
this.debug("Displaying photo with ID " + photoId);
var response = await this.gDriveService.files.get({
fileId: photoId,
fields: "thumbnailLink",
});
var thumbnailLink = response.data.thumbnailLink.replace(
"=s220",
"=s" + this.config.maxWidth,
);
var proxy = https.request(thumbnailLink, function (proxyRes) {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, {
end: true,
});
});
req.pipe(proxy, {
end: true,
});
},
);
},
socketNotificationReceived: async function (notification, payload) {
this.debug("New notification received : " + notification);
switch (notification) {
case "INIT":
this.config = payload;
this.debug("DEBUG IS ACTIVE");
this.debug(JSON.stringify(this.config, null, 2));
await this.startSlideShow(true);
break;
case "REQUEST_NEW_IMAGE":
if (!this.suspended) {
await this.broadcastRandomPhoto();
}
break;
case "STOP_SLIDESHOW":
this.stopSlideShow();
break;
case "START_SLIDESHOW":
await this.startSlideShow();
break;
case "SUSPEND":
this.stopSlideShow();
this.suspended = true;
break;
case "RESUME":
this.suspended = false;
await this.startSlideShow();
break;
}
},
startSlideShow: async function (firstLaunch) {
this.debug("Starting slideshow. First time ? " + (firstLaunch === true));
if (firstLaunch) {
this.broadcastRandomPhoto();
}
if (this.config.playMode === "AUTO") {
this.broadcastTimer = setInterval(
async () => await this.broadcastRandomPhoto(),
this.config.refreshSlideShowIntervalInSeconds * 1000,
);
}
},
stopSlideShow: function () {
this.debug("Slidshow stopped");
clearInterval(this.broadcastTimer);
},
broadcastNewPhoto: async function (photo) {
this.sendSocketNotification("NEW_IMAGE", photo);
},
broadcastRandomPhoto: async function () {
if (
this.lastBroadcastDate == null ||
new Date().getTime() - this.lastBroadcastDate.getTime() > 5000
) {
// Prevent two notifications to request image change to quickly (5 s mini between each)
let photo = await this.getRandomPhoto();
if (!photo) {
setTimeout(() => this.broadcastRandomPhoto(), 1000);
return;
}
await this.broadcastNewPhoto(photo);
this.lastBroadcastDate = new Date();
} else {
this.debug("Throttle detected, skip new image request");
}
},
setupGoogleApiService: async function () {
let { credentials, token } = await this.readAuthenticationFiles();
const {
installed: {
client_id: clientId,
client_secret: clientSecret,
redirect_uris: redirectUris,
},
} = credentials,
redirectUri = (redirectUris ?? [])[0];
const oauth2Client = new google.auth.OAuth2({
clientId,
clientSecret,
redirectUri,
});
oauth2Client.setCredentials(token);
this.gDriveService = google.drive({ version: "v3", auth: oauth2Client });
},
log: function (message) {
console.log(`${this.name} : ${message}`);
},
debug: function (message) {
if (this.config.debug) {
this.log(`[DEBUG] ${message}`);
}
},
readAuthenticationFiles: function () {
return new Promise((resolve, reject) => {
Promise.all([
readFile(`${this.path}/${G_CREDENTIALS_FILE_PATH}`),
readFile(`${this.path}/${G_TOKEN_FILE_PATH}`),
])
.then((values) => {
var credentials = JSON.parse(values[0]);
var token = JSON.parse(values[1]);
resolve({ credentials, token });
})
.catch((reason) => {
reject(reason);
});
});
},
cacheFileExists: function () {
return fs.existsSync(`${this.path}/${CACHE_FILE_PATH}`);
},
loadCache: async function () {
let content = await readFile(`${this.path}/${CACHE_FILE_PATH}`);
this.cache = JSON.parse(content);
},
createCache: async function () {
if (this.refreshCacheInProgress) {
this.debug("Cache already being build, skip this request");
return;
}
this.refreshCacheInProgress = true;
let photos = await this.loadPhotos();
this.cache = {
created: new Date().getTime(),
photos: photos,
};
await writeFile(
`${this.path}/${CACHE_FILE_PATH}`,
JSON.stringify(this.cache),
);
this.refreshCacheInProgress = false;
},
resetCache: async function () {
this.cache.created = -1;
await unlink(`${this.path}/${CACHE_FILE_PATH}`);
},
buildPhotoUrl: function (photo) {
return photo.thumbnailLink.replace(
"=s200",
"=s" + this.config.minWidth.replace("px", ""),
);
//return photo.thumbnailLink;
},
getRandomPhoto: async function () {
let photos = await this.getPhotos();
if (!Array.isArray(photos) || photos.length === 0) return undefined;
let randomIndex = Math.floor(Math.random() * photos.length);
let randomPhoto = photos[randomIndex];
if (!randomPhoto || !randomPhoto["id"]) return undefined;
this.cache.photos.splice(randomIndex, 1);
// If all photos are sent, reload cache from file
if (this.cache.photos.length === 0) {
await this.loadCache();
this.alreadySentPhotoIds = [];
}
this.alreadySentPhotoIds.push(randomPhoto.id);
return randomPhoto;
},
getPhotos: async function () {
// Get cache if not already loaded and cache file exists (after a restart for example)
if (!this.cache.created && this.cacheFileExists()) {
this.log("No memory cache, loading it from disk");
await this.loadCache();
}
// Check if need reload
let needReload =
!this.cache ||
!this.cache.created ||
(new Date().getTime() - (this.cache.created ?? 0)) / 1000 >
this.config.refreshDriveDelayInSeconds;
// (re)create the cache if missing or expired
if (needReload) {
this.log("No cache file, or expired, (re)creating it...");
await this.createCache();
this.cache.photos = await this.cache.photos.filter(
(photo) => !this.alreadySentPhotoIds.includes(photo.id),
);
}
return this.cache.photos;
},
walkFolders: async function (folderId, limits, alreadyWalked) {
var folders = [];
folders.push(folderId);
// Store already analyzed folders
if (!alreadyWalked) {
alreadyWalked = [];
}
if (alreadyWalked.length > limits) {
return folders;
}
// Add current folder
alreadyWalked.push(folderId);
// Query API
const response = await this.gDriveService.files.list({
q: `'${folderId}' in parents and mimeType = 'application/vnd.google-apps.folder'`,
pageSize: 100,
});
if (response.data.files.length) {
let subFolders =
alreadyWalked.length + response.data.files.length < limits
? response.data.files
: response.data.files.slice(0, limits - alreadyWalked.length);
for (var entry of subFolders) {
if (alreadyWalked.indexOf(entry.id) === -1) {
var rec = await this.walkFolders(entry.id, limits, alreadyWalked);
folders = folders.concat(rec);
}
}
}
if (alreadyWalked.length % 10 === 0) {
this.debug(`${alreadyWalked.length} folders found`);
}
return folders;
},
buildMimeTypeQuery: function () {
return "mimeType contains 'image/'";
},
searchPhotosByFolders: async function (folderIds) {
let results = [];
const maxFoldersPerQuery = 10;
let iterations = Math.ceil(folderIds.length / maxFoldersPerQuery);
for (let i = 0; i < iterations; i++) {
this.debug(`Query for photos : iteration ${i + 1}`);
// Build query
let range = folderIds.slice(
i * maxFoldersPerQuery,
(i + 1) * maxFoldersPerQuery,
);
let parentsQuery = range
.map((folderId) => `'${folderId}' in parents`)
.join(" or ");
let query = `(${parentsQuery}) and ${this.buildMimeTypeQuery()}`;
// Run query
let max = this.config.maxResults - results.length;
let r = await this.searchPhotosByQuery(query, max);
results = results.concat(r);
if (results.length === this.config.maxResults) {
break;
}
}
return results;
},
searchPhotosByQuery: async function (query, max) {
let results = [];
let pageToken;
do {
const response = await this.gDriveService.files.list({
q: query,
fields:
"nextPageToken, files(id,name,imageMediaMetadata(width, height, rotation))",
pageToken: pageToken,
});
pageToken = response.data.nextPageToken;
let limit = Math.min(max - results.length, response.data.files.length);
results = results.concat(response.data.files.splice(0, limit));
if (limit < response.data.files.length) {
pageToken = null;
}
this.debug(`${results.length} photos retrieved`);
} while (pageToken);
return results;
},
loadPhotos: async function () {
let start = new Date();
this.debug("Loading photos from Google Drive");
try {
let photos;
if (!this.config.rootFolderId) {
// Root => only query by mimetype
this.debug("Root folder => search files over all gDrive");
photos = await this.searchPhotosByQuery(
this.buildMimeTypeQuery(),
this.config.maxResults,
);
} else {
// Root folder provided : must discover sub folders before
this.debug(`Search subfolders of folder ${this.config.rootFolderId}`);
let folderIds = await this.walkFolders(
this.config.rootFolderId,
this.config.maxFolders,
).catch(console.error);
this.debug(
`${folderIds.length} of maximum ${this.config.maxFolders} folders scanned`,
);
photos = await this.searchPhotosByFolders(folderIds);
}
this.log(
`${photos.length} photos metadata retrieved in ${(new Date().getTime() - start.getTime()) / 1000} seconds`,
);
return photos;
} catch (e) {
const msg =
e?.response?.data?.error_description || e?.message || String(e);
this.log(`[MMM-GoogleDriveSlideShow] Google Drive load failed: ${msg}`);
// Importante: no revientes el proceso
return [];
}
},
});