Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

functions.ts 29KB

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