-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfeed-form-impl.ts
More file actions
434 lines (405 loc) · 12.9 KB
/
Copy pathfeed-form-impl.ts
File metadata and controls
434 lines (405 loc) · 12.9 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
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";
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);
try {
const response = await axios.post(
githubRepoUrlIssue,
{
title: issueTitle,
body: issueBody,
labels: ["feed submission"],
},
{
headers: {
Authorization: `token ${githubToken}`,
Accept: "application/vnd.github.v3+json",
},
}
);
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 */