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

functions.ts 27KB

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