All files / utils/backend texts.ts

95.81% Statements 229/239
85.71% Branches 42/49
100% Functions 5/5
95.81% Lines 229/239

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 3041x     1x   1x                           1x     1x 1x   1x   1x 1x   8x 8x 8x 8x 8x 8x     8x 8x 8x 8x 8x 3x 3x   3x 3x 3x 3x 8x 3x   3x 3x 3x 3x 3x 3x 3x 3x     8x 2x 2x   2x 2x 2x 2x     8x 5x 5x   8x 8x 8x 1x 1x 1x 1x   8x 8x   1x 1x 1x 1x 1x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 6x 1x 1x 1x 1x 6x 1x 1x 1x 1x 6x 1x 1x 1x 1x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x   7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     7x 7x 1x 1x 6x   6x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     6x 7x       6x 7x 7x 7x 7x 6x 6x 7x         6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   2x 2x 2x 2x 2x   2x 2x 2x 2x       2x 2x 2x 4x 4x 4x 4x 4x 2x 2x 2x   1x 5x   5x     5x     5x 1x 1x 1x   1x     4x 4x 2x 1x 5x 1x 1x             3x 3x  
import {
  CloudWatchClient, PutMetricDataCommand
} from '@aws-sdk/client-cloudwatch';
import twilio from 'twilio';
 
import {
  getTwilioSecret, twilioPhoneCategories
} from '@/deprecated/utils/general';
import {
  FullTextObject, TextTypes
} from '@/types/api/texts';
import {
  FullUserObject, PagingTalkgroup, UserDepartment
} from '@/types/api/users';
import { AlertCategory } from '@/types/backend/alerts';
import { PhoneNumberTypes } from '@/types/backend/department';
import {
  TypedScanInput, TypedUpdateInput
} from '@/types/backend/dynamo';
import {
  TABLE_TEXT, TABLE_USER, typedScan, typedUpdate
} from '@/utils/backend/dynamoTyped';
import { getLogger } from '@/utils/common/logger';
import { getUserPermissions } from '@/utils/common/user';
 
const logger = getLogger('stack/resources/utils/texts');
 
const cloudWatch = new CloudWatchClient();
const testUser = Number(process.env.TESTING_USER);
 
export async function getUserRecipients(
  department: UserDepartment | 'all',
  pageTg: PagingTalkgroup | null,
  isTest: boolean = false
): Promise<FullUserObject[]> {
  logger.trace('getUserRecipients', ...arguments);
 
  // Build out the scanning information
  const scanInput: TypedScanInput<FullUserObject> = {
    TableName: TABLE_USER,
  };
  const filterExpressions: string[] = [];
  if (pageTg !== null) {
    scanInput.ExpressionAttributeNames = scanInput.ExpressionAttributeNames || {};
    scanInput.ExpressionAttributeValues = scanInput.ExpressionAttributeValues || {};
 
    filterExpressions.push('contains(#talkgroups, :talkgroup)');
    scanInput.ExpressionAttributeNames['#talkgroups'] = 'talkgroups';
    scanInput.ExpressionAttributeValues[':talkgroup'] = pageTg;
  }
  if (department !== 'all') {
    scanInput.ExpressionAttributeValues = scanInput.ExpressionAttributeValues || {};
 
    filterExpressions.push(`#${department}.#active = :active`);
    scanInput.ExpressionAttributeNames = {
      ...scanInput.ExpressionAttributeNames || {},
      [`#${department}`]: department,
      '#active': 'active',
    };
    scanInput.ExpressionAttributeValues[':active'] = true;
  }
 
  // Handle test pages/notifications/etc
  if (isTest) {
    scanInput.ExpressionAttributeNames = scanInput.ExpressionAttributeNames || {};
    scanInput.ExpressionAttributeValues = scanInput.ExpressionAttributeValues || {};
 
    filterExpressions.push('#isTest = :isTest');
    scanInput.ExpressionAttributeNames['#isTest'] = 'isTest';
    scanInput.ExpressionAttributeValues[':isTest'] = true;
  }
 
  // Add the filter expressions to the query
  if (filterExpressions.length > 0) {
    scanInput.FilterExpression = filterExpressions.join(' AND ');
  }
 
  const result = await typedScan(scanInput);
  const users = result.Items || [];
  if (isTest && !users.some(u => u.phone === testUser)) {
    users.push({
      phone: testUser,
    });
  }
 
  return users;
}
 
const messageTypesThatRequireDepartment: TextTypes[] = [
  'department',
  'departmentAnnounce',
  'departmentAlert',
];
 
export async function saveMessageData(
  messageType: TextTypes,
  messageId: number,
  recipients: number,
  body: string,
  mediaUrls: string[] = [],
  pageId: string | null = null,
  pageTg: PagingTalkgroup | null = null,
  department: UserDepartment | null = null,
  isTest: boolean = false
) {
  logger.trace('saveMessageData', ...arguments);
  if (messageTypesThatRequireDepartment.includes(messageType) && department === null) {
    department = 'PageOnly';
  }
  const promises: Promise<unknown>[] = [];
 
  // Build the insert/update statement
  const updateItem: TypedUpdateInput<FullTextObject> & Required<Pick<TypedUpdateInput<FullTextObject>, 'ExpressionAttributeValues'>> = {
    TableName: TABLE_TEXT,
    Key: {
      datetime: messageId,
    },
    ExpressionAttributeNames: {
      '#recipients': 'recipients',
      '#body': 'body',
      '#testPageIndex': 'testPageIndex',
      '#isPage': 'isPage',
      '#isTest': 'isTest',
      '#type': 'type',
    },
    ExpressionAttributeValues: {
      ':recipients': recipients,
      ':body': body,
      ':isPage': pageId !== null,
      ':isTest': isTest,
      ':testPageIndex': `${isTest ? 'y' : 'n'}${pageId !== null ? 'y' : 'n'}`,
      ':type': messageType,
    },
  };
  const updateExpressions: string[] = [
    '#recipients = :recipients',
    '#body = :body',
    '#isPage = :isPage',
    '#isTest = :isTest',
    '#testPageIndex = :testPageIndex',
    '#type = :type',
  ];
  if (department !== null) {
    updateItem.ExpressionAttributeNames['#department'] = 'department';
    updateItem.ExpressionAttributeValues[':department'] = department;
    updateExpressions.push('#department = :department');
  }
  if (pageTg !== null) {
    updateItem.ExpressionAttributeNames['#talkgroup'] = 'talkgroup';
    updateItem.ExpressionAttributeValues[':talkgroup'] = pageTg;
    updateExpressions.push('#talkgroup = :talkgroup');
  }
  if (pageId !== null) {
    updateItem.ExpressionAttributeNames['#pageId'] = 'pageId';
    updateItem.ExpressionAttributeValues[':pageId'] = pageId;
    updateExpressions.push('#pageId = :pageId');
  }
  if (mediaUrls.length > 0) {
    updateItem.ExpressionAttributeNames['#mediaUrls'] = 'mediaUrls';
    updateItem.ExpressionAttributeValues[':mediaUrls'] = mediaUrls;
    updateExpressions.push('#mediaUrls = :mediaUrls');
  }
  updateItem.UpdateExpression = `SET ${updateExpressions.join(', ')}`;
  promises.push(typedUpdate<FullTextObject>(updateItem));
 
  // Add the metric data
  const dataDate = new Date(messageId);
  promises.push(cloudWatch.send(new PutMetricDataCommand({
    Namespace: 'Twilio Health',
    MetricData: [ {
      MetricName: 'Initiated',
      Timestamp: dataDate,
      Unit: 'Count',
      Value: recipients,
    }, ],
  }))
    .catch(e => logger.error('Error pushing metrics in saveMessageData', e)));
 
  await Promise.all(promises);
}
 
export async function sendMessage(
  messageType: TextTypes,
  messageId: number | null,
  phone: number,
  sendNumberCategory: PhoneNumberTypes,
  body: string,
  mediaUrls: string[] = [],
  isTest: boolean = false
) {
  logger.trace('sendMessage', ...arguments);
 
  // Make sure the number is valid
  const phoneCategories = await twilioPhoneCategories();
  if (typeof phoneCategories[sendNumberCategory] === 'undefined') {
    throw new Error(`Invalid phone number category - ${sendNumberCategory}`);
  }
  const numberConfig = phoneCategories[sendNumberCategory];
 
  let saveMessageDataPromise: Promise<unknown> = new Promise(res => res(null));
  if (messageId === null) {
    messageId = Date.now();
    saveMessageDataPromise = saveMessageData(
      messageType,
      messageId,
      1,
      body,
      mediaUrls,
      null,
      null,
      null,
      isTest
    );
  }
 
  // Get the twilio configuration
  const twilioConf = await getTwilioSecret();
  if (twilioConf === null) {
    throw new Error('Unable to get twilio secret');
  }
 
  const fromNumber = numberConfig.number;
  const accountSid = twilioConf[`accountSid${numberConfig.account || ''}`];
  const authToken = twilioConf[`authToken${numberConfig.account || ''}`];
  if (
    typeof fromNumber === 'undefined' ||
    typeof accountSid === 'undefined' ||
    typeof authToken === 'undefined'
  ) {
    logger.error(`Invalid phone information - ${sendNumberCategory}`, fromNumber, accountSid, authToken);
    throw new Error(`Invalid phone information - ${sendNumberCategory}`);
  }
 
  return Promise.all([
    twilio(accountSid, authToken)
      .messages.create({
        body,
        mediaUrl: mediaUrls,
        from: fromNumber,
        to: `+1${phone}`,
        statusCallback: `https://cofrn.org/api/v2/twilio/${messageId}/`,
      }),
    saveMessageDataPromise,
  ]);
}
 
export async function sendAlertMessage(
  alertType: AlertCategory,
  body: string
) {
  logger.trace('sendAlertMessage', ...arguments);
 
  const messageId = Date.now();
  const recipients = (await getUserRecipients('all', null))
    .filter(user => user[`get${alertType}Alerts`]);
  if (recipients.length === 0) {
    throw new Error(`No recipients found for ${alertType} alert`);
  }
 
  await Promise.all([
    saveMessageData('alert', messageId, recipients.length, body),
    ...recipients.map(user => sendMessage(
      'alert',
      messageId,
      user.phone,
      'alert',
      body
    )),
  ]);
}
 
const DEFAULT_PAGE_NUMBER = 'page';
export async function getPageNumber(user: FullUserObject): Promise<PhoneNumberTypes> {
  // Get the active departments for the user
  const possibleDepartments = getUserPermissions(user).activeDepartments;
 
  // Get the twilio phone information
  const phoneCategories = await twilioPhoneCategories();
 
  // If there is only one department, use that department's number
  if (possibleDepartments.length === 1) {
    const phoneName: `page${UserDepartment}` = `page${possibleDepartments[0]}`;
    return phoneName in phoneCategories
      ? phoneName as PhoneNumberTypes
      : DEFAULT_PAGE_NUMBER;
  }
 
  // Check for an explicitly set paging number
  if (
    typeof user.pagingPhone !== 'undefined' &&
    possibleDepartments.includes(user.pagingPhone) &&
    `page${user.pagingPhone}` in phoneCategories
  ) {
    return `page${user.pagingPhone}`;
  }
 
  /*
   * Use the global paging number if the user is:
   * - a member of multiple departments without a paging number set
   * - a member no departments
   */
  return DEFAULT_PAGE_NUMBER;
}