forked from kolbyjack/MMM-Wallpaper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_helper.js
343 lines (285 loc) · 9.42 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
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
"use strict";
const NodeHelper = require("node_helper");
const request = require("request");
const fs = require("fs");
function shuffle(a) {
var source = a.slice(0);
var result = [];
var i, j;
for (i = a.length; i > 0; --i) {
j = Math.floor(Math.random() * i);
result.push(source[j]);
source[j] = source[i];
}
return result;
}
function pick(a) {
if (Array.isArray(a)) {
return a[Math.floor(Math.random() * a.length)];
} else {
return a;
}
}
function fmt(f) {
var parts = f.split("{}");
var result = parts[0];
var i;
for (i = 1; i < parts.length; ++i) {
result += arguments[i] + parts[i];
}
return result;
}
module.exports = NodeHelper.create({
start: function() {
var self = this;
console.log(fmt("Starting node helper for: {}", self.name));
self.cache = {};
self.firetv = JSON.parse(fs.readFileSync(fmt("{}/firetv.json", __dirname)));
},
socketNotificationReceived: function(notification, payload) {
var self = this;
if (notification === "FETCH_WALLPAPERS") {
self.fetchWallpapers(payload);
}
},
fetchWallpapers: function(config) {
var self = this;
var cache_key = self.getCacheKey(config);
var url;
var method = "GET";
var body = undefined;
if (cache_key in self.cache &&
config.maximumEntries <= self.cache[cache_key].images.length &&
Date.now() < self.cache[cache_key].expires)
{
self.sendWallpaperUpdate(config);
return;
}
config.source = pick(config.source);
var source = config.source.toLowerCase();
if (source === "firetv") {
self.sendSocketNotification("WALLPAPERS", {
"source": config.source,
"orientation": config.orientation,
"images": shuffle(self.firetv.images).slice(0, config.maximumEntries),
});
return;
} else if (source.startsWith("/r/")) {
self.request(config, {
url: fmt("https://www.reddit.com{}/hot.json", config.source),
headers: {
"user-agent": "MagicMirror:MMM-Wallpaper:v1.0 (by /u/kolbyhack)"
},
});
} else if (source === "pexels") {
self.request(config, {
url: "https://api.pexels.com/v1/search?query=" + config.pexels_search,
headers: {
Authorization: config.pexels_key
},
});
} else if (source.startsWith("icloud:")) {
self.iCloudState = "webstream";
self.request(config, {
method: "POST",
url: fmt("https://p04-sharedstreams.icloud.com/{}/sharedstreams/webstream", config.source.substring(7)),
body: '{"streamCtag":null}',
});
} else if (source.startsWith("flickr-group:")) {
self.request(config, {
url: fmt("https://api.flickr.com/services/feeds/groups_pool.gne?format=json&id={}", config.source.substring(13)),
});
} else if (source.startsWith("flickr-user:")) {
self.request(config, {
url: fmt("https://api.flickr.com/services/feeds/photos_public.gne?format=json&id={}", config.source.substring(12)),
});
} else if (source.startsWith("flickr-user-faves:")) {
self.request(config, {
url: fmt("https://api.flickr.com/services/feeds/photos_faves.gne?format=json&id={}", config.source.substring(18)),
});
} else {
self.request(config, {
url: fmt("https://www.bing.com/HPImageArchive.aspx?format=js&mkt=en-US&idx=0&n={}", config.maximumEntries),
});
}
},
request: function(config, params) {
var self = this;
if (!("headers" in params)) {
params.headers = {};
}
if (!("cache-control" in params.headers)) {
params.headers["cache-control"] = "no-cache";
}
request(params,
function(error, response, body) {
if (error) {
self.sendSocketNotification("FETCH_ERROR", { error: error });
return console.error(fmt(" ERROR - MMM-Wallpaper: {}", error));
}
if (response.statusCode < 400 && body.length > 0) {
self.processResponse(response, body, config);
}
}
);
},
sendWallpaperUpdate: function(config) {
var self = this;
var cache_key = self.getCacheKey(config);
self.sendSocketNotification("WALLPAPERS", {
"source": config.source,
"orientation": config.orientation,
"images": self.cache[cache_key].images,
});
},
processResponse: function(response, body, config) {
var self = this;
var cache_key = self.getCacheKey(config);
var images;
var source = config.source.toLowerCase();
if (source.startsWith("/r/")) {
images = self.processRedditData(config, JSON.parse(body));
} else if (source.startsWith("icloud:")) {
images = self.processiCloudData(response, JSON.parse(body), config);
} else if (source.startsWith("flickr-")) {
images = self.processFlickrData(config, body);
} else if (source === "pexels") {
images = self.processPexelsData(config, JSON.parse(body));
} else {
images = self.processBingData(config, JSON.parse(body));
}
if (images.length === 0) {
return;
}
self.cache[cache_key] = {
"expires": Date.now() + config.updateInterval * 0.9,
"images": images,
};
self.sendWallpaperUpdate(config);
},
processPexelsData: function (config, data) {
var self = this;
var width = (config.orientation === "vertical") ? 1080 : 1920;
var height = (config.orientation === "vertical") ? 1920 : 1080;
var suffix = "_" + width + "x" + height + ".jpg";
var orientation
if (config.orientation === "vertical") {
orientation = "portrait"
} else {
orientation = "landscape"
}
var images = [];
for (var i in data.photos) {
var image = data.photos[i];
images.push({
url: image.src[orientation],
caption: "Photographer:" + image.photographer,
});
}
return images;
},
processBingData: function(config, data) {
var self = this;
var width = (config.orientation === "vertical") ? 1080 : 1920;
var height = (config.orientation === "vertical") ? 1920 : 1080;
var suffix = "_" + width + "x" + height + ".jpg";
var images = [];
for (var i in data.images) {
var image = data.images[i];
images.push({
url: fmt("https://www.bing.com{}{}", image.urlbase, suffix),
caption: image.copyright,
});
}
return images;
},
processRedditData: function(config, data) {
var self = this;
var images = [];
for (var i in data.data.children) {
var post = data.data.children[i];
if (post.kind === "t3" && !post.data.pinned && !post.data.stickied && post.data.post_hint === "image") {
var variants = post.data.preview.images[0].resolutions.slice(0);
variants.push(post.data.preview.images[0].source);
variants.map((v) => { v.url = v.url.split("&").join("&"); return v; });
variants.sort((a, b) => { return a.width * a.height - b.width * b.height; });
images.push({
url: post.data.url.replace("&", "&"),
caption: post.data.title,
variants: variants,
});
if (images.length === config.maximumEntries) {
break;
}
}
}
return images;
},
processiCloudData: function(response, body, config) {
var self = this;
var album = config.source.substring(7);
var images = [];
if (self.iCloudState === "webstream") {
if (response.statusCode === 330) {
self.iCloudHost = body["X-Apple-MMe-Host"];
self.request(config, {
method: "POST",
url: fmt("https://{}/{}/sharedstreams/webstream", self.iCloudHost, album),
body: '{"streamCtag":null}'
});
} else if (response.statusCode === 200) {
var photos = shuffle(body.photos).filter((p) => p != null).slice(0, config.maximumEntries);
var photoGuids = photos.map((p) => { return p.photoGuid; });
self.iCloudState = "webasseturls";
self.iCloudMetadata = photos.reduce((o, p) => {
if (p.derivatives.mediaAssetType === "video") {
return o;
}
for (var d in p.derivatives) {
var meta = p.derivatives[d];
o[meta.checksum] = {
caption: p.caption
};
}
return o
}, {});
self.request(config, {
method: "POST",
url: fmt("https://{}/{}/sharedstreams/webasseturls", self.iCloudHost, album),
body: JSON.stringify({"photoGuids": photoGuids}),
});
}
} else if (self.iCloudState === "webasseturls") {
for (var guid in body.items) {
var p = body.items[guid];
var loc = body.locations[p.url_location];
var host = loc.hosts[Math.floor(Math.random() * loc.hosts.length)];
var meta = self.iCloudMetadata[guid];
images.push({
url: fmt("{}://{}{}", loc.scheme, host, p.url_path),
caption: meta.caption,
});
}
}
return images;
},
processFlickrData: function(config, body) {
var self = this;
var data = JSON.parse(body.replace(/^[^{]*/, "").replace(/[^}]*$/, ""));
var images = [];
for (var i in data.items) {
var post = data.items[i];
images.push({
url: post.media.m.replace(/_m\./, "_h."),
caption: post.title,
});
if (images.length === config.maximumEntries) {
break;
}
}
return images;
},
getCacheKey: function(config) {
return config.source + "::" + config.orientation;
},
});