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

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