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.

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