-
Notifications
You must be signed in to change notification settings - Fork 1
/
oura-ring.ts
268 lines (261 loc) · 9.49 KB
/
oura-ring.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
import { config, cosmicSync } from "@anandchowdhary/cosmic";
import axios from "axios";
import dayjs from "dayjs";
import isLeapYear from "dayjs/plugin/isLeapYear";
import isoWeeksInYear from "dayjs/plugin/isoWeeksInYear";
import week from "dayjs/plugin/weekOfYear";
import { lstat, pathExists, readdir, readJson } from "fs-extra";
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");
interface CategoryData {
[index: string]: number;
}
const updateOuraDailyData = async (date: Date) => {
const formattedDate = dayjs(date).format("YYYY-MM-DD");
if (integrationConfig("oura-ring", "weight")) {
const {
data: healthData,
}: {
data: {
age: number;
weight: number;
height: number;
gender: string;
email: string;
};
} = await axios.get(`https://api.ouraring.com/v1/userinfo?access_token=${config("ouraPersonalAccessToken")}`);
await write(
join(
".",
"data",
"oura-weight",
"daily",
dayjs(formattedDate).format("YYYY"),
dayjs(formattedDate).format("MM"),
dayjs(formattedDate).format("DD"),
"sessions.json"
),
JSON.stringify({ weight: healthData.weight }, null, 2)
);
console.log("Oura: Added summary data");
}
if (integrationConfig("oura-ring", "sleep")) {
const {
data: sleepData,
}: {
data: {
sleep: Array<{ summary_date: string }>;
};
} = await axios.get(
`https://api.ouraring.com/v1/sleep?start=${formattedDate}&end=${formattedDate}&access_token=${config(
"ouraPersonalAccessToken"
)}`
);
console.log("Oura: Added sleep data");
await write(
join(
".",
"data",
"oura-sleep",
"daily",
dayjs(formattedDate).format("YYYY"),
dayjs(formattedDate).format("MM"),
dayjs(formattedDate).format("DD"),
"sessions.json"
),
JSON.stringify(sleepData.sleep, null, 2)
);
}
if (integrationConfig("oura-ring", "readiness")) {
const {
data: readinessData,
}: {
data: {
readiness: Array<{ summary_date: string }>;
};
} = await axios.get(
`https://api.ouraring.com/v1/readiness?start=${formattedDate}&end=${formattedDate}&access_token=${config(
"ouraPersonalAccessToken"
)}`
);
console.log("Oura: Added readiness data");
await write(
join(
".",
"data",
"oura-readiness",
"daily",
dayjs(formattedDate).format("YYYY"),
dayjs(formattedDate).format("MM"),
dayjs(formattedDate).format("DD"),
"sessions.json"
),
JSON.stringify(readinessData.readiness, null, 2)
);
}
if (integrationConfig("oura-ring", "activity")) {
const {
data: activityData,
}: {
data: {
activity: Array<{ summary_date: string }>;
};
} = await axios.get(
`https://api.ouraring.com/v1/activity?start=${formattedDate}&end=${formattedDate}&access_token=${config(
"ouraPersonalAccessToken"
)}`
);
console.log("Oura: Added activity data");
await write(
join(
".",
"data",
"oura-activity",
"daily",
dayjs(formattedDate).format("YYYY"),
dayjs(formattedDate).format("MM"),
dayjs(formattedDate).format("DD"),
"sessions.json"
),
JSON.stringify(activityData.activity, null, 2)
);
}
};
export default class OuraRing implements Integration {
name = "oura-ring";
cli = {};
async update() {
console.log("Oura: Starting...");
for await (const day of [0, 1, 2, 3, 4]) {
await updateOuraDailyData(dayjs().subtract(day, "day").toDate());
console.log("Oura: Added data");
}
console.log("Oura: 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 updateOuraDailyData(date.toDate());
}
console.log("Done!");
}
async summary() {
for await (const category of ["oura-readiness", "oura-activity", "oura-weight", "oura-sleep"]) {
if (
(await pathExists(join(".", "data", category, "daily"))) &&
(await lstat(join(".", "data", category, "daily"))).isDirectory()
) {
for await (const file of ["sessions.json"]) {
const years = (await readdir(join(".", "data", category, "daily"))).filter((i) => /^\d+$/.test(i));
const yearData: { [index: string]: CategoryData } = {};
const weeklyData: {
[index: string]: { [index: string]: { [index: string]: CategoryData } };
} = {};
for await (const year of years) {
let yearlySum: CategoryData = {};
const monthlyData: { [index: string]: CategoryData } = {};
[...Array(13).keys()].slice(1).forEach((val) => (monthlyData[val.toString()] = {}));
const months = (await readdir(join(".", "data", category, "daily", year))).filter((i) => /^\d+$/.test(i));
for await (const month of months) {
let monthlySum: CategoryData = {};
const dailyData: { [index: string]: CategoryData } = {};
[...Array(dayjs(`${year}-${month}-10`).daysInMonth()).keys()]
.slice(1)
.forEach((val) => (dailyData[val.toString()] = {}));
const days = (await readdir(join(".", "data", category, "daily", year, month))).filter((i) =>
/^\d+$/.test(i)
);
for await (const day of days) {
let json: any[] = [];
try {
json = await readJson(join(".", "data", category, "daily", year, month, day, file));
} catch (error) {}
let dailySum: CategoryData = {};
if (Array.isArray(json) && json.length) {
json.forEach((record: any) => {
[
"steps",
"total",
"cal_active",
"cal_total",
"rem",
"awake",
"deep",
"duration",
"efficiency",
"light",
"score",
"score_activity_balance",
"score_hrv_balance",
"score_previous_day",
"score_previous_night",
"score_recovery_index",
"score_resting_hr",
"score_sleep_balance",
"score_temperature",
].forEach((dataType) => {
if (typeof record[dataType] === "number") {
dailySum[dataType] = dailySum[dataType] || 0;
dailySum[dataType] += record[dataType];
}
});
});
} else if (typeof json === "object") {
if (typeof (json as any).weight === "number") {
dailySum.weight = dailySum.weight || 0;
dailySum.weight += (json as any).weight;
}
}
if (Object.keys(dailySum).length) dailyData[parseInt(day)] = dailySum;
Object.keys(dailySum).forEach((key) => {
monthlySum[key] = monthlySum[key] || 0;
monthlySum[key] += dailySum[key];
yearlySum[key] = yearlySum[key] || 0;
yearlySum[key] += dailySum[key];
});
}
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", 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", 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", 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 + Object.keys(b).length, 0)
)
await write(
join(".", "data", category, "summary", "weeks", year, `${week}.json`),
JSON.stringify(weeklyData[year][week], null, 2)
);
}
}
}
}
}
}
}