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 26KB

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