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.ts 29KB

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