-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathgooglefit.gs
286 lines (259 loc) · 8.89 KB
/
googlefit.gs
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
const googleFit = {
"serviceName": "GoogleFit",
"clientId": PropertiesService.getScriptProperties().getProperty('GOOGLE_API_CLIENT_ID'),
"clientSecret": PropertiesService.getScriptProperties().getProperty('GOOGLE_API_CLIENT_SECRET'),
"setAuthorizationBaseUrl": "https://accounts.google.com/o/oauth2/auth",
"tokenUrl": "https://oauth2.googleapis.com/token",
"dataSourceUrl": "https://www.googleapis.com/fitness/v1/users/me/dataSources",
"callback": "gfAuthCallback",
"scope": "https://www.googleapis.com/auth/fitness.body.write",
"weight": "com.google.weight",
"fat": "com.google.body.fat.percentage"
}
/**
* GoogleFit用の認証サービスを取得する。
*/
const getGFService = () => {
return OAuth2.createService(googleFit.serviceName)
.setAuthorizationBaseUrl(googleFit.setAuthorizationBaseUrl)
.setTokenUrl(googleFit.tokenUrl)
.setClientId(googleFit.clientId)
.setClientSecret(googleFit.clientSecret)
.setCallbackFunction(googleFit.callback)
.setPropertyStore(property)
.setScope(googleFit.scope)
.setParam("login_hint", Session.getActiveUser().getEmail())
.setParam("access_type", "offline")
.setParam("approval_prompt", "force");
}
/**
* GoogleFitのOAuth認証が完了したときに呼ばれるコールバック関数。
*/
const gfAuthCallback = (request) => {
const gfService = getGFService();
const isAuthorized = gfService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput("Success!");
} else {
return HtmlService.createHtmlOutput("Denied.");
}
}
/**
* GoogleFitにデータソースを作成する。
*/
const createGFDataSource = (service, dataName) => {
const payload = {
"dataStreamName": "TanitaScales",
"type": "raw",
"application": {
"detailsUrl": "http://example.com",
"name": "GoogleFit Transmitter",
"version": "1"
},
"dataType": {
"field": [
{
"name": dataName === googleFit.weight ? "weight" : "percentage",
"format": "floatPoint"
}
],
"name": dataName
},
"device": {
"manufacturer": "TANITA",
"model": SCALE_MODEL,
"type": "scale",
"uid": "1000001",
"version": "1.0"
}
};
const options = {
"headers": {
"Authorization": "Bearer " + service.getAccessToken()
},
"muteHttpExceptions": true,
"method": "POST",
"contentType": "application/json",
"payload": JSON.stringify(payload, null, 2)
};
const response = UrlFetchApp.fetch(googleFit.dataSourceUrl, options);
if (response.getResponseCode() === HTTP_STATUS_CODE_CONFLICT) {
console.log("GoogleFit data source %s is ready", dataName);
} else if (response.getResponseCode() === HTTP_STATUS_CODE_OK) {
const json = JSON.parse(response);
if (!property.getProperty(dataName)) {
property.setProperty(dataName, json.dataStreamId);
}
console.log("GoogleFit data source %s has been created successfully", dataName);
} else {
console.log("Failed to create GoogleFit data source %s", dataName);
console.log(response.getResponseCode());
console.log(response.getContentText());
}
}
/**
* GoogleFitへヘルスデータ(体重・体脂肪率)を登録する。
*/
const postHealthData = (service, dataName, healthData) => {
// 登録するデータセットの最小時刻と最大時刻を算出する
const minTime = Math.min.apply(null, healthData.data.map((elem) => { return elem.date; })).toString();
const maxTime = Math.max.apply(null, healthData.data.map((elem) => { return elem.date; })).toString();
const minTimeNs = convertUnixStartTime(minTime);
const maxTimeNs = convertUnixEndTime(maxTime);
payload = {
minStartTimeNs: minTimeNs,
maxEndTimeNs: maxTimeNs,
dataSourceId: property.getProperty(dataName),
point: []
};
healthData.data.map((elem) => {
if ((dataName === googleFit.weight ? BODY_WEIGHT : BODY_FAT) === elem.tag) {
payload.point.push({
startTimeNanos: convertUnixStartTime(elem.date),
endTimeNanos: convertUnixEndTime(elem.date),
dataTypeName: dataName,
value: [{ fpVal: elem.keydata }]
});
}
});
const options = {
"headers": {
"Authorization": "Bearer " + service.getAccessToken()
},
"muteHttpExceptions": true,
"method": "PATCH",
"contentType": "application/json",
"payload": JSON.stringify(payload, null, 2)
};
const response = UrlFetchApp.fetch(
Utilities.formatString(
"%s/%s/datasets/%s",
googleFit.dataSourceUrl,
property.getProperty(dataName),
`${minTimeNs}-${maxTimeNs}`
),
options
);
if (response.getResponseCode = HTTP_STATUS_CODE_OK) {
console.log("GoogleFit datasets %s have been registered successfully", dataName);
console.log(response.getContentText());
} else {
console.log("Failed to register GoogleFit datasets %s", dataName);
console.log(response.getResponseCode());
console.log(response.getContentText());
}
}
/**
* 指定した日付(文字列)の開始時刻をナノ秒精度のUNIX時間に変換する。
*/
const convertUnixStartTime = (dateString) => {
return dayjs.dayjs(dateString, "YYYYMMDDHHmm").unix() * TO_NS;
}
/**
* 指定した日付(文字列)の終了時刻をナノ精度のUNIX時間に変換する。
*/
const convertUnixEndTime = (dateString) => {
return dayjs.dayjs(dateString, "YYYYMMDDHHmm").unix() * TO_NS;
}
/**
* GoogleFitのデータソースを列挙する(開発時用、単独で実行する)。
*/
const listGFDataSource = () => {
const gfService = getGFService();
const options = {
"headers": {
"Authorization": "Bearer " + gfService.getAccessToken()
},
"muteHttpExceptions": true,
"method": "GET"
};
const response = UrlFetchApp.fetch(googleFit.dataSourceUrl, options);
console.log(response.getResponseCode());
console.log(response.getContentText());
}
/**
* GoogleFitのデータソースを削除する(開発時用、単独で実行する)。
* データを削除するには事前に全てのヘルスデータが削除されている必要がある。
*/
const removeGFDataSource = () => {
// 処理したいデータに合わせてコメントアウトを入れ替える
const dataName = googleFit.weight;
// const dataName = googleFit.fat;
const gfService = getGFService();
const options = {
"headers": {
"Authorization": "Bearer " + gfService.getAccessToken()
},
"muteHttpExceptions": true,
"method": "DELETE"
};
const response = UrlFetchApp.fetch(
Utilities.formatString(
"%s/%s",
googleFit.dataSourceUrl,
property.getProperty(dataName)
),
options
);
console.log(response.getResponseCode());
console.log(response.getContentText());
}
/**
* GoogleFitからヘルスデータを削除する(開発時用、単独で実行する)。
*/
const removeHealthData = () => {
// 処理したいデータに合わせてコメントアウトを入れ替える
const dataName = googleFit.weight;
// const dataName = googleFit.fat;
const gfService = getGFService();
const listOptions = {
"headers": {
"Authorization": "Bearer " + gfService.getAccessToken()
},
"muteHttpExceptions": true,
"method": "GET"
};
const listResponse = UrlFetchApp.fetch(
Utilities.formatString(
"%s/%s/dataPointChanges",
googleFit.dataSourceUrl,
property.getProperty(dataName),
),
listOptions
);
console.log(listResponse.getResponseCode());
console.log(listResponse.getContentText());
const json = JSON.parse(listResponse);
// 登録されたデータセットの最小時刻と最大時刻を算出する
const minTime = Math.min.apply(null, json.insertedDataPoint.map((elem) => { return elem.startTimeNanos; })).toString();
const maxTime = Math.max.apply(null, json.insertedDataPoint.map((elem) => { return elem.endTimeNanos; })).toString();
const deleteOptions = {
"headers": {
"Authorization": "Bearer " + gfService.getAccessToken()
},
"muteHttpExceptions": true,
"method": "DELETE"
};
const deleteResponse = UrlFetchApp.fetch(
Utilities.formatString(
"%s/%s/datasets/%s",
googleFit.dataSourceUrl,
property.getProperty(dataName),
`${minTime}-${maxTime}`
),
deleteOptions
);
console.log(listResponse.getResponseCode());
console.log(listResponse.getContentText());
}
/**
* プロパティにGoogleFitのデータソース名をセットする(開発時用、単独で実行する)。
* listGFDataSourceで取得したデータソース名をsetProperty第2引数に指定する。
* 各サービスのサイトで接続を解除した後に実行する。
*/
const setDataourceToProperty = () => {
console.log(property.getProperty(googleFit.weight));
console.log(property.getProperty(googleFit.fat));
property.setProperty(googleFit.weight, "< dataStreamId >");
property.setProperty(googleFit.fat, "< dataStreamId >");
}