-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgcloud.ts
More file actions
401 lines (369 loc) · 10.4 KB
/
Copy pathgcloud.ts
File metadata and controls
401 lines (369 loc) · 10.4 KB
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import path from "path";
import * as google from "googleapis";
import { getAccessToken } from "./oauth";
import { OauthProvider, Ofmi, ParticipationRole } from "@prisma/client";
import { findParticipants, friendlyOfmiName } from "./ofmi";
import { PronounName } from "@/types/pronouns";
import { jsonToCsv } from "@/utils";
import config from "@/config/default";
import { TTLCache } from "./cache";
export const FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
const SPREADSHEETS_MIME_TYPE = "application/vnd.google-apps.spreadsheet";
export const spreadsheetURL = (id: string): string =>
`https://docs.google.com/spreadsheets/d/${id}`;
const caches = {
findOrCreateResource: new TTLCache<string>(),
};
export async function getGoogleAuth(
userAuthId: string,
): Promise<google.Auth.OAuth2Client> {
const token = await getAccessToken(userAuthId, OauthProvider.GCLOUD);
return new google.Auth.OAuth2Client({
credentials: {
access_token: token,
},
});
}
export async function trashResource({
id,
service,
}: {
id: string;
service: google.drive_v3.Drive;
}): Promise<void> {
await service.files.update({
fileId: id,
requestBody: {
trashed: true,
},
supportsAllDrives: true,
});
}
// Returns the id of the resource
async function findOrCreateResource({
mimeType,
name,
parentFolderId,
service,
}: {
mimeType: string;
name: string;
parentFolderId: string;
service: google.drive_v3.Drive;
}): Promise<string> {
// Check if the cache has the result
const ttlCache = caches["findOrCreateResource"];
const cacheKey = `${name}:${parentFolderId}:${mimeType}`;
const cacheValue = ttlCache.get(cacheKey);
if (cacheValue) {
return cacheValue;
}
const { data } = await service.files.list({
q: `trashed=false and name='${name}' and '${parentFolderId}' in parents and mimeType = '${mimeType}'`,
includeItemsFromAllDrives: true,
supportsAllDrives: true,
});
if (!data.files) {
throw Error("Google Drive API failed. findOrCreateResource -> not files");
}
let id: string | null = null;
if (data.files.length === 0) {
id =
(
await service.files.create({
requestBody: {
mimeType: mimeType,
name: name,
parents: [parentFolderId],
},
fields: "id",
supportsAllDrives: true,
})
).data.id ?? null;
} else {
id = data.files[0].id ?? null;
}
if (!id) {
throw Error(
"Google Drive API failed. findOrCreateResource -> not folderId",
);
}
ttlCache.set(cacheKey, id);
return id;
}
export async function getOrCreateFolder({
dir,
service,
parentFolderId,
}: {
dir: string;
service: google.drive_v3.Drive;
parentFolderId: string;
}): Promise<string> {
if (!dir) {
return parentFolderId;
}
const parts = dir.split("/");
const base = parts[0];
const rest = parts.slice(1).join("/");
const folderId = await findOrCreateResource({
mimeType: FOLDER_MIME_TYPE,
name: base,
parentFolderId: parentFolderId,
service,
});
return await getOrCreateFolder({
dir: rest,
parentFolderId: folderId,
service,
});
}
async function getOrCreateFile({
filepath,
service,
mimeType,
parentFolderId,
}: {
filepath: string;
service: google.drive_v3.Drive;
mimeType: string;
parentFolderId: string;
}): Promise<string> {
const filename = path.basename(filepath);
const dir = path.dirname(filepath);
const folderId = await getOrCreateFolder({
dir,
service,
parentFolderId,
});
return await findOrCreateResource({
mimeType,
parentFolderId: folderId,
name: filename,
service,
});
}
async function getOrCreateSheets({
names,
spreadsheetId,
service,
}: {
names: Array<string>;
spreadsheetId: string;
service: google.sheets_v4.Sheets;
}): Promise<Array<number>> {
const existingSheetsResponse = await service.spreadsheets.get({
spreadsheetId,
});
const existingSheets =
existingSheetsResponse.data.sheets?.slice(0, names.length) || [];
const { data } = await service.spreadsheets.batchUpdate({
spreadsheetId,
requestBody: {
requests: [
// Upsert sheet names
...names.map((title, index) => {
const existingSheetProperties = existingSheets.at(index)?.properties;
if (!existingSheetProperties) {
return {
addSheet: {
properties: { title, index },
},
};
}
return {
updateSheetProperties: {
fields: "*",
properties: { ...existingSheetProperties, title },
},
};
}),
],
},
});
return names.map((_, index) => {
const dataSheetId = data.replies?.at(index)?.addSheet?.properties?.sheetId;
const existingSheetId = existingSheets.at(index)?.properties?.sheetId;
const sheetId = dataSheetId || existingSheetId;
if (sheetId === null || sheetId === undefined) {
throw Error("Could not find sheet Id");
}
return sheetId;
});
}
export async function listResourceChildren({
folderId,
mimeType,
mimeTypeOp = "=",
service,
}: {
folderId: string;
mimeType: string;
mimeTypeOp?: string;
service: google.drive_v3.Drive;
}): Promise<google.drive_v3.Schema$File[]> {
const { data } = await service.files.list({
q: `trashed=false and '${folderId}' in parents and mimeType ${mimeTypeOp} '${mimeType}'`,
includeItemsFromAllDrives: true,
supportsAllDrives: true,
});
return data.files || [];
}
export async function listFolderChildren({
folderId,
service,
}: {
folderId: string;
service: google.drive_v3.Drive;
}): Promise<google.drive_v3.Schema$File[]> {
return await listResourceChildren({
folderId,
mimeType: FOLDER_MIME_TYPE,
service,
});
}
// Returns the URL of the Drive Folder
export async function getOrCreateDriveFolder({
userAuthId,
dir,
rootFolderId,
}: {
userAuthId: string;
dir: string;
rootFolderId: string;
}): Promise<string> {
const auth = await getGoogleAuth(userAuthId);
const service = new google.drive_v3.Drive({
auth,
});
const id = await getOrCreateFolder({
dir,
service,
parentFolderId: rootFolderId,
});
return `https://drive.google.com/drive/folders/${id}`;
}
export async function exportParticipants({
userAuthId,
ofmi,
spreadsheetName,
}: {
userAuthId: string;
ofmi: Ofmi;
spreadsheetName: string;
}): Promise<string> {
const auth = await getGoogleAuth(userAuthId);
const service = new google.drive_v3.Drive({
auth,
});
const spreadsheetId = await getOrCreateFile({
filepath: spreadsheetName,
service,
mimeType: SPREADSHEETS_MIME_TYPE,
parentFolderId: config.GDRIVE_OFMI_ROOT_FOLDER,
});
const sheets = new google.sheets_v4.Sheets({ auth });
const sheetNames = [
ParticipationRole.CONTESTANT,
ParticipationRole.VOLUNTEER,
];
const sheetIds = await getOrCreateSheets({
names: sheetNames,
spreadsheetId,
service: sheets,
});
const contestantSheetId = sheetIds.at(0);
const volunteerSheetId = sheetIds.at(1);
if (contestantSheetId === undefined || volunteerSheetId === undefined) {
throw Error("Bug: Sheet id do not coincide");
}
// Retrieve data
const participants = await findParticipants(ofmi);
const participantsFolderId = await getOrCreateFolder({
dir: path.join(friendlyOfmiName(ofmi.edition), "Assets", "Participants"),
service,
parentFolderId: config.GDRIVE_OFMI_ROOT_FOLDER,
});
const driveFolders = await listFolderChildren({
folderId: participantsFolderId,
service,
});
const createData = (role: ParticipationRole): string => {
const json = participants
.filter((v) => v.userParticipation.role === role)
.map((participation) => {
const optInToString = (f: boolean): string => {
return f ? "Sí" : "No";
};
let data: Record<string, string> = {
"Nombre completo": `${participation.user.firstName.trim()} ${participation.user.lastName.trim()}`,
Email: participation.user.email.trim(),
Pronombre: PronounName(participation.user.pronouns),
"Fecha de nacimiento": `=DATEVALUE(MID("${participation.user.birthDate}",1,10))+TIMEVALUE(MID("${participation.user.birthDate}",12,8))`,
"Google Drive Folder": `https://drive.google.com/drive/folders/${
driveFolders.find((file) => file.name === participation.user.email)
?.id || ""
}`,
};
const { userParticipation } = participation;
if (userParticipation.role === "CONTESTANT") {
data = {
...data,
"Fecha de registro": `=DATEVALUE(MID("${participation.registeredAt}",1,10))+TIMEVALUE(MID("${participation.registeredAt}",12,8))`,
Estado: userParticipation.schoolState,
Escuela: userParticipation.schoolName.trim(),
};
} else if (userParticipation.role === "VOLUNTEER") {
data = {
...data,
Teléfono: participation.user.mailingAddress.phone,
"Comunidad / Redes": optInToString(
userParticipation.communityOptIn,
),
"Vinculación educativa": optInToString(
userParticipation.educationalLinkageOptIn,
),
Fundraising: optInToString(userParticipation.fundraisingOptIn),
Entrenamientos: optInToString(userParticipation.trainerOptIn),
Problemsetter: optInToString(userParticipation.problemSetterOptIn),
Mentorías: optInToString(userParticipation.mentorOptIn),
};
}
return data;
});
return jsonToCsv(json);
};
// Paste data
await sheets.spreadsheets.batchUpdate({
spreadsheetId,
requestBody: {
requests: [
// Update CONTESTANT sheet
{
pasteData: {
coordinate: {
sheetId: contestantSheetId,
rowIndex: 0,
columnIndex: 0,
},
data: createData(ParticipationRole.CONTESTANT),
delimiter: ",",
},
},
// Update VOLUNTEER sheet
{
pasteData: {
coordinate: {
sheetId: volunteerSheetId,
rowIndex: 0,
columnIndex: 0,
},
data: createData(ParticipationRole.VOLUNTEER),
delimiter: ",",
},
},
],
},
});
return spreadsheetId;
}