Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 | import * as https from 'https'; import { CloudWatchClient, PutMetricDataCommand } from '@aws-sdk/client-cloudwatch'; import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; import { GetTranscriptionJobCommand, TranscribeClient } from '@aws-sdk/client-transcribe'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; import * as lambda from 'aws-lambda'; import { getTwilioSecret, twilioPhoneCategories, twilioPhoneNumbers } from '@/deprecated/utils/general'; import { FileTranslationObject, FullFileObject } from '@/types/api/files'; import { FullSiteObject } from '@/types/api/sites'; import { FullUserObject, PagingTalkgroup } from '@/types/api/users'; import { PhoneNumberTypes, departmentConfig, pagingTalkgroupConfig } from '@/types/backend/department'; import { TypedGetOutput, TypedUpdateInput } from '@/types/backend/dynamo'; import { ActivateUserQueueItem, PhoneNumberIssueQueueItem, SendPageQueueItem, SendUserAuthCodeQueueItem, SiteStatusQueueItem, TranscribeJobResultQueueItem, TwilioTextQueueItem } from '@/types/backend/queue'; import { TABLE_FILE, TABLE_FILE_TRANSLATION, TABLE_SITE, TABLE_USER, typedGet, typedQuery, typedScan, typedUpdate } from '@/utils/backend/dynamoTyped'; import { getPageNumber, getUserRecipients, saveMessageData, sendMessage } from '@/utils/backend/texts'; import { getLogger } from '@/utils/common/logger'; import { dateToTimeString, fNameToDate, formatPhone, randomString } from '@/utils/common/strings'; import { getUserPermissions } from '@/utils/common/user'; const logger = getLogger('queue'); const transcribe = new TranscribeClient(); const cloudWatch = new CloudWatchClient(); const s3 = new S3Client(); const cacheBucket = process.env.COSTS_BUCKET; type WelcomeMessageConfigKeys = 'name' | 'type' | 'pageNumber'; const welcomeMessageParts: { welcome: string; textGroup: string; textPageGroup: string; pageGroup: string; howToLeave: string; } = { welcome: 'Welcome to the {{name}} {{type}} group!', textGroup: 'This number will be used to send and receive messages from other members of the department.\n\nTo send a message to other members of your department, just send a text to this number. Any message you send will show up for others with your name and callsign attached.\n\nYou will receive important announcements from {{pageNumber}}. No-one except department administrators will be able to send announcements from that number.', textPageGroup: 'This number will be used to send and receive messages from other members of the department.\n\nIn a moment, you will receive a text from {{pageNumber}} with a link to a sample page similar to what you will receive. That number will only ever send you pages or important announcements.\n\nTo send a message to other members of your department, just send a text to this number. Any message you send will show up for others with your name and callsign attached.', pageGroup: 'This number will be used to send pages or important announcements.\n\nIn a moment, you will receive a text with a link to a sample page like that you will receive.', howToLeave: 'You can leave this group at any time by texting "STOP" to this number.', }; const codeTtl = 1000 * 60 * 5; // 5 minutes function createPageMessage( fileKey: string, pageTg: PagingTalkgroup, number: number | null = null, messageId: number | null = null, transcript: string | null = null ): string { logger.trace('createPageMessage', ...arguments); const pageConfig = pagingTalkgroupConfig[pageTg]; if (typeof pageConfig === 'undefined') { return `Invalid paging talkgroup - ${pageTg} - ${fileKey}`; } let pageStr = `${pageConfig.pagedService} PAGE\n`; pageStr += `${pageConfig.partyBeingPaged} paged `; pageStr += `${dateToTimeString(fNameToDate(fileKey))}\n`; if (transcript !== null) { pageStr += `\n${transcript}\n\n`; } pageStr += `https://cofrn.org/?f=${fileKey}&tg=${pageConfig.linkPreset}`; if (number !== null) { pageStr += `&p=${number}`; } if (messageId !== null) { pageStr += `&m=${messageId}`; } return pageStr; } interface TranscribeResult { jobName: string; results: { transcripts: { transcript: string; }[]; speaker_labels: { segments: { start_time: string; end_time: string; speaker_label: string; }[]; }, items: ({ type: 'pronunciation'; start_time: string; alternatives: { content: string; }[]; } | { type: 'punctuation'; alternatives: { content: string; }[]; })[]; }; } async function getItemToUpdate(key: string | null): Promise<FullFileObject | null> { logger.trace('getItemToUpdate', ...arguments); if (key === null) { return key; } let item: FullFileObject | null = null; let count = 0; do { const result = await typedQuery<FullFileObject>({ TableName: TABLE_FILE, IndexName: 'KeyIndex', ExpressionAttributeNames: { '#Key': 'Key', }, ExpressionAttributeValues: { ':Key': key, }, KeyConditionExpression: '#Key = :Key', }); if (!result.Items || result.Items.length === 0) { const resultMap: TypedGetOutput<FileTranslationObject> = await typedGet({ TableName: TABLE_FILE_TRANSLATION, Key: { Key: key, }, }); key = resultMap.Item?.NewKey || null; } else { item = result.Items[0]; } } while (item === null && key !== null && count++ < 10); return item; } async function handleTranscribe(body: TranscribeJobResultQueueItem) { logger.trace('handleTranscribe', ...arguments); // Check for the correct transcription job fomat if (!(/^\d{4,5}\-\d+$/).test(body.detail.TranscriptionJobName)) { throw new Error(`Invalid transcription job name - ${body.detail.TranscriptionJobName}`); } // Get the transcription results const transcriptionInfo = await transcribe.send(new GetTranscriptionJobCommand({ TranscriptionJobName: body.detail.TranscriptionJobName, })); const fileData: string = await new Promise((res, rej) => https.get( transcriptionInfo.TranscriptionJob?.Transcript?.TranscriptFileUri as string, response => { let data = ''; response.on('data', chunk => data += chunk); response.on('end', () => res(data)); } ).on('error', e => rej(e))); const result: TranscribeResult = JSON.parse(fileData); const transcript: string = result.results.transcripts[0].transcript === '' ? 'No voices detected' : result.results.transcripts[0].transcript; // Build the message let messageBody: string; let updateFilePromise: Promise<unknown> = new Promise(res => res(null)); let tg: PagingTalkgroup; const jobInfo: { [key: string]: string; } = (transcriptionInfo.TranscriptionJob?.Tags || []) .reduce((agg: { [key: string]: string; }, value) => { if ( typeof value.Key !== 'undefined' && typeof value.Value !== 'undefined' ) { agg[value.Key] = value.Value; } return agg; }, {}); if (jobInfo.Talkgroup) { tg = Number(jobInfo.Talkgroup) as PagingTalkgroup; messageBody = createPageMessage( jobInfo.File as string, tg, null, null, transcript ); updateFilePromise = getItemToUpdate(jobInfo.FileKey as string) .then(item => { if (item === null) { return; } return typedUpdate<FullFileObject>({ TableName: TABLE_FILE, Key: { Talkgroup: item.Talkgroup, Added: item.Added, }, ExpressionAttributeNames: { '#Transcript': 'Transcript', }, ExpressionAttributeValues: { ':Transcript': transcript, }, UpdateExpression: 'SET #Transcript = :Transcript', }); }); } else { tg = Number(body.detail.TranscriptionJobName.split('-')[0]) as PagingTalkgroup; messageBody = `Transcript for ${pagingTalkgroupConfig[tg].partyBeingPaged} page:\n\n${transcript}\n\nCurrent radio traffic: https://cofrn.org/?tg=${pagingTalkgroupConfig[tg].linkPreset}`; } // Exit early if this is transcribing an emergency transmission if (jobInfo.IsPage === 'n') { await updateFilePromise; return; } // Get recipients and send const recipients = (await getUserRecipients('all', tg)) .filter(r => r.getTranscript); const messageId = Date.now(); const insertMessage = saveMessageData( 'transcript', messageId, recipients.length, messageBody, [], jobInfo.File || null, tg ); if (jobInfo.File) { await Promise.all(recipients .map(async phone => sendMessage( 'transcript', messageId, phone.phone, await getPageNumber(phone), createPageMessage( jobInfo.File as string, tg, phone.phone, messageId, transcript ), [] ))); } else { await Promise.all(recipients .map(async number => sendMessage( 'transcript', messageId, number.phone, await getPageNumber(number), messageBody, [] ))); } await insertMessage; await updateFilePromise; } const applePrefixes = [ 'Liked', 'Loved', 'Disliked', 'Laughed at', 'Questioned', ]; const emojiRegex = / to “/; async function handleTwilioText(body: TwilioTextQueueItem) { logger.trace('handleTwilioText', ...arguments); // Pull out the phone number config const phoneNumberConfigs = await twilioPhoneNumbers(); const phoneNumberConfig = phoneNumberConfigs[body.body.To]; if (typeof phoneNumberConfig === 'undefined') { throw new Error(`Unable to find config for phone number - ${body.body.To}`); } if (typeof phoneNumberConfig.department === 'undefined') { throw new Error('Text to number not associated with any department'); } const depConfig = departmentConfig[phoneNumberConfig.department]; // Check for messages that should not be sent to the group const msgBody = body.body.Body; const doNotSend = ( msgBody.includes('I\'m Driving') && msgBody.includes('Sent from My Car') ) || applePrefixes.some(prefix => msgBody.startsWith(prefix)) || emojiRegex.test(msgBody); // Get the sending user's permissions const userPerms = getUserPermissions(body.user); // Determine if this is an announcement or not let isAnnouncement: boolean = false; let includeSender: boolean = false; if (phoneNumberConfig.type === 'page') { includeSender = true; isAnnouncement = userPerms.adminDepartments.includes(phoneNumberConfig.department); } if (!isAnnouncement && typeof depConfig.textPhone === 'undefined') { throw new Error('Tried to send group text on department where that is not available'); } // Determine if this is a test or not const isTest = !!body.user.isTest; // Get the recipients const recipients = (await getUserRecipients(phoneNumberConfig.department, null, isTest)) .filter(number => { if (doNotSend) { return false; } if (isTest) { return true; } return includeSender || number.phone !== body.user.phone; }); // Build the message const sendingUserCallsign = body.user[phoneNumberConfig.department]?.callSign || null; const sendingUserInfo = `${body.user.fName} ${body.user.lName}${sendingUserCallsign !== null ? ` (${sendingUserCallsign})` : ''}`; const messageBody = `${isAnnouncement ? `${depConfig.shortName} Announcement` : sendingUserInfo}: ${body.body.Body}${isAnnouncement ? ` - ${sendingUserInfo}` : ''}`; const mediaUrls: string[] = Object.keys(body.body) .filter(key => key.indexOf('MediaUrl') === 0) .map(key => body.body[key as keyof TwilioTextQueueItem['body']] as string); let storedMediaUrls: string[] = []; let outboundMediaUrls: string[] = []; const messageId = Date.now(); // Add auth information to the media URLs if (mediaUrls.length > 0) { const twilioConf = await getTwilioSecret(); storedMediaUrls = await Promise.all(mediaUrls // .map(url => url.replace( // /https:\/\//, // `https://${twilioConf.accountSid}:${twilioConf.authToken}@` // )) .map(async (url, idx) => { const key = `textMedia/${messageId}-${idx}`; const response = await fetch(url, { headers: { Authorization: `Basic ${Buffer .from(`${twilioConf.accountSid}:${twilioConf.authToken}`) .toString('base64')}`, }, }); await s3.send(new PutObjectCommand({ Body: await response.bytes(), Bucket: cacheBucket, Key: key, ContentType: response.headers.get('content-type') || undefined, })); return key; })); outboundMediaUrls = await Promise.all(storedMediaUrls.map(async Key => { return await getSignedUrl(s3, new GetObjectCommand({ Bucket: cacheBucket, Key, }), { expiresIn: 3600, }); })); } // Save the message data const insertMessage = saveMessageData( isAnnouncement ? 'departmentAnnounce' : 'department', messageId, recipients.length, messageBody, storedMediaUrls, null, null, phoneNumberConfig.department, isTest ); // Send the text to everyone await Promise.all(recipients .filter(number => typeof number.phone !== 'undefined') .map(async number => sendMessage( isAnnouncement ? 'departmentAnnounce' : 'department', messageId, number.phone, isAnnouncement ? await getPageNumber(number) : depConfig.textPhone || depConfig.pagePhone, messageBody, outboundMediaUrls ))); await insertMessage; } async function handlePhoneIssue(body: PhoneNumberIssueQueueItem) { logger.trace('handlePhoneIssue', ...arguments); const recipients = (await getUserRecipients('all', null)) .filter(u => { if (u.phone === body.number) { return false; } for (let i = 0; i < body.department.length; i++) { const dep = body.department[i]; if (u[dep]?.admin && u[dep].active) { return true; } } return false; }); const message = `Text delivery issue for ${body.name} (number ${formatPhone(body.number)})\n\nLast ${body.count} messages have not been delivered.`; const messageId = Date.now(); const insertMessage = saveMessageData( 'departmentAlert', messageId, recipients.length, message, [], null, null, body.department[0] ); await Promise.all(recipients.map(async user => sendMessage( 'departmentAlert', messageId, user.phone, await getPageNumber(user), message, [] ))); await insertMessage; } async function handleActivateUser(body: ActivateUserQueueItem) { logger.trace('handleActivateUser', ...arguments); const promises: Promise<unknown>[] = []; // Get the user's information const userGet = await typedGet<FullUserObject>({ TableName: TABLE_USER, Key: { phone: body.phone, }, }); if (!userGet.Item) { throw new Error(`Invalid user - ${body.phone}`); } const user = userGet.Item; const phoneCategories = await twilioPhoneCategories(); const config = departmentConfig[body.department]; const pagePhoneName: PhoneNumberTypes = config.pagePhone; if ( typeof config === 'undefined' || typeof phoneCategories[pagePhoneName] === 'undefined' ) { throw new Error(`Invalid phone config - ${config}`); } const pageTgs = (user.talkgroups || []) .map(key => pagingTalkgroupConfig[key].partyBeingPaged) .join(', '); const messagePieces: { [key in WelcomeMessageConfigKeys]: string; } = { pageNumber: formatPhone(phoneCategories[pagePhoneName].number.slice(2)), name: config.name, type: config.type, }; const groupType = config.type === 'page' ? 'page' : pageTgs.length === 0 ? 'text' : 'textPage'; const phoneType = config.type === 'page' ? 'page' : 'text'; const customWelcomeMessage = ( `${welcomeMessageParts.welcome}\n\n` + `${welcomeMessageParts[`${groupType}Group`]}\n\n` + (pageTgs.length > 0 ? `You will receive pages for: ${pageTgs}\n\n` : '') + `${welcomeMessageParts.howToLeave}` ) .replace(/\{\{([^\}]+)\}\}/g, (a: string, b: WelcomeMessageConfigKeys) => messagePieces[b]); promises.push(sendMessage( 'account', null, body.phone, config[`${phoneType}Phone`] || config.pagePhone, customWelcomeMessage, [] )); // Send a message to the admins promises.push(typedScan<FullUserObject>({ TableName: TABLE_USER, ExpressionAttributeNames: { '#admin': 'admin', '#department': body.department, '#isDistrictAdmin': 'isDistrictAdmin', }, ExpressionAttributeValues: { ':admin': true, }, FilterExpression: '#department.#admin = :admin OR #isDistrictAdmin = :admin', }) .then(admins => { const adminsToSendTo = admins.Items || []; if (adminsToSendTo.length === 0) { return; } const adminMessageId = Date.now(); const adminMessageBody = `New subscriber: ${user.fName} ${user.lName} (${formatPhone(body.phone)}) has been added to the ${body.department} group`; return Promise.all([ saveMessageData( 'departmentAlert', adminMessageId, adminsToSendTo.length, adminMessageBody, [], null, null, body.department ), ...adminsToSendTo.map(async item => sendMessage( 'departmentAlert', adminMessageId, item.phone, groupType === 'page' ? await getPageNumber(item) : config.textPhone || config.pagePhone, adminMessageBody )), ]); })); // Send a sample page if (user.talkgroups && user.talkgroups.length > 0) { promises.push(typedQuery<FullFileObject>({ TableName: TABLE_FILE, IndexName: 'ToneIndex', ExpressionAttributeValues: { ':ToneIndex': 'y', ':Talkgroup': user.talkgroups[0], }, ExpressionAttributeNames: { '#ToneIndex': 'ToneIndex', '#Talkgroup': 'Talkgroup', }, KeyConditionExpression: '#ToneIndex = :ToneIndex', FilterExpression: '#Talkgroup = :Talkgroup', ScanIndexForward: false, }) .then(data => { if (!data.Items || data.Items.length === 0) { return; } const pageKey = data.Items[0].Key?.split('/').pop() || 'none'; const pageTg = data.Items[0].Talkgroup as PagingTalkgroup; return sendMessage( 'account', null, body.phone, config.pagePhone, createPageMessage(pageKey, pageTg), [] ); })); } return await Promise.all(promises); } async function handleSiteStatus(body: SiteStatusQueueItem) { const sites = body.sites; await Promise.all(Object.keys(sites).map(async siteId => { const site = sites[siteId]; const systemShortNames: string[] = []; const updateConfig: TypedUpdateInput<FullSiteObject> = { TableName: TABLE_SITE, Key: { SiteId: siteId, }, ExpressionAttributeNames: { '#IsActive': 'IsActive', }, ExpressionAttributeValues: { ':IsActive': 'y', }, UpdateExpression: '', }; const updateStrings: string[] = [ '#IsActive = :IsActive', ]; (Object.keys(site) as (keyof typeof site)[]).forEach(key => { if (typeof site[key] === 'string') { return; } updateConfig.ExpressionAttributeNames[`#${key}`] = key as any; // eslint-disable-line @typescript-eslint/no-explicit-any Object.keys(site[key]).forEach(shortName => { if (!systemShortNames.includes(shortName)) { updateConfig.ExpressionAttributeNames[`#sys${systemShortNames.length}`] = shortName; systemShortNames.push(shortName); } const sysIndex = systemShortNames.indexOf(shortName); const value = site[key][shortName]; updateConfig.ExpressionAttributeValues = updateConfig.ExpressionAttributeValues || {}; updateConfig.ExpressionAttributeValues[`:${key}${sysIndex}`] = value; updateStrings.push(`#${key}.#sys${sysIndex} = :${key}${sysIndex}`); }); }); updateConfig.UpdateExpression = `SET ${updateStrings.join(', ')}`; await typedUpdate<FullSiteObject>(updateConfig); })); } async function handleAuthCode(body: SendUserAuthCodeQueueItem) { logger.trace('handleAuthCode', ...arguments); const code = randomString(6, true); const codeTimeout = Date.now() + codeTtl; const updateResult = await typedUpdate<FullUserObject>({ TableName: TABLE_USER, Key: { phone: body.phone, }, ExpressionAttributeNames: { '#code': 'code', '#codeExpiry': 'codeExpiry', }, ExpressionAttributeValues: { ':code': code, ':codeExpiry': codeTimeout, }, UpdateExpression: 'SET #code = :code, #codeExpiry = :codeExpiry', ReturnValues: 'ALL_NEW', }); if (!updateResult.Attributes) { throw new Error('Failed to add login code to user'); } await sendMessage( 'account', null, body.phone, await getPageNumber(updateResult.Attributes as FullUserObject), `This message was only sent to you. Your login code is ${code}. This code expires in 5 minutes.`, [] ); } async function handlePage(body: SendPageQueueItem) { logger.trace('handlePage'); // Build the message body const pageInitTime = new Date(); const messageBody = createPageMessage(body.key, body.tg); const recipients = (await getUserRecipients('all', body.tg, !!body.isTest)) .filter(v => !v.getTranscriptOnly); body.len = body.len || 0; // Increment the metrics looking at twilio health let metricPromise: Promise<unknown> = new Promise(res => res(null)); const pageTime = fNameToDate(body.key); const lenMs = body.len * 1000; if (!body.isTest) { metricPromise = cloudWatch.send(new PutMetricDataCommand({ Namespace: 'Twilio Health', MetricData: [ { MetricName: 'PageDuration', Timestamp: pageTime, Unit: 'Milliseconds', Value: lenMs, }, { MetricName: 'PageToQueue', Timestamp: pageTime, Unit: 'Milliseconds', Value: pageInitTime.getTime() - pageTime.getTime() - lenMs, }, ], })); } // Save the message data const messageId = Date.now(); const insertMessagePromise = saveMessageData( 'page', messageId, recipients.length, messageBody, [], body.key, body.tg, null, !!body.isTest ); // Send the messages await Promise.all(recipients .map(async phone => sendMessage( 'page', messageId, phone.phone, await getPageNumber(phone), createPageMessage(body.key, body.tg, phone.phone, messageId) ))); await insertMessagePromise; await metricPromise; } async function parseRecord(event: lambda.SQSRecord) { logger.debug('parseRecord', ...arguments); const body = JSON.parse(event.body); if (typeof body.action === 'undefined' && typeof body['detail-type'] !== 'undefined') { body.action = 'transcribe'; } let response; switch (body.action) { // v2 functions case 'transcribe': response = await handleTranscribe(body); break; case 'twilio-text': response = await handleTwilioText(body); break; case 'phone-issue': response = await handlePhoneIssue(body); break; case 'activate-user': response = await handleActivateUser(body); break; case 'site-status': response = await handleSiteStatus(body); break; case 'auth-code': response = await handleAuthCode(body); break; case 'page': response = await handlePage(body); break; default: throw new Error(`Unkown body - ${JSON.stringify(body)}`); } return response; } export async function main(event: lambda.SQSEvent) { logger.trace('main', ...arguments); await Promise.all(event.Records.map(parseRecord)); } |