-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfeed-form-impl.ts
More file actions
595 lines (551 loc) · 17.1 KB
/
Copy pathfeed-form-impl.ts
File metadata and controls
595 lines (551 loc) · 17.1 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import {GoogleSpreadsheet} from "google-spreadsheet";
import {GoogleAuth} from "google-auth-library";
import * as logger from "firebase-functions/logger";
import {type FeedSubmissionFormRequestBody} from "./types";
import {type CallableRequest, HttpsError} from "firebase-functions/v2/https";
import axios from "axios";
import {countries, continents, type TCountryCode} from "countries-list";
const SCOPES = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
];
export const writeToSheet = async (
request: CallableRequest<FeedSubmissionFormRequestBody>
) => {
try {
const uid = request.auth?.uid ?? "";
const sheetId = process.env.FEED_SUBMIT_GOOGLE_SHEET_ID;
if (sheetId === undefined || sheetId === "") {
throw new HttpsError("internal", "Google Sheet ID is not defined");
}
const auth = new GoogleAuth({
scopes: SCOPES,
});
const doc = await new GoogleSpreadsheet(sheetId, auth);
await doc.loadInfo();
const rawDataSheet = doc.sheetsByIndex[0];
const formData: FeedSubmissionFormRequestBody = request.data;
const rows = buildFeedRows(formData, uid);
await rawDataSheet.addRows(rows, {insert: true});
const projectId = process.env.GCLOUD_PROJECT || process.env.GCP_PROJECT;
const isProduction = projectId === "mobility-feeds-prod";
let githubIssueUrl = "";
if (
process.env.GITHUB_TOKEN !== undefined &&
process.env.GITHUB_TOKEN !== "" &&
isProduction
) {
githubIssueUrl = await createGithubIssue(
formData,
sheetId,
process.env.GITHUB_TOKEN
);
}
await sendSlackWebhook(
sheetId,
githubIssueUrl,
formData.isOfficialFeed === "yes"
);
return {message: "Data written to the new sheet successfully!"};
} catch (error) {
logger.error("Error writing to sheet:", error);
throw new HttpsError(
"internal",
"An error occurred while writing to the sheet."
);
}
};
// Google sheet types that were not exportable
type RowCellData = string | number | boolean | Date;
type RawRowData = RowCellData[] | Record<string, RowCellData>;
/* eslint-disable max-len */
// Google Sheets columns titles
export enum SheetCol {
Status = "Status",
Timestamp = "Timestamp",
TransitProvider = "Transit Provider",
CurrentUrl = "Current feed URL (for feed updates)",
DataType = "Data type",
IssueType = "Issue type",
DownloadUrl = "Download URL",
Country = "Country",
Subdivision = "Region (e.g Province, State)",
Municipality = "Municipality",
Name = "Feed Name",
UserId = "User ID",
LinkToDatasetLicense = "License URL",
AuthenticationType = "Authentication Type",
AuthenticationSignupLink = "API Key URL",
AuthenticationParameterName = "HTTP header or API key parameter name",
Note = "Note (any important clarifications so people know how to use your dataset)",
UserInterview = "User interview email",
DataProducerEmail = "Data producer email",
OfficialProducer = "Are you the official producer or transit agency responsible for this data?",
OfficialFeedSource = "Is Official Feed Source",
ToolsAndSupport = "What tools and support do you use to create your GTFS data?",
LinkToAssociatedGTFS = "Link to associated GTFS Schedule feed",
LogoPermission = "Do we have permission to share your logo on https://mobilitydatabase.org/contribute?",
UnofficialDesc = "Why was this feed created?",
UpdateFreq = "How often is this feed updated?",
EmptyLicenseUsage = "Feed intended for trip planners/third parties?",
}
/**
*
* @param {FeedSubmissionFormRequestBody} formData The request body from the feed submission form
* @param {string} uid The user ID of the user submitting the feed
* @return {RawRowData[]} Formatted rows data to be written to the Google Sheet
*/
export function buildFeedRows(
formData: FeedSubmissionFormRequestBody,
uid: string
): RawRowData[] {
/* eslint-enable max-len */
const rowsToAdd: RawRowData[] = [];
if (formData.dataType === "gtfs") {
rowsToAdd.push(
buildFeedRow(formData, {
dataTypeName: "GTFS Schedule",
downloadUrl: formData.feedLink ?? "",
currentUrl: formData.oldFeedLink ?? "",
uid,
})
);
} else {
if (formData.tripUpdates) {
rowsToAdd.push(
buildFeedRow(formData, {
dataTypeName: "GTFS Realtime - Trip Updates",
downloadUrl: formData.tripUpdates ?? "",
currentUrl: formData.oldTripUpdates ?? "",
uid,
})
);
}
if (formData.vehiclePositions) {
rowsToAdd.push(
buildFeedRow(formData, {
dataTypeName: "GTFS Realtime - Vehicle Positions",
downloadUrl: formData.vehiclePositions ?? "",
currentUrl: formData.oldVehiclePositions ?? "",
uid,
})
);
}
if (formData.serviceAlerts) {
rowsToAdd.push(
buildFeedRow(formData, {
dataTypeName: "GTFS Realtime - Service Alerts",
downloadUrl: formData.serviceAlerts ?? "",
currentUrl: formData.oldServiceAlerts ?? "",
uid,
})
);
}
}
return rowsToAdd;
}
/* eslint-disable max-len */
interface BuildRowParameters {
dataTypeName: string;
downloadUrl: string;
currentUrl: string;
uid: string;
}
/**
*
* @param {FeedSubmissionFormRequestBody} formData The request body from the feed submission form
* @param {BuildRowParameters} formRowParameters Specific parameters based on feed type
* @return {RawRowData} Formatted row data to be written to the Google Sheet
*/
export function buildFeedRow(
formData: FeedSubmissionFormRequestBody,
formRowParameters: BuildRowParameters
): RawRowData {
const dateNow = new Date();
return {
[SheetCol.Status]: "Feed Submitted",
[SheetCol.Timestamp]: dateNow.toLocaleString("en-US", {
timeZoneName: "short",
timeZone: "UTC",
}),
[SheetCol.TransitProvider]: formData.transitProviderName ?? "",
[SheetCol.CurrentUrl]: formRowParameters.currentUrl,
[SheetCol.DataType]: formRowParameters.dataTypeName,
[SheetCol.IssueType]:
formData.isUpdatingFeed === "yes" ? "Feed update" : "New feed",
[SheetCol.DownloadUrl]: formRowParameters.downloadUrl,
[SheetCol.Country]: formData.country ?? "",
[SheetCol.Subdivision]: formData.region ?? "",
[SheetCol.Municipality]: formData.municipality ?? "",
[SheetCol.Name]: formData.name ?? "",
[SheetCol.UserId]: formRowParameters.uid,
[SheetCol.LinkToDatasetLicense]: formData.licensePath ?? "",
[SheetCol.AuthenticationType]: formData.authType ?? "",
[SheetCol.AuthenticationSignupLink]: formData.authSignupLink ?? "",
[SheetCol.AuthenticationParameterName]: formData.authParameterName ?? "",
[SheetCol.UserInterview]: formData.userInterviewEmail ?? "",
[SheetCol.DataProducerEmail]: formData.dataProducerEmail ?? "",
[SheetCol.OfficialProducer]: formData.isOfficialProducer,
[SheetCol.OfficialFeedSource]: formData.isOfficialFeed ?? "",
[SheetCol.ToolsAndSupport]: formData.whatToolsUsedText ?? "",
[SheetCol.LinkToAssociatedGTFS]: formData.gtfsRelatedScheduleLink ?? "",
[SheetCol.LogoPermission]: formData.hasLogoPermission,
[SheetCol.UnofficialDesc]: formData.unofficialDesc ?? "",
[SheetCol.UpdateFreq]: formData.updateFreq ?? "",
[SheetCol.EmptyLicenseUsage]: formData.emptyLicenseUsage ?? "",
};
}
/**
* Sends a Slack webhook message to the configured Slack webhook URL
* @param {string} spreadsheetId The ID of the Google Sheet
* @param {string} githubIssueUrl The URL of the created GitHub issue
* @param {boolean} isOfficialSource Whether the feed is an official source
*/
async function sendSlackWebhook(
spreadsheetId: string,
githubIssueUrl: string,
isOfficialSource: boolean
) {
const slackWebhookUrl = process.env.SLACK_WEBHOOK_URL;
const sheetUrl = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/edit`;
if (slackWebhookUrl !== undefined && slackWebhookUrl !== "") {
let headerText = "New Feed Added";
if (isOfficialSource) {
headerText += " 🔹 Official Source";
}
const linksElement = [
{
type: "emoji",
name: "google_drive",
},
{
type: "link",
url: sheetUrl,
text: " View Feed ",
style: {
bold: true,
},
},
];
if (githubIssueUrl !== "") {
linksElement.push(
{
type: "emoji",
name: "github-logo",
},
{
type: "link",
url: githubIssueUrl,
text: " View Issue ",
style: {
bold: true,
},
}
);
}
const slackMessage = {
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: headerText,
emoji: true,
},
},
{
type: "rich_text",
elements: [
{
type: "rich_text_section",
elements: [
{
type: "emoji",
name: "inbox_tray",
},
{
type: "text",
text: " A new entry was received in the OpenMobilityData source updates Google Sheet",
},
],
},
],
},
{
type: "rich_text",
elements: [
{
type: "rich_text_section",
elements: linksElement,
},
],
},
],
};
await axios.post(slackWebhookUrl, slackMessage).catch((error) => {
logger.error("Error sending Slack webhook:", error);
});
} else {
logger.error("Slack webhook URL is not defined");
}
}
/* eslint-enable max-len */
/**
* Creates a GitHub issue in the Mobility Database Catalogs repository
* @param {FeedSubmissionFormRequestBody} formData feed submission form
* @param {string} spreadsheetId googleshhet id
* @param {string} githubToken github token to create the issue
* @return {Promise<string>} The URL of the created GitHub issue
*/
async function createGithubIssue(
formData: FeedSubmissionFormRequestBody,
spreadsheetId: string,
githubToken: string
): Promise<string> {
const githubRepoUrlIssue =
"https://api.github.com/repos/MobilityData/mobility-database-catalogs/issues";
let issueTitle =
"New Feed Added" +
(formData.transitProviderName ? `: ${formData.transitProviderName}` : "");
if (formData.isOfficialFeed === "yes") {
issueTitle += " - Official Feed";
}
const issueBody = buildGithubIssueBody(formData, spreadsheetId);
const labels = ["feed submission"];
if (formData.country && formData.country in countries) {
const country = countries[formData.country as TCountryCode];
const continent = continents[country.continent].toLowerCase();
if (continent != null) labels.push(`region/${continent}`);
}
if (formData.authType !== "None - 0") {
labels.push("auth required");
}
if (!isValidZipUrl(formData.feedLink)) {
if (!await isValidZipDownload(formData.feedLink)) {
labels.push("invalid");
}
}
try {
const response = await axios.post(
githubRepoUrlIssue,
{
title: issueTitle,
body: issueBody,
labels,
},
{
headers: {
Authorization: `token ${githubToken}`,
Accept: "application/vnd.github.v3+json",
},
}
);
const issueNodeId = response.data.node_id;
const projectId = "PVT_kwDOAnHxDs4Ayxl6";
const statusFieldId = "PVTSSF_lADOAnHxDs4Ayxl6zgorIUI";
const backlogOptionId = "8e14ac56";
await addIssueToProjectV2(
issueNodeId,
githubToken,
projectId,
statusFieldId,
backlogOptionId
);
return response.data.html_url;
} catch (error) {
logger.error("Error creating GitHub issue:", error);
return "";
}
}
// Markdown format is strange in strings, so we disable eslint for this function
/* eslint-disable */
export function buildGithubIssueBody(
formData: FeedSubmissionFormRequestBody,
spreadsheetId: string
) {
let content = "";
if (formData.transitProviderName) {
content += `
# Agency name/Transit Provider: ${formData.name}`;
}
if (formData.country || formData.region || formData.municipality) {
let locationName = formData.country ?? "";
locationName += formData.region ? `, ${formData.region}` : "";
locationName += formData.municipality ? `, ${formData.municipality}` : "";
content += `
### Location
${locationName}`;
}
content += `
## Details`;
content += `
#### Data type
${formData.dataType}
#### Issue type
${formData.isUpdatingFeed === "yes" ? "Feed update" : "New feed"}`;
if (formData.name) {
content += `
#### Name
${formData.name}`;
}
content += `
## URLs
| Current URL on OpenMobilityData.org | Updated/new feed URL |
|---|---|`;
if (formData.dataType === "gtfs") {
content += `
| ${formData.oldFeedLink} | ${formData.feedLink} |`;
} else {
if (formData.tripUpdates) {
content += `
| ${formData.oldTripUpdates} | ${formData.tripUpdates} |`;
}
if (formData.vehiclePositions) {
content += `
| ${formData.oldVehiclePositions} | ${formData.vehiclePositions} |`;
}
if (formData.serviceAlerts) {
content += `
| ${formData.oldServiceAlerts} | ${formData.serviceAlerts} |`;
}
}
content += `
## Authentication
#### Authentication type
${formData.authType}`;
if (formData.authSignupLink) {
content += `
#### Link to how to sign up for authentication credentials (API KEY)
${formData.authSignupLink}`;
}
if (formData.authParameterName) {
content += `
#### HTTP header or API key parameter name
${formData.authParameterName}`;
}
content += `
## View more details
https://docs.google.com/spreadsheets/d/${spreadsheetId}/edit`;
return content;
}
/* eslint-enable */
/**
* Parses the provided URL to check if it is a valid ZIP file URL
* @param {string | undefined | null } url The direct download URL
* @return {boolean} Whether the URL is a valid ZIP file URL
*/
function isValidZipUrl(url: string | undefined | null): boolean {
if (!url) return false;
try {
const parsed = new URL(url);
return parsed.pathname.toLowerCase().endsWith(".zip");
} catch {
return false;
}
}
/**
* Checks if URL points to a valid ZIP file by making HEAD request
* @param {string | undefined | null } url The download URL
* @return {boolean} Whether the URL downloads a valid ZIP file
*/
async function isValidZipDownload(
url: string | undefined | null
): Promise<boolean> {
try {
if (!url) return false;
const response = await axios.head(url, {maxRedirects: 2});
const contentType = response.headers["content-type"];
const contentDisposition = response.headers["content-disposition"];
if (contentType && contentType.includes("zip")) return true;
if (contentDisposition && contentDisposition.includes("zip")) return true;
return false;
} catch {
return false;
}
}
/**
* Adds a GitHub issue to a project with a specific status
* @param {string} issueNodeId The ID of the created issue
* @param {string} githubToken GitHub token
* @param {string} projectId The ID of the project
* @param {string} statusFieldId The ID of the Status field
* @param {string} statusOptionId The ID of the status option
*/
async function addIssueToProjectV2(
issueNodeId: string,
githubToken: string,
projectId: string,
statusFieldId: string,
statusOptionId: string
) {
try {
const addToProjectMutation = `
mutation($projectId: ID!, $contentId: ID!) {
addProjectV2ItemById(
input: {projectId: $projectId, contentId: $contentId}
) {
item { id }
}
}
`;
const addToProjectResponse = await axios.post(
"https://api.github.com/graphql",
{
query: addToProjectMutation,
variables: {
projectId,
contentId: issueNodeId,
},
},
{
headers: {
Authorization: `bearer ${githubToken}`,
Accept: "application/vnd.github.v3+json",
},
}
);
const itemId = addToProjectResponse.data.data.addProjectV2ItemById.item.id;
const updateStatusMutation = `
mutation(
$projectId: ID!
$itemId: ID!
$fieldId: ID!
$value: ProjectV2FieldValue!
) {
updateProjectV2ItemFieldValue(
input: {
projectId: $projectId
itemId: $itemId
fieldId: $fieldId
value: $value
}
) {
projectV2Item { id }
}
}
`;
await axios.post(
"https://api.github.com/graphql",
{
query: updateStatusMutation,
variables: {
projectId,
itemId,
fieldId: statusFieldId,
value: {
singleSelectOptionId: statusOptionId,
},
},
},
{
headers: {
Authorization: `bearer ${githubToken}`,
Accept: "application/vnd.github.v3+json",
},
}
);
logger.info("Successfully added issue to Feed Submissions Backlog");
} catch (error) {
logger.error("Error adding issue to Feed Submissions Backlog:", error);
}
}