-
Notifications
You must be signed in to change notification settings - Fork 1
/
google-fit.ts
334 lines (326 loc) · 11.2 KB
/
google-fit.ts
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
import { config, cosmicSync } from "@anandchowdhary/cosmic";
import slugify from "@sindresorhus/slugify";
import dayjs from "dayjs";
import isLeapYear from "dayjs/plugin/isLeapYear";
import isoWeeksInYear from "dayjs/plugin/isoWeeksInYear";
import week from "dayjs/plugin/weekOfYear";
import PromisePool from "es6-promise-pool";
import { lstat, pathExists, readdir, readJson } from "fs-extra";
import { fitness_v1, google } from "googleapis";
import { join } from "path";
import { integrationConfig, write } from "../common";
import type { Integration } from "../integration";
dayjs.extend(week);
dayjs.extend(isoWeeksInYear);
dayjs.extend(isLeapYear);
cosmicSync("stethoscope");
const oauth2Client = new google.auth.OAuth2(
config("googleFitClientId") || "example",
config("googleFitClientSecret") || "example",
"https://developers.google.com/oauthplayground"
);
oauth2Client.setCredentials({
access_token: config("googleFitAccessToken") || "example",
refresh_token: config("googleFitRefreshToken") || "example",
});
const fitness = google.fitness({ version: "v1", auth: oauth2Client });
const saveData = async (data: fitness_v1.Schema$Session[]) => {
const itemsByDateAndType: {
[index: string]: {
[index: string]: Array<fitness_v1.Schema$Session & { startTime?: Date; endTime?: Date }>;
};
} = {};
data.forEach((session) => {
if (session.startTimeMillis && session.name) {
const name = slugify(session.name);
const date = dayjs(new Date(parseInt(session.startTimeMillis)));
const year = date.format("YYYY");
const month = date.format("MM");
const day = date.format("DD");
itemsByDateAndType[name] = itemsByDateAndType[name] || {};
itemsByDateAndType[name][`${year}/${month}/${day}`] = itemsByDateAndType[name][`${year}/${month}/${day}`] || [];
itemsByDateAndType[name][`${year}/${month}/${day}`].push({
...session,
startTime: new Date(parseInt(session.startTimeMillis)),
endTime: session.endTimeMillis ? new Date(parseInt(session.endTimeMillis)) : undefined,
});
}
});
for await (const sessionType of Object.keys(itemsByDateAndType)) {
if (integrationConfig("google-fit", sessionType))
for await (const sessionDate of Object.keys(itemsByDateAndType[sessionType])) {
await write(
join(".", "data", `google-fit-${sessionType.replace(/_/g, "-")}`, "daily", sessionDate, "sessions.json"),
JSON.stringify(itemsByDateAndType[sessionType][sessionDate], null, 2)
);
}
}
};
const updateGoogleFitDailyData = async (date: Date) => {
const sources = await fitness.users.sessions.list({
userId: "me",
startTime: dayjs(date).startOf("day").toISOString(),
endTime: dayjs(date).endOf("day").toISOString(),
});
if (sources.data.session && sources.data.session.length) await saveData(sources.data.session);
console.log(`Fetched ${(sources.data.session || []).length || 0} workout sessions for ${date.toLocaleDateString()}`);
if (sources.data.session) await saveData(sources.data.session);
};
export default class GoogleFit implements Integration {
name = "google-fit";
cli = {};
async update() {
console.log("Google Fit: Starting...");
for await (const day of [0, 1, 2, 3, 4]) {
await updateGoogleFitDailyData(dayjs().subtract(day, "day").toDate());
console.log("Google Fit: Added data");
}
console.log("Google Fit: Added daily summaries");
}
async legacy(start: string) {
const startDate = dayjs(start);
for await (const count of [...Array(dayjs().diff(startDate, "day")).keys()]) {
const date = dayjs(startDate).add(count, "day");
await updateGoogleFitDailyData(date.toDate());
}
console.log("Done!");
}
async summary() {
for await (const category of [
"aerobics",
"archery",
"badminton",
"baseball",
"basketball",
"biathlon",
"biking",
"biking-hand",
"biking-mountain",
"biking-road",
"biking-spinning",
"biking-stationary",
"biking-utility",
"boxing",
"calisthenics",
"circuit-training",
"cricket",
"crossfit",
"curling",
"dancing",
"diving",
"elevator",
"elliptical",
"ergometer",
"escalator",
"extra-status",
"fencing",
"football-american",
"football-australian",
"football-soccer",
"frisbee-disc",
"gardening",
"golf",
"guided-breathing",
"gymnastics",
"handball",
"high-intensity-interval-training",
"hiking",
"hockey",
"horseback-riding",
"housework",
"ice-skating",
"interval-training",
"in-vehicle",
"jump-rope",
"kayaking",
"kettlebell-training",
"kickboxing",
"kick-scooter",
"kitesurfing",
"martial-arts",
"meditation",
"mime-type-prefix",
"mixed-martial-arts",
"on-foot",
"other",
"p90x",
"paragliding",
"pilates",
"polo",
"racquetball",
"rock-climbing",
"rowing",
"rowing-machine",
"rugby",
"running",
"running-jogging",
"running-sand",
"running-treadmill",
"sailing",
"scuba-diving",
"skateboarding",
"skating",
"skating-cross",
"skating-indoor",
"skating-inline",
"skiing",
"skiing-back-country",
"skiing-cross-country",
"skiing-downhill",
"skiing-kite",
"skiing-roller",
"sledding",
"sleep",
"sleep-awake",
"sleep-deep",
"sleep-light",
"sleep-rem",
"snowboarding",
"snowmobile",
"snowshoeing",
"softball",
"squash",
"stair-climbing",
"stair-climbing-machine",
"standup-paddleboarding",
"status-active",
"status-completed",
"still",
"strength-training",
"surfing",
"swimming",
"swimming-open-water",
"swimming-pool",
"table-tennis",
"team-sports",
"tennis",
"tilting",
"treadmill",
"unknown",
"volleyball",
"volleyball-beach",
"volleyball-indoor",
"wakeboarding",
"walking",
"walking-fitness",
"walking-nordic",
"walking-stroller",
"walking-treadmill",
"water-polo",
"weightlifting",
"wheelchair",
"windsurfing",
"yoga",
"zumba",
]) {
// Find all items that have daily
if (
(await pathExists(join(".", "data", `google-fit-${category}`, "daily"))) &&
(await lstat(join(".", "data", `google-fit-${category}`, "daily"))).isDirectory()
) {
const years = (await readdir(join(".", "data", `google-fit-${category}`, "daily"))).filter((i) =>
/^\d+$/.test(i)
);
const yearData: { [index: string]: number } = {};
const weeklyData: {
[index: string]: {
[index: string]: { [index: string]: number };
};
} = {};
for await (const year of years) {
let yearlySum = 0;
const monthlyData: { [index: string]: number } = {};
[...Array(13).keys()].slice(1).forEach((val) => (monthlyData[val.toString()] = 0));
const months = (await readdir(join(".", "data", `google-fit-${category}`, "daily", year))).filter((i) =>
/^\d+$/.test(i)
);
for await (const month of months) {
let monthlySum = 0;
const dailyData: { [index: string]: number } = {};
[...Array(dayjs(`${year}-${month}-10`).daysInMonth()).keys()]
.slice(1)
.forEach((val) => (dailyData[val.toString()] = 0));
const days = (
await readdir(join(".", "data", `google-fit-${category}`, "daily", year, month))
).filter((i) => /^\d+$/.test(i));
for await (const day of days) {
let json = await readJson(
join(".", "data", `google-fit-${category}`, "daily", year, month, day, "sessions.json")
);
let dailySum = 0;
if (Array.isArray(json)) {
// If it's a Google Fit health record
try {
json = json
.sort(
(a, b) =>
dayjs(a.startTime).unix() - dayjs(b.startTime).unix() ||
dayjs(a.endTime).unix() - dayjs(b.endTime).unix()
)
.reduce((r: Array<{ startTime: string; endTime: string }>, a) => {
const last = r[r.length - 1] || [];
if (
dayjs(last.startTime).unix() <= dayjs(a.startTime).unix() &&
dayjs(a.startTime).unix() <= dayjs(last.endTime).unix()
) {
if (dayjs(last.endTime).unix() < dayjs(a.endTime).unix()) {
last.endTime = a.endTime;
}
return r;
}
return r.concat(a);
}, []);
} catch (error) {}
json.forEach((record: any) => {
if (record.startTime && record.endTime) {
dailySum += dayjs(record.endTime).diff(record.startTime, "second");
} else if (record.total) {
dailySum += record.total;
}
});
}
if (dailySum) dailyData[parseInt(day)] = dailySum;
monthlySum += dailySum;
yearlySum += dailySum;
Object.keys(dailyData).forEach((key) => {
const weekNumber = dayjs(`${year}-${month}-${key}`).week();
weeklyData[year] = weeklyData[year] || {};
weeklyData[year][weekNumber] = weeklyData[year][weekNumber] || {};
weeklyData[year][weekNumber][`${year}-${month}-${key}`] = dailyData[key];
});
}
if (Object.keys(dailyData).length)
await write(
join(".", "data", `google-fit-${category}`, "summary", "days", year, `${month}.json`),
JSON.stringify(dailyData, null, 2)
);
if (monthlySum) monthlyData[parseInt(month)] = monthlySum;
}
if (Object.keys(monthlyData).length)
await write(
join(".", "data", `google-fit-${category}`, "summary", "months", `${year}.json`),
JSON.stringify(monthlyData, null, 2)
);
if (yearlySum) yearData[parseInt(year)] = yearlySum;
}
if (Object.keys(yearData).length)
await write(
join(".", "data", `google-fit-${category}`, "summary", "years.json"),
JSON.stringify(yearData, null, 2)
);
for await (const year of Object.keys(weeklyData)) {
for await (const week of Object.keys(weeklyData[year])) {
if (
Object.keys(weeklyData[year][week]).length &&
Object.values(weeklyData[year][week]).reduce((a, b) => a + b, 0)
)
await write(
join(".", "data", `google-fit-${category}`, "summary", "weeks", year, `${week}.json`),
JSON.stringify(weeklyData[year][week], null, 2)
);
}
}
}
}
}
}