Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

functions.js 26KB

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