forked from jclarke0000/MMM-MyCommute
-
Notifications
You must be signed in to change notification settings - Fork 14
/
MMM-MyCommute.js
591 lines (511 loc) · 16.8 KB
/
MMM-MyCommute.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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/*********************************
Magic Mirror Module:
MMM-MyCommute
By Jeff Clarke
Fork of mrx-work-traffic
By Dominic Marx
https://github.com/domsen123/mrx-work-traffic
MIT Licensed
*********************************/
/* global config, Module, Log, moment */
Module.register("MMM-MyCommute", {
defaults: {
apiKey: "",
origin: "65 Front St W, Toronto, ON M5J 1E6",
startTime: "00:00",
endTime: "23:59",
lang: config.language,
hideDays: [],
showSummary: true,
showUpdated: true,
showUpdatedPosition: "footer", // Valid options are header or footer
colorCodeTravelTime: true,
moderateTimeThreshold: 1.1,
poorTimeThreshold: 1.3,
nextTransitVehicleDepartureFormat: "[next at] h:mm a",
travelTimeFormat: "m [min]",
travelTimeFormatTrim: "left",
pollFrequency: 10 * 60 * 1000, //every ten minutes, in milliseconds
maxCalendarEvents: 0,
maxCalendarTime: 24 * 60 * 60 * 1000,
calendarOptions: [{mode: "driving", maxLabelLength: 25}],
showArrivalTime: true,
showError: true,
destinations: [
{
destination: "40 Bay St, Toronto, ON M5J 2X2",
label: "Air Canada Centre",
mode: "walking",
time: null
},
{
destination: "317 Dundas St W, Toronto, ON M5T 1G4",
label: "Art Gallery of Ontario",
mode: "transit",
time: null
},
{
destination: "55 Mill St, Toronto, ON M5A 3C4",
label: "Distillery",
mode: "bicycling",
time: null
},
{
destination: "6301 Silver Dart Dr, Mississauga, ON L5P 1B2",
label: "Pearson Airport",
time: null
}
]
},
getTranslations: function() {
return {
en: "translations/en.json",
hu: "translations/hu.json",
nl: "translations/nl.json",
de: "translations/de.json"
};
},
// Define required scripts.
getScripts: function() {
return ["moment.js", this.file("node_modules/moment-duration-format/lib/moment-duration-format.js")];
},
// Define required styles.
getStyles: function () {
return ["MMM-MyCommute.css", "font-awesome.css"];
},
travelModes: [
"driving",
"walking",
"bicycling",
"transit"
],
transitModes: [
"bus",
"subway",
"train",
"tram",
"rail"
],
avoidOptions: [
"tolls",
"highways",
"ferries",
"indoor"
],
// Icons to use for each transportation mode
symbols: {
"driving": "car",
"walking": "walk",
"bicycling": "bike",
"transit": "streetcar",
"tram": "streetcar",
"bus": "bus",
"subway": "subway",
"train": "train",
"rail": "train",
"metro_rail": "subway",
"monorail": "train",
"heavy_rail": "train",
"commuter_train": "train",
"high_speed_train": "train",
"intercity_bus": "bus",
"trolleybus": "streetcar",
"share_taxi": "taxi",
"ferry": "boat",
"cable_car": "gondola",
"gondola_lift": "gondola",
"funicular": "gondola",
"other": "streetcar"
},
start: function() {
Log.info("Starting module: " + this.name);
this.predictions = [];
this.loading = true;
this.inWindow = true;
this.isHidden = false;
//start data poll
this.getData();
this.rescheduleInterval();
},
rescheduleInterval: function() {
const self = this;
if(this.interval !== null) {
// Clear current interval, just in case
clearInterval(this.interval);
}
this.interval = setInterval(function() {
self.getData();
}, this.config.pollFrequency);
},
suspended: false,
suspend: function() {
Log.log(this.name + " suspended");
if(!this.suspended) {
this.suspended = true;
clearInterval(this.interval);
}
},
resume: function() {
Log.log(this.name + " resumed");
if(this.suspended) {
this.suspended = false;
if(new Date() - this.lastUpdate > this.config.pollFrequency) {
// Last refresh, before suspend, is too old. Update now
this.getData();
}
this.rescheduleInterval();
}
},
/*
function isInWindow()
@param start
STRING display start time in 24 hour format e.g.: 06:00
@param end
STRING display end time in 24 hour format e.g.: 10:00
@param hideDays
ARRAY of numbers representing days of the week during which
this tested item shall not be displayed. Sun = 0, Sat = 6
e.g.: [3,4] to hide the module on Wed & Thurs
returns TRUE if current time is within start and end AND
today is not in the list of days to hide.
*/
isInWindow: function(start, end, hideDays) {
const now = moment();
const startTimeSplit = start.split(":");
const endTimeSplit = end.split(":");
const startTime = moment().hour(startTimeSplit[0]).minute(startTimeSplit[1]);
const endTime = moment().hour(endTimeSplit[0]).minute(endTimeSplit[1]);
if (now.isBefore(startTime) || now.isAfter(endTime)) {
return false;
} else if ( hideDays.indexOf( now.day() ) !== -1) {
return false;
}
return true;
},
appointmentDestinations: [],
trimCalendarLabel: function(label, maxLength) {
if (label.length > maxLength) {
label = label.substr(0, maxLength - 1) + "…";
}
return label;
},
setAppointmentDestinations: function(payload) {
this.appointmentDestinations = [];
if ( this.config.calendarOptions.length === 0) {
// No routing configs for calendar events
// Skip looking those up then
return;
}
for (let i=0; i<payload.length && this.appointmentDestinations.length<this.config.maxCalendarEvents; ++i) {
const calendarEvent = payload[i];
if ("location" in calendarEvent &&
calendarEvent.location !== undefined &&
calendarEvent.location !== false &&
calendarEvent.startDate < (Date.now() + this.config.maxCalendarTime)
) {
this.appointmentDestinations.push.apply(this.appointmentDestinations,
this.config.calendarOptions.map( calOpt => Object.assign({}, calOpt, {
label: this.trimCalendarLabel(calendarEvent.title, calOpt.maxLabelLength),
destination: calendarEvent.location,
arrival_time: calendarEvent.startDate / 1000,
color: calendarEvent.color
}))
);
}
}
// Make sure appointmentDestinations is not too long
// Which could happend because of inner forEach on calendarOptions
this.appointmentDestinations = this.appointmentDestinations.slice(0, this.config.maxCalendarEvents);
},
getDestinations: function() {
return this.config.destinations.concat(this.appointmentDestinations);
},
lastUpdate: 0,
getData: function() {
Log.log(this.name + " refreshing routes");
//only poll if in window
if (this.isInWindow(this.config.startTime, this.config.endTime, this.config.hideDays)) {
//build URLs
let destinationGetInfo = [];
const destinations = this.getDestinations();
for(let i = 0; i < destinations.length; i++) {
const d = destinations[i];
const destStartTime = d.startTime || "00:00";
const destEndTime = d.endTime || "23:59";
const destHideDays = d.hideDays || [];
if (this.isInWindow(destStartTime, destEndTime, destHideDays)) {
const url = "https://maps.googleapis.com/maps/api/directions/json" + this.getParams(d);
destinationGetInfo.push({ url:url, config: d});
}
}
this.inWindow = true;
if (destinationGetInfo.length > 0) {
this.sendSocketNotification("GOOGLE_TRAFFIC_GET", {destinations: destinationGetInfo, instanceId: this.identifier});
} else {
this.hide(1000, {lockString: this.identifier});
this.inWindow = false;
this.isHidden = true;
}
this.lastUpdate = new Date();
} else {
this.hide(1000, {lockString: this.identifier});
this.inWindow = false;
this.isHidden = true;
}
},
getParams: function(dest) {
let params = "?";
params += "origin=" + encodeURIComponent(dest.origin || this.config.origin);
params += "&destination=" + encodeURIComponent(dest.destination);
params += "&key=" + (this.config.apiKey || this.config.apikey);
params += "&language=" + this.config.lang;
//travel mode
let mode = "driving";
if (dest.mode && this.travelModes.indexOf(dest.mode) !== -1) {
mode = dest.mode;
}
params += "&mode=" + mode;
//transit mode if travelMode = "transit"
if (mode === "transit" && dest.transitMode) {
const tModes = dest.transitMode.split("|");
let sanitizedTransitModes = "";
for (let i = 0; i < tModes.length; i++) {
if (this.transitModes.indexOf(tModes[i]) !== -1) {
sanitizedTransitModes += (sanitizedTransitModes === "" ? tModes[i] : "|" + tModes[i]);
}
}
if (sanitizedTransitModes.length > 0) {
params += "&transit_mode=" + sanitizedTransitModes;
}
}
if (dest.waypoints) {
const waypoints = dest.waypoints.split("|");
for (let i = 0; i < waypoints.length; i++) {
waypoints[i] = "via:" + encodeURIComponent(waypoints[i]);
}
params += "&waypoints=" + waypoints.join("|");
}
//avoid
if (dest.avoid) {
const a = dest.avoid.split("|");
let sanitizedAvoidOptions = "";
for (let i = 0; i < a.length; i++) {
if (this.avoidOptions.indexOf(a[i]) !== -1) {
sanitizedAvoidOptions += (sanitizedAvoidOptions === "" ? a[i] : "|" + a[i]);
}
}
if (sanitizedAvoidOptions.length > 0) {
params += "&avoid=" + sanitizedAvoidOptions;
}
}
if (dest.alternatives === true) {
params += "&alternatives=true";
}
if (dest.arrival_time) {
params += "&arrival_time=" + dest.arrival_time;
} else {
params += "&departure_time=now"; //needed for time based on traffic conditions
}
return params;
},
svgIconFactory: function(glyph) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttributeNS(null, "class", "transit-mode-icon");
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttributeNS("http://www.w3.org/1999/xlink", "href", "modules/MMM-MyCommute/icon_sprite.svg#" + glyph);
svg.appendChild(use);
return(svg);
},
formatTime: function(time, timeInTraffic) {
const timeEl = document.createElement("span");
timeEl.classList.add("travel-time");
let now = moment();
if (timeInTraffic != null) {
if(this.config.showArrivalTime) {
timeEl.innerHTML = moment.duration(Number(timeInTraffic), "seconds").format(this.config.travelTimeFormat, {trim: this.config.travelTimeFormatTrim}) + " - " + now.add(Number(timeInTraffic), "seconds").format("HH:mm");
}
else {
timeEl.innerHTML = moment.duration(Number(timeInTraffic), "seconds").format(this.config.travelTimeFormat, {trim: this.config.travelTimeFormatTrim});
}
const variance = timeInTraffic / time;
if (this.config.colorCodeTravelTime) {
if (variance > this.config.poorTimeThreshold) {
timeEl.classList.add("status-poor");
} else if (variance > this.config.moderateTimeThreshold) {
timeEl.classList.add("status-moderate");
} else {
timeEl.classList.add("status-good");
}
}
} else {
if(this.config.showArrivalTime) {
timeEl.innerHTML = moment.duration(Number(time), "seconds").format(this.config.travelTimeFormat, {trim: this.config.travelTimeFormatTrim}) + " - " + now.add(Number(time), "seconds").format("HH:mm");
}
else {
timeEl.innerHTML = moment.duration(Number(time), "seconds").format(this.config.travelTimeFormat, {trim: this.config.travelTimeFormatTrim});
}
timeEl.classList.add("status-good");
}
return timeEl;
},
getTransitIcon: function(dest, route) {
let transitIcon;
if (dest.transitMode) {
transitIcon = dest.transitMode.split("|")[0];
if (this.symbols[transitIcon] != null) {
transitIcon = this.symbols[transitIcon];
} else {
transitIcon = this.symbols[route.transitInfo[0].vehicle.toLowerCase()];
}
} else {
transitIcon = this.symbols[route.transitInfo[0].vehicle.toLowerCase()];
}
return transitIcon;
},
buildTransitSummary: function(transitInfo, summaryContainer) {
for (let i = 0; i < transitInfo.length; i++) {
const transitLeg = document.createElement("span");
transitLeg.classList.add("transit-leg");
transitLeg.appendChild(this.svgIconFactory(this.symbols[transitInfo[i].vehicle.toLowerCase()]));
const routeNumber = document.createElement("span");
routeNumber.innerHTML = transitInfo[i].routeLabel;
if (transitInfo[i].arrivalTime) {
routeNumber.innerHTML = routeNumber.innerHTML + " (" + moment(transitInfo[i].arrivalTime).format(this.config.nextTransitVehicleDepartureFormat) + ")";
}
transitLeg.appendChild(routeNumber);
summaryContainer.appendChild(transitLeg);
}
},
getHeader: function () {
var headerTitle = this.data.header;
if(this.config.showUpdated && this.config.showUpdatedPosition === "header") {
headerTitle += " - " + this.translate("LAST_REFRESHED")
if(this.lastUpdated){
headerTitle += this.lastUpdated.format("HH:mm");
} else {
headerTitle += "no update received yet";
}
}
return headerTitle;
},
getDom: function() {
const wrapper = document.createElement("div");
if (this.loading) {
const loading = document.createElement("div");
loading.innerHTML = this.translate("LOADING");
loading.className = "dimmed light small";
wrapper.appendChild(loading);
this.lastWrapper = wrapper;
return wrapper;
}
const destinations = this.getDestinations();
for (let i = 0; i < this.predictions.length; i++) {
const p = this.predictions[i];
const row = document.createElement("div");
row.classList.add("row");
const destination = document.createElement("span");
destination.className = "destination-label bright";
destination.innerHTML = p.config.label;
row.appendChild(destination);
const icon = document.createElement("span");
icon.className = "transit-mode bright";
let symbolIcon = "car";
if (destinations[i].color) {
icon.setAttribute("style", "color:" + p.config.color);
}
if (p.config.mode && this.symbols[p.config.mode]) {
symbolIcon = this.symbols[p.config.mode];
}
//different rendering for single route vs multiple
if (p.error) {
if(!this.config.showError){
return this.lastWrapper;
}
//no routes available. display an error instead.
const errorTxt = document.createElement("span");
errorTxt.classList.add("route-error");
errorTxt.innerHTML = "Error: " + p.error_msg;
row.appendChild(errorTxt);
console.error("MMM-MyCommute error: " + p.error_msg, "Config:", p.config);
} else if (p.routes.length === 1 || !this.config.showSummary) {
let r = p.routes[0];
//summary?
if (this.config.showSummary) {
var singleSummary = document.createElement("div");
singleSummary.classList.add("route-summary");
if (r.transitInfo) {
symbolIcon = this.getTransitIcon(p.config,r);
this.buildTransitSummary(r.transitInfo, singleSummary);
} else {
singleSummary.innerHTML = r.summary;
}
singleSummary.appendChild(this.formatTime(r.time, r.timeInTraffic));
row.appendChild(singleSummary);
}
else {
row.appendChild(this.formatTime(r.time, r.timeInTraffic));
}
} else {
row.classList.add("with-multiple-routes");
for (let j = 0; j < p.routes.length; j++) {
const routeSummaryOuter = document.createElement("div");
routeSummaryOuter.classList.add("route-summary-outer");
let r = p.routes[j];
var multiSummary = document.createElement("div");
multiSummary.classList.add("route-summary");
if (r.transitInfo) {
symbolIcon = this.getTransitIcon(p.config,r);
this.buildTransitSummary(r.transitInfo, multiSummary);
} else {
multiSummary.innerHTML = r.summary;
}
routeSummaryOuter.appendChild(multiSummary);
routeSummaryOuter.appendChild(this.formatTime(r.time, r.timeInTraffic));
row.appendChild(routeSummaryOuter);
}
}
const svg = this.svgIconFactory(symbolIcon);
icon.appendChild(svg);
row.appendChild(icon);
wrapper.appendChild(row);
}
if(this.config.showUpdated && this.config.showUpdatedPosition === "footer") {
const updatedRow = document.createElement("div");
updatedRow.classList.add("light");
updatedRow.classList.add("xsmall");
updatedRow.innerHTML = this.translate("LAST_REFRESHED") + this.lastUpdated.format("HH:mm");
wrapper.appendChild(updatedRow);
}
this.lastWrapper = wrapper;
return wrapper;
},
socketNotificationReceived: function(notification, payload) {
if (notification === "GOOGLE_TRAFFIC_RESPONSE" + this.identifier) {
this.predictions = payload;
this.lastUpdated = moment();
if (this.loading) {
this.loading = false;
if (this.isHidden) {
this.updateDom();
this.show(1000, { lockString: this.identifier });
} else {
this.updateDom(1000);
}
} else {
this.updateDom();
if ( this.isHidden ) {
this.show(1000, { lockString: this.identifier });
}
}
this.isHidden = false;
}
},
notificationReceived: function(notification, payload) {
if (notification === "DOM_OBJECTS_CREATED" && !this.inWindow) {
this.hide(0, { lockString: this.identifier });
this.isHidden = true;
} else if (notification === "CALENDAR_EVENTS") {
this.setAppointmentDestinations(payload);
}
}
});