-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMMM-Strava.js
374 lines (374 loc) · 12.4 KB
/
MMM-Strava.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
/**
* @file MMM-Strava.js
*
* @author ianperrin
* @license MIT
*
* @see https://github.com/ianperrin/MMM-Strava
*/
Module.register("MMM-Strava", {
// Set the minimum MagicMirror module version for this module.
requiresVersion: "2.2.0",
// Default module config.
defaults: {
client_id: "",
client_secret: "",
mode: "table", // Possible values "table", "chart"
chartType: "bar", // Possible values "bar", "radial"
activities: ["ride", "run", "swim"], // Possible values "alpineski", "backcountryski", "canoeing", "crossfit", "ebikeride", "elliptical", "golf", "handcycle", "hike", "iceskate", "inlineskate", "kayaking", "kitesurf", "nordicski", "ride", "rockclimbing", "rollerski", "rowing", "run", "sail", "skateboard", "snowboard", "snowshoe", "soccer", "stairstepper", "standuppaddling", "surfing", "swim", "velomobile", "virtualride", "virtualrun", "walk", "weighttraining", "wheelchair", "windsurf", "workout", "yoga"
period: "recent", // Possible values "recent", "ytd", "all"
stats: [], // Possible values "count", "distance", "elevation", "moving_time", "elapsed_time", "achievements"
auto_rotate: false, // Rotate stats through each period starting from specified period
locale: config.language,
units: config.units,
reloadInterval: 5 * 60 * 1000, // every 5 minutes
updateInterval: 10 * 1000, // 10 seconds
animationSpeed: 2.5 * 1000, // 2.5 seconds
debug: false, // Set to true to enable extending logging
digits: 1, // digits for distance and elevation
firstYear: new Date().getFullYear() - 4 // first year to group activities by in chart mode when the period is 'all'
},
/**
* @member {boolean} loading - Flag to indicate the loading state of the module.
*/
loading: true,
/**
* @member {boolean} rotating - Flag to indicate the rotating state of the module.
*/
rotating: false,
/**
* @function getStyles
* @description Style dependencies for this module.
* @override
*
* @returns {string[]} List of the style dependency filepaths.
*/
getStyles: function () {
return ["font-awesome.css", "MMM-Strava.css"];
},
/**
* @function getScripts
* @description Script dependencies for this module.
* @override
*
* @returns {string[]} List of the script dependency filepaths.
*/
getScripts: function () {
return ["moment.js"];
},
/**
* @function getTranslations
* @description Translations for this module.
* @override
*
* @returns {object.<string, string>} Available translations for this module (key: language code, value: filepath).
*/
getTranslations: function () {
return {
en: "translations/en.json",
de: "translations/de.json",
es: "translations/es.json",
fr: "translations/fr.json",
gr: "translations/gr.json",
hu: "translations/hu.json",
id: "translations/id.json",
it: "translations/it.json",
pt: "translations/pt.json",
nl: "translations/nl.json",
ru: "translations/ru.json"
};
},
/**
* @function start
* @description Validates config values, adds nunjuck filters and initialises requests for data.
* @override
*/
start: function () {
Log.info("Starting module: " + this.name);
// Validate config options
this.config.mode = this.config.mode.toLowerCase();
this.config.chartType = this.config.chartType.toLowerCase();
this.config.activities = this.filterActivities(this.config.activities.map((activity) => activity.toLowerCase()));
this.config.period = this.config.period.toLowerCase();
// Set stats defaults based on mode
if (!this.config.stats || this.config.stats.length === 0) {
const defaultChartStats = ["distance", "moving_time", "elevation"];
const defaultTableStats = ["count", "distance", "achievements"];
this.config.stats = this.config.mode === "chart" ? defaultChartStats : defaultTableStats;
}
this.config.stats = this.config.stats.map((stat) => stat.toLowerCase());
// Add custom filters
this.addFilters();
// Initialise helper and schedule api calls
this.sendSocketNotification("SET_CONFIG", { identifier: this.identifier, config: this.config });
this.scheduleUpdates();
},
/**
* @function socketNotificationReceived
* @description Handles incoming messages from node_helper.
* @override
*
* @param {string} notification - Notification name
* @param {Object,<string,*} payload - Detailed payload of the notification.
*/
socketNotificationReceived: function (notification, payload) {
this.log(`Receiving notification: ${notification} for ${payload.identifier}`);
if (payload.identifier === this.identifier) {
if (notification === "DATA") {
this.stravaData = payload.data;
this.loading = false;
this.updateDom(this.config.animationSpeed);
} else if (notification === "ERROR") {
this.loading = false;
this.error = payload.data.message;
this.updateDom(this.config.animationSpeed);
} else if (notification === "WARNING") {
this.loading = false;
this.sendNotification("SHOW_ALERT", { type: "notification", title: payload.data.message });
}
}
},
/**
* @function getTemplate
* @description Nunjuck template.
* @override
*
* @returns {string} Path to nunjuck template.
*/
getTemplate: function () {
return "templates\\MMM-Strava." + this.config.mode + ".njk";
},
/**
* @function getTemplateData
* @description Data that gets rendered in the nunjuck template.
* @override
*
* @returns {string} Data for the nunjuck template.
*/
getTemplateData: function () {
moment.locale(this.config.locale);
return {
config: this.config,
loading: this.loading,
error: this.error || null,
data: this.stravaData || {},
chart: { bars: this.config.period === "ytd" ? moment.monthsShort() : moment.weekdaysShort() }
};
},
/**
* @function scheduleUpdates
* @description Schedules table rotation
*/
scheduleUpdates: function () {
var self = this;
// Schedule table rotation
if (!this.rotating && this.config.mode === "table") {
this.rotating = true;
if (this.config.auto_rotate && this.config.updateInterval) {
setInterval(function () {
// Get next period
self.config.period = self.config.period === "recent" ? "ytd" : self.config.period === "ytd" ? "all" : "recent";
self.updateDom(self.config.animationSpeed);
}, this.config.updateInterval);
}
}
},
/**
* @function log
* @description logs the message, prefixed by the Module name, if debug is enabled.
* @param {string} msg the message to be logged
*/
log: function (msg) {
if (this.config && this.config.debug) {
Log.info(`${this.name}: ` + JSON.stringify(msg));
}
},
/**
* @function filterActivities
* @description Removes invalid activity values from an array.
*
* @param {Object} activityArray - Array of activities to be validated
*/
filterActivities: function (activityArray) {
var validActivities = this.config.mode === "chart" ? activityArray : this.defaults.activities;
return activityArray.filter(function (activity) {
return validActivities.indexOf(activity) === -1 ? false : true;
});
},
/**
* @function addFilters
* @description adds filters to the Nunjucks environment.
*/
addFilters() {
var env = this.nunjucksEnvironment();
env.addFilter("getIntervalClass", this.getIntervalClass.bind(this));
env.addFilter("getLabel", this.getLabel.bind(this));
env.addFilter("formatTime", this.formatTime.bind(this));
env.addFilter("formatDistance", this.formatDistance.bind(this));
env.addFilter("formatElevation", this.formatElevation.bind(this));
env.addFilter("roundValue", this.roundValue.bind(this));
env.addFilter("getRadialLabelTransform", this.getRadialLabelTransform.bind(this));
env.addFilter("getRadialDataPath", this.getRadialDataPath.bind(this));
},
/**
* @function getIntervalClass
* @description returns the CSS Class for the supplied interval based on the config period.
*/
getIntervalClass: function (interval) {
moment.locale(this.config.locale);
const currentIntervalMap = {
all: moment().year() - this.config.firstYear,
ytd: moment().month(),
recent: moment().weekday()
};
var currentInterval = currentIntervalMap[this.config.period];
var className = "future";
if (currentInterval === interval) {
className = "current";
} else if (currentInterval > interval) {
className = "past";
}
return className;
},
getLabel: function (interval) {
moment.locale(this.config.locale);
const intervalDateMap = {
all: moment().year(this.config.firstYear).add(interval, "years").format("YY"),
ytd: moment().startOf("year").add(interval, "months").format("MMM").slice(0, 1).toUpperCase(),
recent: moment().startOf("week").add(interval, "days").format("dd").slice(0, 1).toUpperCase()
};
return intervalDateMap[this.config.period];
},
formatTime: function (timeInSeconds) {
var duration = moment.duration(timeInSeconds, "seconds");
return Math.floor(duration.asHours()) + "h " + duration.minutes() + "m";
},
// formatDistance
formatDistance: function (value, digits, showUnits) {
const distanceMultiplier = this.config.units === "imperial" ? 0.0006213712 : 0.001;
const distanceUnits = this.config.units === "imperial" ? " mi" : " km";
return this.formatNumber(value, distanceMultiplier, digits, showUnits ? distanceUnits : null);
},
// formatElevation
formatElevation: function (value, digits, showUnits) {
const elevationMultiplier = this.config.units === "imperial" ? 3.28084 : 1;
const elevationUnits = this.config.units === "imperial" ? " ft" : " m";
return this.formatNumber(value, elevationMultiplier, digits, showUnits ? elevationUnits : null);
},
// formatNumber
formatNumber: function (value, multipler, digits, units) {
if (!isNaN(value)) {
// Convert value
value = value * multipler;
// Round value
value = this.roundValue(value, digits);
// Format number
value = new Number(value).toLocaleString(this.config.locale);
// Append units
if (units) {
value += units;
}
}
return value;
},
// getRadialLabelTransform
getRadialLabelTransform(index, count) {
const degrees = 360 / count / 2 + index * (360 / count);
const rotation = (index < count / 2 ? -90 : 90) + degrees;
const labelRadius = 96;
const translation = this.polarToCartesian(0, 0, labelRadius, degrees);
return `translate(${translation.x}, ${translation.y}) rotate(${rotation})`;
},
// getRadialDataPath
getRadialDataPath(index, count, value) {
const gap = 5;
const startAngle = gap / 2 + index * (360 / count);
const endAngle = startAngle + (360 - count * gap) / count;
const radius = { inner: 109, outer: 109 + value * 100 };
if (value > 0) {
// identify points
var p1 = this.polarToCartesian(0, 0, radius.inner, startAngle);
var p2 = this.polarToCartesian(0, 0, radius.outer - 10, startAngle);
var p3 = this.polarToCartesian(0, 0, radius.outer, startAngle + 5 / 2);
var p4 = this.polarToCartesian(0, 0, radius.outer, endAngle - 5 / 2);
var p5 = this.polarToCartesian(0, 0, radius.outer - 10, endAngle);
var p6 = this.polarToCartesian(0, 0, radius.inner, endAngle);
// describe path
var d = [
"M",
p1.x,
p1.y,
"L",
p2.x,
p2.y,
"A",
10,
10,
0,
0,
1,
p3.x,
p3.y,
"A",
radius.outer,
radius.outer,
0,
0,
1,
p4.x,
p4.y,
"A",
10,
10,
0,
0,
1,
p5.x,
p5.y,
"L",
p6.x,
p6.y,
"A",
radius.inner,
radius.inner,
0,
0,
0,
p1.x,
p1.y,
"L",
p1.x,
p1.y
].join(" ");
return d;
} else {
return "";
}
},
/**
* @function polarToCartesian
* @description Calculates the coordinates of a point on the circumference of a circle.
* @param {integer} centerX x
* @param {integer} centerY y
* @param {integer} radius radius of the circle
* @param {integer} angleInDegrees angle to the new point in degrees
* @see https://stackoverflow.com/questions/5736398/how-to-calculate-the-svg-path-for-an-arc-of-a-circle
*/
polarToCartesian: function (centerX, centerY, radius, angleInDegrees) {
var angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0;
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians)
};
},
/**
* @function roundValue
* @description rounds the value to number of digits.
* @param {decimal} value the value to be rounded
* @param {integer} digits the number of digits to round the value to
*/
roundValue: function (value, digits) {
var rounder = Math.pow(10, digits);
return (Math.round(value * rounder) / rounder).toFixed(digits);
}
});