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

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