This repository has been archived by the owner on Aug 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
node_helper.js
217 lines (177 loc) · 6.7 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
const NodeHelper = require("node_helper");
const request = require("request");
const jsonfile = require("./lib/jsonfile.js");
const path = require("path");
const dataFile = path.resolve(__dirname, "data.json");
const debugData = require("./debug_data.js");
module.exports = NodeHelper.create({
client_id: "846766038767-8fs63le8h45dhjpf0umhc1ai07q4rhn7.apps.googleusercontent.com",
client_secret: "kbJlTr7uQPCiClb5JSrGE-Ve",
config: {
//refresh_token
},
debug: false,
useDebugData: false,
tmpAuthData: undefined,
tmpAccessToken: undefined,
start: function () {
console.log("MMM-GoogleFit helper started...");
if (this.debug) {
console.log(process.versions);
}
try {
var c = jsonfile.readFileSync(dataFile);
if (c.refresh_token) {
this.config = c;
}
} catch (error) {
// Probably have not yet written the file, no worries
}
},
getAuthCode: function() {
var self = this;
var url = "https://accounts.google.com/o/oauth2/device/code";
var scopes = "email profile https://www.googleapis.com/auth/fitness.activity.read https://www.googleapis.com/auth/fitness.body.read";
request.post(url, { form: { client_id: self.client_id, scope: scopes } }, function(error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
self.tmpAuthData = data;
self.sendSocketNotification("AUTH_CODE_BODY", data);
self.getRefreshToken();
} else {
self.sendSocketNotification("AUTH_CODE_ERROR", response);
}
self.logRequest("getAuthCode", error, response, body);
});
},
getRefreshToken: function () {
var self = this;
var url = "https://www.googleapis.com/oauth2/v4/token";
var grant = "http://oauth.net/grant_type/device/1.0";
request.post(url, { form: { client_id: self.client_id, client_secret: self.client_secret, code: self.tmpAuthData.device_code, grant_type: grant } }, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
self.sendSocketNotification("REFRESH_TOKEN_BODY", data);
self.config.refresh_token = data.refresh_token;
self.writeConfig();
self.getAccessToken();
} else {
if (self.debug) {
console.error(response)
}
self.sendSocketNotification("REFRESH_TOKEN_ERROR", response);
setTimeout(function() { self.getRefreshToken() }, 10000);
}
self.logRequest("getRefreshToken", error, response, body);
});
},
getAccessToken: function(clientConfig) {
var self = this;
var url = "https://www.googleapis.com/oauth2/v4/token";
var grant = "refresh_token";
request.post(url, { form: { client_id: self.client_id, client_secret: self.client_secret, refresh_token: self.config.refresh_token, grant_type: grant } }, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
self.sendSocketNotification("ACCESS_TOKEN_BODY", data);
self.tmpAccessToken = data;
self.getStats(clientConfig);
} else {
self.sendSocketNotification("ACCESS_TOKEN_ERROR", response);
}
self.logRequest("getAccessToken", error, response, body);
});
},
logRequest: function(title, error, response, body) {
if (this.debug) {
console.log(title);
console.log("---------------------------------------------------------------------------------------------");
console.log("error");
console.log(error);
console.log("response");
console.log(response);
console.log("body");
console.log(body);
}
},
getStats: function (clientConfig) {
var self = this;
if (this.useDebugData) {
self.sendSocketNotification("STATS", debugData);
return;
}
var url = "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate";
var startTime = new Date();
startTime.setDate(startTime.getDate() - startTime.getDay()); // get last sunday
startTime.setHours(0, 0, 0, 0);
if (clientConfig.startOnMonday) { // start on monday instead
startTime.setDate(startTime.getDate() + 1);
}
if (clientConfig.lastSevenDays) {
startTime.setDate(new Date().getDate() - 6);
}
var endTime = new Date(startTime); // end sets month of start (Issue #9)
endTime.setDate(startTime.getDate() + 6);
endTime.setHours(23, 59, 59, 999);
var rotate = 0;
if (clientConfig.lastSevenDays) {
rotate = new Date().getDay() + 1;
} else if (clientConfig.startOnMonday) {
rotate = 1;
}
var days = ["S", "M", "T", "W", "T", "F", "S"];
if (rotate != 0) {
rotate %= days.length;
days = days.slice(rotate, days.length).concat(days.slice(0, rotate));
}
var req = {
"aggregateBy": [{
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 }, // 1 day per bucket
"startTimeMillis": startTime.getTime(),
"endTimeMillis": endTime.getTime()
};
if (clientConfig.displayWeight) {
req.aggregateBy.push({
"dataSourceId": "derived:com.google.weight:com.google.android.gms:merge_weight"
});
}
var options = {
url: url,
json: req,
headers: {
Authorization: "Bearer " + self.tmpAccessToken.access_token
}
}
request.post(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// body is already json at this point
body.days = days;
self.sendSocketNotification("STATS", body);
} else {
self.sendSocketNotification("STATS_ERROR", error);
self.sendSocketNotification("STATS_ERROR", response);
self.sendSocketNotification("STATS_ERROR", body);
}
self.logRequest("getStats", error, response, body);
});
},
writeConfig: function() {
jsonfile.writeFileSync(dataFile, this.config, { spaces: 2 });
},
//Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
if (notification === "UPDATE") {
if (this.config.refresh_token) {
this.sendSocketNotification("REFRESH_TOKEN_BODY", this.config.refresh_token);
this.getAccessToken(payload); // This will get an access token and then get stats afterwards if successful (payload is if we want last monday/sunday)
} else if (this.tmpAuthData) {
// Just in case refreshing the page before auth complete
this.sendSocketNotification("AUTH_CODE_BODY", this.tmpAuthData);
this.getRefreshToken();
} else {
this.getAuthCode();
}
}
}
});