You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

functions.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. // @flow
  2. import { i18next } from '../base/i18n';
  3. import { isLocalParticipantModerator } from '../base/participants';
  4. import { toState } from '../base/redux';
  5. import { doGetJSON, parseURIString } from '../base/util';
  6. import logger from './logger';
  7. declare var $: Function;
  8. declare var interfaceConfig: Object;
  9. /**
  10. * Sends an ajax request to check if the phone number can be called.
  11. *
  12. * @param {string} dialNumber - The dial number to check for validity.
  13. * @param {string} dialOutAuthUrl - The endpoint to use for checking validity.
  14. * @returns {Promise} - The promise created by the request.
  15. */
  16. export function checkDialNumber(
  17. dialNumber: string,
  18. dialOutAuthUrl: string
  19. ): Promise<Object> {
  20. const fullUrl = `${dialOutAuthUrl}?phone=${dialNumber}`;
  21. return new Promise((resolve, reject) => {
  22. $.getJSON(fullUrl)
  23. .then(resolve)
  24. .catch(reject);
  25. });
  26. }
  27. /**
  28. * Sends a GET request to obtain the conference ID necessary for identifying
  29. * which conference to join after diaing the dial-in service.
  30. *
  31. * @param {string} baseUrl - The url for obtaining the conference ID (pin) for
  32. * dialing into a conference.
  33. * @param {string} roomName - The conference name to find the associated
  34. * conference ID.
  35. * @param {string} mucURL - In which MUC the conference exists.
  36. * @returns {Promise} - The promise created by the request.
  37. */
  38. export function getDialInConferenceID(
  39. baseUrl: string,
  40. roomName: string,
  41. mucURL: string
  42. ): Promise<Object> {
  43. const conferenceIDURL = `${baseUrl}?conference=${roomName}@${mucURL}`;
  44. return doGetJSON(conferenceIDURL, true);
  45. }
  46. /**
  47. * Sends a GET request for phone numbers used to dial into a conference.
  48. *
  49. * @param {string} url - The service that returns conference dial-in numbers.
  50. * @param {string} roomName - The conference name to find the associated
  51. * conference ID.
  52. * @param {string} mucURL - In which MUC the conference exists.
  53. * @returns {Promise} - The promise created by the request. The returned numbers
  54. * may be an array of Objects containing numbers, with keys countryCode,
  55. * tollFree, formattedNumber or an object with countries as keys and arrays of
  56. * phone number strings, as the second one should not be used and is deprecated.
  57. */
  58. export function getDialInNumbers(
  59. url: string,
  60. roomName: string,
  61. mucURL: string
  62. ): Promise<*> {
  63. const fullUrl = `${url}?conference=${roomName}@${mucURL}`;
  64. return doGetJSON(fullUrl, true);
  65. }
  66. /**
  67. * Removes all non-numeric characters from a string.
  68. *
  69. * @param {string} text - The string from which to remove all characters except
  70. * numbers.
  71. * @returns {string} A string with only numbers.
  72. */
  73. export function getDigitsOnly(text: string = ''): string {
  74. return text.replace(/\D/g, '');
  75. }
  76. /**
  77. * Type of the options to use when sending a search query.
  78. */
  79. export type GetInviteResultsOptions = {
  80. /**
  81. * The endpoint to use for checking phone number validity.
  82. */
  83. dialOutAuthUrl: string,
  84. /**
  85. * Whether or not to search for people.
  86. */
  87. addPeopleEnabled: boolean,
  88. /**
  89. * Whether or not to check phone numbers.
  90. */
  91. dialOutEnabled: boolean,
  92. /**
  93. * Array with the query types that will be executed -
  94. * "conferenceRooms" | "user" | "room".
  95. */
  96. peopleSearchQueryTypes: Array<string>,
  97. /**
  98. * The url to query for people.
  99. */
  100. peopleSearchUrl: string,
  101. /**
  102. * The jwt token to pass to the search service.
  103. */
  104. jwt: string
  105. };
  106. /**
  107. * Combines directory search with phone number validation to produce a single
  108. * set of invite search results.
  109. *
  110. * @param {string} query - Text to search.
  111. * @param {GetInviteResultsOptions} options - Options to use when searching.
  112. * @returns {Promise<*>}
  113. */
  114. export function getInviteResultsForQuery(
  115. query: string,
  116. options: GetInviteResultsOptions
  117. ): Promise<*> {
  118. const text = query.trim();
  119. const {
  120. dialOutAuthUrl,
  121. addPeopleEnabled,
  122. dialOutEnabled,
  123. peopleSearchQueryTypes,
  124. peopleSearchUrl,
  125. jwt
  126. } = options;
  127. let peopleSearchPromise;
  128. if (addPeopleEnabled && text) {
  129. peopleSearchPromise = searchDirectory(
  130. peopleSearchUrl,
  131. jwt,
  132. text,
  133. peopleSearchQueryTypes);
  134. } else {
  135. peopleSearchPromise = Promise.resolve([]);
  136. }
  137. let hasCountryCode = text.startsWith('+');
  138. let phoneNumberPromise;
  139. // Phone numbers are handled a specially to enable both cases of restricting
  140. // numbers to telephone number-y numbers and accepting any arbitrary string,
  141. // which may be valid for SIP (jigasi) calls. If the dialOutAuthUrl is
  142. // defined, then it is assumed the call is to a telephone number and
  143. // some validation of the number is completed, with the + sign used as a way
  144. // for the UI to detect and enforce the usage of a country code. If the
  145. // dialOutAuthUrl is not defined, accept anything because this is assumed
  146. // to be the SIP (jigasi) case.
  147. if (dialOutEnabled && dialOutAuthUrl && isMaybeAPhoneNumber(text)) {
  148. let numberToVerify = text;
  149. // When the number to verify does not start with a +, we assume no
  150. // proper country code has been entered. In such a case, prepend 1 for
  151. // the country code. The service currently takes care of prepending the
  152. // +.
  153. if (!hasCountryCode && !text.startsWith('1')) {
  154. numberToVerify = `1${numberToVerify}`;
  155. }
  156. // The validation service works properly when the query is digits only
  157. // so ensure only digits get sent.
  158. numberToVerify = getDigitsOnly(numberToVerify);
  159. phoneNumberPromise = checkDialNumber(numberToVerify, dialOutAuthUrl);
  160. } else if (dialOutEnabled && !dialOutAuthUrl) {
  161. // fake having a country code to hide the country code reminder
  162. hasCountryCode = true;
  163. // With no auth url, let's say the text is a valid number
  164. phoneNumberPromise = Promise.resolve({
  165. allow: true,
  166. country: '',
  167. phone: text
  168. });
  169. } else {
  170. phoneNumberPromise = Promise.resolve({});
  171. }
  172. return Promise.all([ peopleSearchPromise, phoneNumberPromise ])
  173. .then(([ peopleResults, phoneResults ]) => {
  174. const results = [
  175. ...peopleResults
  176. ];
  177. /**
  178. * This check for phone results is for the day the call to searching
  179. * people might return phone results as well. When that day comes
  180. * this check will make it so the server checks are honored and the
  181. * local appending of the number is not done. The local appending of
  182. * the phone number can then be cleaned up when convenient.
  183. */
  184. const hasPhoneResult
  185. = peopleResults.find(result => result.type === 'phone');
  186. if (!hasPhoneResult && typeof phoneResults.allow === 'boolean') {
  187. results.push({
  188. allowed: phoneResults.allow,
  189. country: phoneResults.country,
  190. type: 'phone',
  191. number: phoneResults.phone,
  192. originalEntry: text,
  193. showCountryCodeReminder: !hasCountryCode
  194. });
  195. }
  196. return results;
  197. });
  198. }
  199. /**
  200. * Creates a message describing how to dial in to the conference.
  201. *
  202. * @returns {string}
  203. */
  204. export function getInviteText({
  205. _conferenceName,
  206. _localParticipantName,
  207. _inviteUrl,
  208. _locationUrl,
  209. _dialIn,
  210. _liveStreamViewURL,
  211. phoneNumber,
  212. t
  213. }: Object) {
  214. const inviteURL = _decodeRoomURI(_inviteUrl);
  215. let invite = _localParticipantName
  216. ? t('info.inviteURLFirstPartPersonal', { name: _localParticipantName })
  217. : t('info.inviteURLFirstPartGeneral');
  218. invite += t('info.inviteURLSecondPart', {
  219. url: inviteURL
  220. });
  221. if (_liveStreamViewURL) {
  222. const liveStream = t('info.inviteLiveStream', {
  223. url: _liveStreamViewURL
  224. });
  225. invite = `${invite}\n${liveStream}`;
  226. }
  227. if (shouldDisplayDialIn(_dialIn)) {
  228. const dial = t('info.invitePhone', {
  229. number: phoneNumber,
  230. conferenceID: _dialIn.conferenceID
  231. });
  232. const moreNumbers = t('info.invitePhoneAlternatives', {
  233. url: getDialInfoPageURL(
  234. _conferenceName,
  235. _locationUrl
  236. ),
  237. silentUrl: `${inviteURL}#config.startSilent=true`
  238. });
  239. invite = `${invite}\n${dial}\n${moreNumbers}`;
  240. }
  241. return invite;
  242. }
  243. /**
  244. * Helper for determining how many of each type of user is being invited. Used
  245. * for logging and sending analytics related to invites.
  246. *
  247. * @param {Array} inviteItems - An array with the invite items, as created in
  248. * {@link _parseQueryResults}.
  249. * @returns {Object} An object with keys as user types and values as the number
  250. * of invites for that type.
  251. */
  252. export function getInviteTypeCounts(inviteItems: Array<Object> = []) {
  253. const inviteTypeCounts = {};
  254. inviteItems.forEach(({ type }) => {
  255. if (!inviteTypeCounts[type]) {
  256. inviteTypeCounts[type] = 0;
  257. }
  258. inviteTypeCounts[type]++;
  259. });
  260. return inviteTypeCounts;
  261. }
  262. /**
  263. * Sends a post request to an invite service.
  264. *
  265. * @param {string} inviteServiceUrl - The invite service that generates the
  266. * invitation.
  267. * @param {string} inviteUrl - The url to the conference.
  268. * @param {string} jwt - The jwt token to pass to the search service.
  269. * @param {Immutable.List} inviteItems - The list of the "user" or "room" type
  270. * items to invite.
  271. * @returns {Promise} - The promise created by the request.
  272. */
  273. export function invitePeopleAndChatRooms( // eslint-disable-line max-params
  274. inviteServiceUrl: string,
  275. inviteUrl: string,
  276. jwt: string,
  277. inviteItems: Array<Object>
  278. ): Promise<void> {
  279. if (!inviteItems || inviteItems.length === 0) {
  280. return Promise.resolve();
  281. }
  282. return fetch(
  283. `${inviteServiceUrl}?token=${jwt}`,
  284. {
  285. body: JSON.stringify({
  286. 'invited': inviteItems,
  287. 'url': inviteUrl
  288. }),
  289. method: 'POST',
  290. headers: {
  291. 'Content-Type': 'application/json'
  292. }
  293. }
  294. );
  295. }
  296. /**
  297. * Determines if adding people is currently enabled.
  298. *
  299. * @param {boolean} state - Current state.
  300. * @returns {boolean} Indication of whether adding people is currently enabled.
  301. */
  302. export function isAddPeopleEnabled(state: Object): boolean {
  303. const { peopleSearchUrl } = state['features/base/config'];
  304. return state['features/base/jwt'].jwt && Boolean(peopleSearchUrl);
  305. }
  306. /**
  307. * Determines if dial out is currently enabled or not.
  308. *
  309. * @param {boolean} state - Current state.
  310. * @returns {boolean} Indication of whether dial out is currently enabled.
  311. */
  312. export function isDialOutEnabled(state: Object): boolean {
  313. const { conference } = state['features/base/conference'];
  314. return isLocalParticipantModerator(state)
  315. && conference && conference.isSIPCallingSupported();
  316. }
  317. /**
  318. * Checks whether a string looks like it could be for a phone number.
  319. *
  320. * @param {string} text - The text to check whether or not it could be a phone
  321. * number.
  322. * @private
  323. * @returns {boolean} True if the string looks like it could be a phone number.
  324. */
  325. function isMaybeAPhoneNumber(text: string): boolean {
  326. if (!isPhoneNumberRegex().test(text)) {
  327. return false;
  328. }
  329. const digits = getDigitsOnly(text);
  330. return Boolean(digits.length);
  331. }
  332. /**
  333. * RegExp to use to determine if some text might be a phone number.
  334. *
  335. * @returns {RegExp}
  336. */
  337. function isPhoneNumberRegex(): RegExp {
  338. let regexString = '^[0-9+()-\\s]*$';
  339. if (typeof interfaceConfig !== 'undefined') {
  340. regexString = interfaceConfig.PHONE_NUMBER_REGEX || regexString;
  341. }
  342. return new RegExp(regexString);
  343. }
  344. /**
  345. * Sends an ajax request to a directory service.
  346. *
  347. * @param {string} serviceUrl - The service to query.
  348. * @param {string} jwt - The jwt token to pass to the search service.
  349. * @param {string} text - Text to search.
  350. * @param {Array<string>} queryTypes - Array with the query types that will be
  351. * executed - "conferenceRooms" | "user" | "room".
  352. * @returns {Promise} - The promise created by the request.
  353. */
  354. export function searchDirectory( // eslint-disable-line max-params
  355. serviceUrl: string,
  356. jwt: string,
  357. text: string,
  358. queryTypes: Array<string> = [ 'conferenceRooms', 'user', 'room' ]
  359. ): Promise<Array<Object>> {
  360. const query = encodeURIComponent(text);
  361. const queryTypesString = encodeURIComponent(JSON.stringify(queryTypes));
  362. return fetch(`${serviceUrl}?query=${query}&queryTypes=${
  363. queryTypesString}&jwt=${jwt}`)
  364. .then(response => {
  365. const jsonify = response.json();
  366. if (response.ok) {
  367. return jsonify;
  368. }
  369. return jsonify
  370. .then(result => Promise.reject(result));
  371. })
  372. .catch(error => {
  373. logger.error(
  374. 'Error searching directory:', error);
  375. return Promise.reject(error);
  376. });
  377. }
  378. /**
  379. * Returns descriptive text that can be used to invite participants to a meeting
  380. * (share via mobile or use it for calendar event description).
  381. *
  382. * @param {Object} state - The current state.
  383. * @param {string} inviteUrl - The conference/location URL.
  384. * @param {boolean} useHtml - Whether to return html text.
  385. * @returns {Promise<string>} A {@code Promise} resolving with a
  386. * descriptive text that can be used to invite participants to a meeting.
  387. */
  388. export function getShareInfoText(
  389. state: Object, inviteUrl: string, useHtml: ?boolean): Promise<string> {
  390. let roomUrl = _decodeRoomURI(inviteUrl);
  391. const includeDialInfo = state['features/base/config'] !== undefined;
  392. if (useHtml) {
  393. roomUrl = `<a href="${roomUrl}">${roomUrl}</a>`;
  394. }
  395. let infoText = i18next.t('share.mainText', { roomUrl });
  396. if (includeDialInfo) {
  397. const { room } = parseURIString(inviteUrl);
  398. let numbersPromise;
  399. if (state['features/invite'].numbers
  400. && state['features/invite'].conferenceID) {
  401. numbersPromise = Promise.resolve(state['features/invite']);
  402. } else {
  403. // we are requesting numbers and conferenceId directly
  404. // not using updateDialInNumbers, because custom room
  405. // is specified and we do not want to store the data
  406. // in the state
  407. const { dialInConfCodeUrl, dialInNumbersUrl, hosts }
  408. = state['features/base/config'];
  409. const mucURL = hosts && hosts.muc;
  410. if (!dialInConfCodeUrl || !dialInNumbersUrl || !mucURL) {
  411. // URLs for fetching dial in numbers not defined
  412. return Promise.resolve(infoText);
  413. }
  414. numbersPromise = Promise.all([
  415. getDialInNumbers(dialInNumbersUrl, room, mucURL),
  416. getDialInConferenceID(dialInConfCodeUrl, room, mucURL)
  417. ]).then(([ numbers, {
  418. conference, id, message } ]) => {
  419. if (!conference || !id) {
  420. return Promise.reject(message);
  421. }
  422. return {
  423. numbers,
  424. conferenceID: id
  425. };
  426. });
  427. }
  428. return numbersPromise.then(
  429. ({ conferenceID, numbers }) => {
  430. const phoneNumber = _getDefaultPhoneNumber(numbers) || '';
  431. return `${
  432. i18next.t('info.dialInNumber')} ${
  433. phoneNumber} ${
  434. i18next.t('info.dialInConferenceID')} ${
  435. conferenceID}#\n\n`;
  436. })
  437. .catch(error =>
  438. logger.error('Error fetching numbers or conferenceID', error))
  439. .then(defaultDialInNumber => {
  440. let dialInfoPageUrl = getDialInfoPageURL(
  441. room,
  442. state['features/base/connection'].locationURL);
  443. if (useHtml) {
  444. dialInfoPageUrl
  445. = `<a href="${dialInfoPageUrl}">${dialInfoPageUrl}</a>`;
  446. }
  447. infoText += i18next.t('share.dialInfoText', {
  448. defaultDialInNumber,
  449. dialInfoPageUrl });
  450. return infoText;
  451. });
  452. }
  453. return Promise.resolve(infoText);
  454. }
  455. /**
  456. * Generates the URL for the static dial in info page.
  457. *
  458. * @param {string} conferenceName - The conference name.
  459. * @param {Object} locationURL - The current location URL, the object coming
  460. * from state ['features/base/connection'].locationURL.
  461. * @returns {string}
  462. */
  463. export function getDialInfoPageURL(
  464. conferenceName: string,
  465. locationURL: Object) {
  466. const origin = locationURL.origin;
  467. const pathParts = locationURL.pathname.split('/');
  468. pathParts.length = pathParts.length - 1;
  469. const newPath = pathParts.reduce((accumulator, currentValue) => {
  470. if (currentValue) {
  471. return `${accumulator}/${currentValue}`;
  472. }
  473. return accumulator;
  474. }, '');
  475. return `${origin}${newPath}/static/dialInInfo.html?room=${_decodeRoomURI(conferenceName)}`;
  476. }
  477. /**
  478. * Generates the URL for the static dial in info page.
  479. *
  480. * @param {string} uri - The conference URI string.
  481. * @returns {string}
  482. */
  483. export function getDialInfoPageURLForURIString(
  484. uri: ?string) {
  485. if (!uri) {
  486. return undefined;
  487. }
  488. const { protocol, host, contextRoot, room } = parseURIString(uri);
  489. return `${protocol}//${host}${contextRoot}static/dialInInfo.html?room=${room}`;
  490. }
  491. /**
  492. * Returns whether or not dial-in related UI should be displayed.
  493. *
  494. * @param {Object} dialIn - Dial in information.
  495. * @returns {boolean}
  496. */
  497. export function shouldDisplayDialIn(dialIn: Object) {
  498. const { conferenceID, numbers, numbersEnabled } = dialIn;
  499. const phoneNumber = _getDefaultPhoneNumber(numbers);
  500. return Boolean(
  501. conferenceID
  502. && numbers
  503. && numbersEnabled
  504. && phoneNumber);
  505. }
  506. /**
  507. * Sets the internal state of which dial-in number to display.
  508. *
  509. * @param {Array<string>|Object} dialInNumbers - The array or object of
  510. * numbers to choose a number from.
  511. * @private
  512. * @returns {string|null}
  513. */
  514. export function _getDefaultPhoneNumber(
  515. dialInNumbers: ?Object): ?string {
  516. if (!dialInNumbers) {
  517. return null;
  518. }
  519. if (Array.isArray(dialInNumbers)) {
  520. // new syntax follows
  521. // find the default country inside dialInNumbers, US one
  522. // or return the first one
  523. const defaultNumber = dialInNumbers.find(number => number.default);
  524. if (defaultNumber) {
  525. return defaultNumber.formattedNumber;
  526. }
  527. return dialInNumbers.length > 0
  528. ? dialInNumbers[0].formattedNumber : null;
  529. }
  530. const { numbers } = dialInNumbers;
  531. if (numbers && Object.keys(numbers).length > 0) {
  532. // deprecated and will be removed
  533. const firstRegion = Object.keys(numbers)[0];
  534. return firstRegion && numbers[firstRegion][0];
  535. }
  536. return null;
  537. }
  538. /**
  539. * Decodes URI only if doesn't contain a space(' ').
  540. *
  541. * @param {string} url - The string to decode.
  542. * @returns {string} - It the string contains space, encoded value is '%20' returns
  543. * same string, otherwise decoded one.
  544. * @private
  545. */
  546. export function _decodeRoomURI(url: string) {
  547. let roomUrl = url;
  548. // we want to decode urls when the do not contain space, ' ', which url encoded is %20
  549. if (roomUrl && !roomUrl.includes('%20')) {
  550. roomUrl = decodeURI(roomUrl);
  551. }
  552. // Handles a special case where the room name has % encoded, the decoded will have
  553. // % followed by a char (non-digit) which is not a valid URL and room name ... so we do not
  554. // want to show this decoded
  555. if (roomUrl.match(/.*%[^\d].*/)) {
  556. return url;
  557. }
  558. return roomUrl;
  559. }
  560. /**
  561. * Returns the stored conference id.
  562. *
  563. * @param {Object | Function} stateful - The Object or Function that can be
  564. * resolved to a Redux state object with the toState function.
  565. * @returns {string}
  566. */
  567. export function getConferenceId(stateful: Object | Function) {
  568. return toState(stateful)['features/invite'].conferenceID;
  569. }
  570. /**
  571. * Returns the default dial in number from the store.
  572. *
  573. * @param {Object | Function} stateful - The Object or Function that can be
  574. * resolved to a Redux state object with the toState function.
  575. * @returns {string | null}
  576. */
  577. export function getDefaultDialInNumber(stateful: Object | Function) {
  578. return _getDefaultPhoneNumber(toState(stateful)['features/invite'].numbers);
  579. }
  580. /**
  581. * Executes the dial out request.
  582. *
  583. * @param {string} url - The url for dialing out.
  584. * @param {Object} body - The body of the request.
  585. * @param {string} reqId - The unique request id.
  586. * @returns {Object}
  587. */
  588. export async function executeDialOutRequest(url: string, body: Object, reqId: string) {
  589. const res = await fetch(url, {
  590. method: 'POST',
  591. headers: {
  592. 'Content-Type': 'application/json',
  593. 'request-id': reqId
  594. },
  595. body: JSON.stringify(body)
  596. });
  597. const json = await res.json();
  598. return res.ok ? json : Promise.reject(json);
  599. }
  600. /**
  601. * Executes the dial out status request.
  602. *
  603. * @param {string} url - The url for dialing out.
  604. * @param {string} reqId - The unique request id used on the dial out request.
  605. * @returns {Object}
  606. */
  607. export async function executeDialOutStatusRequest(url: string, reqId: string) {
  608. const res = await fetch(url, {
  609. method: 'GET',
  610. headers: {
  611. 'Content-Type': 'application/json',
  612. 'request-id': reqId
  613. }
  614. });
  615. const json = await res.json();
  616. return res.ok ? json : Promise.reject(json);
  617. }