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

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