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

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