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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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 dial out is currently enabled.
  404. */
  405. export function isSipInviteEnabled(state: IReduxState): boolean {
  406. const { sipInviteUrl } = state['features/base/config'];
  407. return isJwtFeatureEnabled(state, 'sip-outbound-call') && Boolean(sipInviteUrl);
  408. }
  409. /**
  410. * Checks whether a string looks like it could be for a phone number.
  411. *
  412. * @param {string} text - The text to check whether or not it could be a phone
  413. * number.
  414. * @private
  415. * @returns {boolean} True if the string looks like it could be a phone number.
  416. */
  417. function isMaybeAPhoneNumber(text: string): boolean {
  418. if (!isPhoneNumberRegex().test(text)) {
  419. return false;
  420. }
  421. const digits = getDigitsOnly(text);
  422. return Boolean(digits.length);
  423. }
  424. /**
  425. * Checks whether a string matches a sip address format.
  426. *
  427. * @param {string} text - The text to check.
  428. * @returns {boolean} True if provided text matches a sip address format.
  429. */
  430. function isASipAddress(text: string): boolean {
  431. return SIP_ADDRESS_REGEX.test(text);
  432. }
  433. /**
  434. * RegExp to use to determine if some text might be a phone number.
  435. *
  436. * @returns {RegExp}
  437. */
  438. function isPhoneNumberRegex(): RegExp {
  439. let regexString = '^[0-9+()-\\s]*$';
  440. if (typeof interfaceConfig !== 'undefined') {
  441. regexString = interfaceConfig.PHONE_NUMBER_REGEX || regexString;
  442. }
  443. return new RegExp(regexString);
  444. }
  445. /**
  446. * Sends an ajax request to a directory service.
  447. *
  448. * @param {string} serviceUrl - The service to query.
  449. * @param {string} jwt - The jwt token to pass to the search service.
  450. * @param {string} text - Text to search.
  451. * @param {Array<string>} queryTypes - Array with the query types that will be
  452. * executed - "conferenceRooms" | "user" | "room".
  453. * @returns {Promise} - The promise created by the request.
  454. */
  455. export function searchDirectory( // eslint-disable-line max-params
  456. serviceUrl: string,
  457. jwt: string,
  458. text: string,
  459. queryTypes: Array<string> = [ 'conferenceRooms', 'user', 'room' ]
  460. ): Promise<Array<{ type: string; }>> {
  461. const query = encodeURIComponent(text);
  462. const queryTypesString = encodeURIComponent(JSON.stringify(queryTypes));
  463. return fetch(`${serviceUrl}?query=${query}&queryTypes=${
  464. queryTypesString}&jwt=${jwt}`)
  465. .then(response => {
  466. const jsonify = response.json();
  467. if (response.ok) {
  468. return jsonify;
  469. }
  470. return jsonify
  471. .then(result => Promise.reject(result));
  472. })
  473. .catch(error => {
  474. logger.error(
  475. 'Error searching directory:', error);
  476. return Promise.reject(error);
  477. });
  478. }
  479. /**
  480. * Returns descriptive text that can be used to invite participants to a meeting
  481. * (share via mobile or use it for calendar event description).
  482. *
  483. * @param {IReduxState} state - The current state.
  484. * @param {string} inviteUrl - The conference/location URL.
  485. * @param {boolean} useHtml - Whether to return html text.
  486. * @returns {Promise<string>} A {@code Promise} resolving with a
  487. * descriptive text that can be used to invite participants to a meeting.
  488. */
  489. export function getShareInfoText(state: IReduxState, inviteUrl: string, useHtml?: boolean): Promise<string> {
  490. let roomUrl = _decodeRoomURI(inviteUrl);
  491. const includeDialInfo = state['features/base/config'] !== undefined;
  492. if (useHtml) {
  493. roomUrl = `<a href="${roomUrl}">${roomUrl}</a>`;
  494. }
  495. let infoText = i18next.t('share.mainText', { roomUrl });
  496. if (includeDialInfo) {
  497. const { room } = parseURIString(inviteUrl);
  498. let numbersPromise;
  499. let hasPaymentError = false;
  500. if (state['features/invite'].numbers
  501. && state['features/invite'].conferenceID) {
  502. numbersPromise = Promise.resolve(state['features/invite']);
  503. } else {
  504. // we are requesting numbers and conferenceId directly
  505. // not using updateDialInNumbers, because custom room
  506. // is specified and we do not want to store the data
  507. // in the state
  508. const { dialInConfCodeUrl, dialInNumbersUrl, hosts }
  509. = state['features/base/config'];
  510. const { locationURL = {} } = state['features/base/connection'];
  511. const mucURL = hosts?.muc;
  512. if (!dialInConfCodeUrl || !dialInNumbersUrl || !mucURL) {
  513. // URLs for fetching dial in numbers not defined
  514. return Promise.resolve(infoText);
  515. }
  516. numbersPromise = Promise.all([
  517. getDialInNumbers(dialInNumbersUrl, room, mucURL), // @ts-ignore
  518. getDialInConferenceID(dialInConfCodeUrl, room, mucURL, locationURL)
  519. ]).then(([ numbers, {
  520. conference, id, message } ]) => {
  521. if (!conference || !id) {
  522. return Promise.reject(message);
  523. }
  524. return {
  525. numbers,
  526. conferenceID: id
  527. };
  528. });
  529. }
  530. return numbersPromise.then(
  531. ({ conferenceID, numbers }) => {
  532. const phoneNumber = _getDefaultPhoneNumber(numbers) || '';
  533. return `${
  534. i18next.t('info.dialInNumber')} ${
  535. phoneNumber} ${
  536. i18next.t('info.dialInConferenceID')} ${
  537. conferenceID}#\n\n`;
  538. })
  539. .catch(error => {
  540. logger.error('Error fetching numbers or conferenceID', error);
  541. hasPaymentError = error?.status === StatusCode.PaymentRequired;
  542. })
  543. .then(defaultDialInNumber => {
  544. if (hasPaymentError) {
  545. infoText += `${
  546. i18next.t('info.dialInNumber')} ${i18next.t('info.reachedLimit')} ${
  547. i18next.t('info.upgradeOptions')} ${UPGRADE_OPTIONS_TEXT}`;
  548. return infoText;
  549. }
  550. let dialInfoPageUrl = getDialInfoPageURL(state, room);
  551. if (useHtml) {
  552. dialInfoPageUrl
  553. = `<a href="${dialInfoPageUrl}">${dialInfoPageUrl}</a>`;
  554. }
  555. infoText += i18next.t('share.dialInfoText', {
  556. defaultDialInNumber,
  557. dialInfoPageUrl });
  558. return infoText;
  559. });
  560. }
  561. return Promise.resolve(infoText);
  562. }
  563. /**
  564. * Generates the URL for the static dial in info page.
  565. *
  566. * @param {IReduxState} state - The state from the Redux store.
  567. * @param {string?} roomName - The conference name. Optional name, if missing will be extracted from state.
  568. * @returns {string}
  569. */
  570. export function getDialInfoPageURL(state: IReduxState, roomName?: string) {
  571. const { didPageUrl } = state['features/dynamic-branding'];
  572. const conferenceName = roomName ?? getRoomName(state);
  573. const { locationURL } = state['features/base/connection'];
  574. const { href = '' } = locationURL ?? {};
  575. const room = _decodeRoomURI(conferenceName ?? '');
  576. const url = didPageUrl || `${href.substring(0, href.lastIndexOf('/'))}/${DIAL_IN_INFO_PAGE_PATH_NAME}`;
  577. return appendURLParam(url, 'room', room);
  578. }
  579. /**
  580. * Generates the URL for the static dial in info page.
  581. *
  582. * @param {string} uri - The conference URI string.
  583. * @returns {string}
  584. */
  585. export function getDialInfoPageURLForURIString(
  586. uri?: string) {
  587. if (!uri) {
  588. return undefined;
  589. }
  590. const { protocol, host, contextRoot, room } = parseURIString(uri);
  591. let url = `${protocol}//${host}${contextRoot}${DIAL_IN_INFO_PAGE_PATH_NAME}`;
  592. url = appendURLParam(url, 'room', room);
  593. const { release } = parseURLParams(uri, true, 'search');
  594. release && (url = appendURLParam(url, 'release', release));
  595. return url;
  596. }
  597. /**
  598. * Returns whether or not dial-in related UI should be displayed.
  599. *
  600. * @param {Object} dialIn - Dial in information.
  601. * @returns {boolean}
  602. */
  603. export function shouldDisplayDialIn(dialIn: any) {
  604. const { conferenceID, numbers, numbersEnabled } = dialIn;
  605. const phoneNumber = _getDefaultPhoneNumber(numbers);
  606. return Boolean(
  607. conferenceID
  608. && numbers
  609. && numbersEnabled
  610. && phoneNumber);
  611. }
  612. /**
  613. * Returns if multiple dial-in numbers are available.
  614. *
  615. * @param {Array<string>|Object} dialInNumbers - The array or object of
  616. * numbers to check.
  617. * @private
  618. * @returns {boolean}
  619. */
  620. export function hasMultipleNumbers(dialInNumbers?: { numbers: Object; } | string[]) {
  621. if (!dialInNumbers) {
  622. return false;
  623. }
  624. if (Array.isArray(dialInNumbers)) {
  625. return dialInNumbers.length > 1;
  626. }
  627. // deprecated and will be removed
  628. const { numbers } = dialInNumbers;
  629. // eslint-disable-next-line no-confusing-arrow
  630. return Boolean(numbers && Object.values(numbers).map(a => Array.isArray(a) ? a.length : 0)
  631. .reduce((a, b) => a + b) > 1);
  632. }
  633. /**
  634. * Sets the internal state of which dial-in number to display.
  635. *
  636. * @param {Array<string>|Object} dialInNumbers - The array or object of
  637. * numbers to choose a number from.
  638. * @private
  639. * @returns {string|null}
  640. */
  641. export function _getDefaultPhoneNumber(
  642. dialInNumbers?: { numbers: any; } | Array<{ default: string; formattedNumber: string; }>): string | null {
  643. if (!dialInNumbers) {
  644. return null;
  645. }
  646. if (Array.isArray(dialInNumbers)) {
  647. // new syntax follows
  648. // find the default country inside dialInNumbers, US one
  649. // or return the first one
  650. const defaultNumber = dialInNumbers.find(number => number.default);
  651. if (defaultNumber) {
  652. return defaultNumber.formattedNumber;
  653. }
  654. return dialInNumbers.length > 0
  655. ? dialInNumbers[0].formattedNumber : null;
  656. }
  657. const { numbers } = dialInNumbers;
  658. if (numbers && Object.keys(numbers).length > 0) {
  659. // deprecated and will be removed
  660. const firstRegion = Object.keys(numbers)[0];
  661. return firstRegion && numbers[firstRegion][0];
  662. }
  663. return null;
  664. }
  665. /**
  666. * Decodes URI only if doesn't contain a space(' ').
  667. *
  668. * @param {string} url - The string to decode.
  669. * @returns {string} - It the string contains space, encoded value is '%20' returns
  670. * same string, otherwise decoded one.
  671. * @private
  672. */
  673. export function _decodeRoomURI(url: string) {
  674. let roomUrl = url;
  675. // we want to decode urls when the do not contain space, ' ', which url encoded is %20
  676. if (roomUrl && !roomUrl.includes('%20')) {
  677. roomUrl = decodeURI(roomUrl);
  678. }
  679. // Handles a special case where the room name has % encoded, the decoded will have
  680. // % followed by a char (non-digit) which is not a valid URL and room name ... so we do not
  681. // want to show this decoded
  682. if (roomUrl.match(/.*%[^\d].*/)) {
  683. return url;
  684. }
  685. return roomUrl;
  686. }
  687. /**
  688. * Returns the stored conference id.
  689. *
  690. * @param {IStateful} stateful - The Object or Function that can be
  691. * resolved to a Redux state object with the toState function.
  692. * @returns {string}
  693. */
  694. export function getConferenceId(stateful: IStateful) {
  695. return toState(stateful)['features/invite'].conferenceID;
  696. }
  697. /**
  698. * Returns the default dial in number from the store.
  699. *
  700. * @param {IStateful} stateful - The Object or Function that can be
  701. * resolved to a Redux state object with the toState function.
  702. * @returns {string | null}
  703. */
  704. export function getDefaultDialInNumber(stateful: IStateful) {
  705. // @ts-ignore
  706. return _getDefaultPhoneNumber(toState(stateful)['features/invite'].numbers);
  707. }
  708. /**
  709. * Executes the dial out request.
  710. *
  711. * @param {string} url - The url for dialing out.
  712. * @param {Object} body - The body of the request.
  713. * @param {string} reqId - The unique request id.
  714. * @returns {Object}
  715. */
  716. export async function executeDialOutRequest(url: string, body: Object, reqId: string) {
  717. const res = await fetch(url, {
  718. method: 'POST',
  719. headers: {
  720. 'Content-Type': 'application/json',
  721. 'request-id': reqId
  722. },
  723. body: JSON.stringify(body)
  724. });
  725. const json = await res.json();
  726. return res.ok ? json : Promise.reject(json);
  727. }
  728. /**
  729. * Executes the dial out status request.
  730. *
  731. * @param {string} url - The url for dialing out.
  732. * @param {string} reqId - The unique request id used on the dial out request.
  733. * @returns {Object}
  734. */
  735. export async function executeDialOutStatusRequest(url: string, reqId: string) {
  736. const res = await fetch(url, {
  737. method: 'GET',
  738. headers: {
  739. 'Content-Type': 'application/json',
  740. 'request-id': reqId
  741. }
  742. });
  743. const json = await res.json();
  744. return res.ok ? json : Promise.reject(json);
  745. }
  746. /**
  747. * Returns true if a specific sharing feature is enabled in interface configuration.
  748. *
  749. * @param {string} sharingFeature - The sharing feature to check.
  750. * @returns {boolean}
  751. */
  752. export function isSharingEnabled(sharingFeature: string) {
  753. return typeof interfaceConfig === 'undefined'
  754. || typeof interfaceConfig.SHARING_FEATURES === 'undefined'
  755. || (interfaceConfig.SHARING_FEATURES.length && interfaceConfig.SHARING_FEATURES.indexOf(sharingFeature) > -1);
  756. }
  757. /**
  758. * Sends a post request to an invite service.
  759. *
  760. * @param {Array} inviteItems - The list of the "sip" type items to invite.
  761. * @param {URL} locationURL - The URL of the location.
  762. * @param {string} sipInviteUrl - The invite service that generates the invitation.
  763. * @param {string} jwt - The jwt token.
  764. * @param {string} roomName - The name to the conference.
  765. * @param {string} roomPassword - The password of the conference.
  766. * @param {string} displayName - The user display name.
  767. * @returns {Promise} - The promise created by the request.
  768. */
  769. export function inviteSipEndpoints( // eslint-disable-line max-params
  770. inviteItems: Array<{ address: string; }>,
  771. locationURL: URL,
  772. sipInviteUrl: string,
  773. jwt: string,
  774. roomName: string,
  775. roomPassword: String,
  776. displayName: string
  777. ): Promise<any> {
  778. if (inviteItems.length === 0) {
  779. return Promise.resolve();
  780. }
  781. const regex = new RegExp(`/${roomName}`, 'i');
  782. const baseUrl = Object.assign(new URL(locationURL.toString()), {
  783. pathname: locationURL.pathname.replace(regex, ''),
  784. hash: '',
  785. search: ''
  786. });
  787. return fetch(
  788. sipInviteUrl,
  789. {
  790. body: JSON.stringify({
  791. callParams: {
  792. callUrlInfo: {
  793. baseUrl,
  794. callName: roomName
  795. },
  796. passcode: roomPassword
  797. },
  798. sipClientParams: {
  799. displayName,
  800. sipAddress: inviteItems.map(item => item.address)
  801. }
  802. }),
  803. method: 'POST',
  804. headers: {
  805. 'Authorization': `Bearer ${jwt}`,
  806. 'Content-Type': 'application/json'
  807. }
  808. }
  809. );
  810. }