您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

functions.js 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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 { INVITE_TYPES, 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 === INVITE_TYPES.PHONE);
  197. if (!hasPhoneResult && typeof phoneResults.allow === 'boolean') {
  198. results.push({
  199. allowed: phoneResults.allow,
  200. country: phoneResults.country,
  201. type: INVITE_TYPES.PHONE,
  202. number: phoneResults.phone,
  203. originalEntry: text,
  204. showCountryCodeReminder: !hasCountryCode
  205. });
  206. }
  207. if (sipInviteEnabled && isASipAddress(text)) {
  208. results.push({
  209. type: INVITE_TYPES.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. if (dialIn.sipUri) {
  259. const sipText = t('info.inviteSipEndpoint', {
  260. sipUri: dialIn.sipUri
  261. });
  262. invite = `${invite}\n${sipText}`;
  263. }
  264. return invite;
  265. }
  266. /**
  267. * Helper for determining how many of each type of user is being invited. Used
  268. * for logging and sending analytics related to invites.
  269. *
  270. * @param {Array} inviteItems - An array with the invite items, as created in
  271. * {@link _parseQueryResults}.
  272. * @returns {Object} An object with keys as user types and values as the number
  273. * of invites for that type.
  274. */
  275. export function getInviteTypeCounts(inviteItems: Array<Object> = []) {
  276. const inviteTypeCounts = {};
  277. inviteItems.forEach(({ type }) => {
  278. if (!inviteTypeCounts[type]) {
  279. inviteTypeCounts[type] = 0;
  280. }
  281. inviteTypeCounts[type]++;
  282. });
  283. return inviteTypeCounts;
  284. }
  285. /**
  286. * Sends a post request to an invite service.
  287. *
  288. * @param {string} inviteServiceUrl - The invite service that generates the
  289. * invitation.
  290. * @param {string} inviteUrl - The url to the conference.
  291. * @param {string} jwt - The jwt token to pass to the search service.
  292. * @param {Immutable.List} inviteItems - The list of the "user" or "room" type
  293. * items to invite.
  294. * @returns {Promise} - The promise created by the request.
  295. */
  296. export function invitePeopleAndChatRooms( // eslint-disable-line max-params
  297. inviteServiceUrl: string,
  298. inviteUrl: string,
  299. jwt: string,
  300. inviteItems: Array<Object>
  301. ): Promise<void> {
  302. if (!inviteItems || inviteItems.length === 0) {
  303. return Promise.resolve();
  304. }
  305. return fetch(
  306. `${inviteServiceUrl}?token=${jwt}`,
  307. {
  308. body: JSON.stringify({
  309. 'invited': inviteItems,
  310. 'url': inviteUrl
  311. }),
  312. method: 'POST',
  313. headers: {
  314. 'Content-Type': 'application/json'
  315. }
  316. }
  317. );
  318. }
  319. /**
  320. * Determines if adding people is currently enabled.
  321. *
  322. * @param {boolean} state - Current state.
  323. * @returns {boolean} Indication of whether adding people is currently enabled.
  324. */
  325. export function isAddPeopleEnabled(state: Object): boolean {
  326. const { peopleSearchUrl } = state['features/base/config'];
  327. return state['features/base/jwt'].jwt && Boolean(peopleSearchUrl) && !isVpaasMeeting(state);
  328. }
  329. /**
  330. * Determines if dial out is currently enabled or not.
  331. *
  332. * @param {boolean} state - Current state.
  333. * @returns {boolean} Indication of whether dial out is currently enabled.
  334. */
  335. export function isDialOutEnabled(state: Object): boolean {
  336. const { conference } = state['features/base/conference'];
  337. return isLocalParticipantModerator(state)
  338. && conference && conference.isSIPCallingSupported();
  339. }
  340. /**
  341. * Determines if inviting sip endpoints is enabled or not.
  342. *
  343. * @param {Object} state - Current state.
  344. * @returns {boolean} Indication of whether dial out is currently enabled.
  345. */
  346. export function isSipInviteEnabled(state: Object): boolean {
  347. const { sipInviteUrl } = state['features/base/config'];
  348. const { features = {} } = getLocalParticipant(state);
  349. return state['features/base/jwt'].jwt
  350. && Boolean(sipInviteUrl)
  351. && String(features['sip-outbound-call']) === 'true';
  352. }
  353. /**
  354. * Checks whether a string looks like it could be for a phone number.
  355. *
  356. * @param {string} text - The text to check whether or not it could be a phone
  357. * number.
  358. * @private
  359. * @returns {boolean} True if the string looks like it could be a phone number.
  360. */
  361. function isMaybeAPhoneNumber(text: string): boolean {
  362. if (!isPhoneNumberRegex().test(text)) {
  363. return false;
  364. }
  365. const digits = getDigitsOnly(text);
  366. return Boolean(digits.length);
  367. }
  368. /**
  369. * Checks whether a string matches a sip address format.
  370. *
  371. * @param {string} text - The text to check.
  372. * @returns {boolean} True if provided text matches a sip address format.
  373. */
  374. function isASipAddress(text: string): boolean {
  375. return SIP_ADDRESS_REGEX.test(text);
  376. }
  377. /**
  378. * RegExp to use to determine if some text might be a phone number.
  379. *
  380. * @returns {RegExp}
  381. */
  382. function isPhoneNumberRegex(): RegExp {
  383. let regexString = '^[0-9+()-\\s]*$';
  384. if (typeof interfaceConfig !== 'undefined') {
  385. regexString = interfaceConfig.PHONE_NUMBER_REGEX || regexString;
  386. }
  387. return new RegExp(regexString);
  388. }
  389. /**
  390. * Sends an ajax request to a directory service.
  391. *
  392. * @param {string} serviceUrl - The service to query.
  393. * @param {string} jwt - The jwt token to pass to the search service.
  394. * @param {string} text - Text to search.
  395. * @param {Array<string>} queryTypes - Array with the query types that will be
  396. * executed - "conferenceRooms" | "user" | "room".
  397. * @returns {Promise} - The promise created by the request.
  398. */
  399. export function searchDirectory( // eslint-disable-line max-params
  400. serviceUrl: string,
  401. jwt: string,
  402. text: string,
  403. queryTypes: Array<string> = [ 'conferenceRooms', 'user', 'room' ]
  404. ): Promise<Array<Object>> {
  405. const query = encodeURIComponent(text);
  406. const queryTypesString = encodeURIComponent(JSON.stringify(queryTypes));
  407. return fetch(`${serviceUrl}?query=${query}&queryTypes=${
  408. queryTypesString}&jwt=${jwt}`)
  409. .then(response => {
  410. const jsonify = response.json();
  411. if (response.ok) {
  412. return jsonify;
  413. }
  414. return jsonify
  415. .then(result => Promise.reject(result));
  416. })
  417. .catch(error => {
  418. logger.error(
  419. 'Error searching directory:', error);
  420. return Promise.reject(error);
  421. });
  422. }
  423. /**
  424. * Returns descriptive text that can be used to invite participants to a meeting
  425. * (share via mobile or use it for calendar event description).
  426. *
  427. * @param {Object} state - The current state.
  428. * @param {string} inviteUrl - The conference/location URL.
  429. * @param {boolean} useHtml - Whether to return html text.
  430. * @returns {Promise<string>} A {@code Promise} resolving with a
  431. * descriptive text that can be used to invite participants to a meeting.
  432. */
  433. export function getShareInfoText(
  434. state: Object, inviteUrl: string, useHtml: ?boolean): Promise<string> {
  435. let roomUrl = _decodeRoomURI(inviteUrl);
  436. const includeDialInfo = state['features/base/config'] !== undefined;
  437. if (useHtml) {
  438. roomUrl = `<a href="${roomUrl}">${roomUrl}</a>`;
  439. }
  440. let infoText = i18next.t('share.mainText', { roomUrl });
  441. if (includeDialInfo) {
  442. const { room } = parseURIString(inviteUrl);
  443. let numbersPromise;
  444. if (state['features/invite'].numbers
  445. && state['features/invite'].conferenceID) {
  446. numbersPromise = Promise.resolve(state['features/invite']);
  447. } else {
  448. // we are requesting numbers and conferenceId directly
  449. // not using updateDialInNumbers, because custom room
  450. // is specified and we do not want to store the data
  451. // in the state
  452. const { dialInConfCodeUrl, dialInNumbersUrl, hosts }
  453. = state['features/base/config'];
  454. const mucURL = hosts && hosts.muc;
  455. if (!dialInConfCodeUrl || !dialInNumbersUrl || !mucURL) {
  456. // URLs for fetching dial in numbers not defined
  457. return Promise.resolve(infoText);
  458. }
  459. numbersPromise = Promise.all([
  460. getDialInNumbers(dialInNumbersUrl, room, mucURL),
  461. getDialInConferenceID(dialInConfCodeUrl, room, mucURL)
  462. ]).then(([ numbers, {
  463. conference, id, message } ]) => {
  464. if (!conference || !id) {
  465. return Promise.reject(message);
  466. }
  467. return {
  468. numbers,
  469. conferenceID: id
  470. };
  471. });
  472. }
  473. return numbersPromise.then(
  474. ({ conferenceID, numbers }) => {
  475. const phoneNumber = _getDefaultPhoneNumber(numbers) || '';
  476. return `${
  477. i18next.t('info.dialInNumber')} ${
  478. phoneNumber} ${
  479. i18next.t('info.dialInConferenceID')} ${
  480. conferenceID}#\n\n`;
  481. })
  482. .catch(error =>
  483. logger.error('Error fetching numbers or conferenceID', error))
  484. .then(defaultDialInNumber => {
  485. let dialInfoPageUrl = getDialInfoPageURL(state, room);
  486. if (useHtml) {
  487. dialInfoPageUrl
  488. = `<a href="${dialInfoPageUrl}">${dialInfoPageUrl}</a>`;
  489. }
  490. infoText += i18next.t('share.dialInfoText', {
  491. defaultDialInNumber,
  492. dialInfoPageUrl });
  493. return infoText;
  494. });
  495. }
  496. return Promise.resolve(infoText);
  497. }
  498. /**
  499. * Generates the URL for the static dial in info page.
  500. *
  501. * @param {Object} state - The state from the Redux store.
  502. * @param {string?} roomName - The conference name. Optional name, if missing will be extracted from state.
  503. * @returns {string}
  504. */
  505. export function getDialInfoPageURL(state: Object, roomName: ?string) {
  506. const { didPageUrl } = state['features/dynamic-branding'];
  507. const conferenceName = roomName ?? getRoomName(state);
  508. const { locationURL } = state['features/base/connection'];
  509. const { href } = locationURL;
  510. const room = _decodeRoomURI(conferenceName);
  511. const url = didPageUrl || `${href.substring(0, href.lastIndexOf('/'))}/static/dialInInfo.html`;
  512. return `${url}?room=${room}`;
  513. }
  514. /**
  515. * Generates the URL for the static dial in info page.
  516. *
  517. * @param {string} uri - The conference URI string.
  518. * @returns {string}
  519. */
  520. export function getDialInfoPageURLForURIString(
  521. uri: ?string) {
  522. if (!uri) {
  523. return undefined;
  524. }
  525. const { protocol, host, contextRoot, room } = parseURIString(uri);
  526. return `${protocol}//${host}${contextRoot}static/dialInInfo.html?room=${room}`;
  527. }
  528. /**
  529. * Returns whether or not dial-in related UI should be displayed.
  530. *
  531. * @param {Object} dialIn - Dial in information.
  532. * @returns {boolean}
  533. */
  534. export function shouldDisplayDialIn(dialIn: Object) {
  535. const { conferenceID, numbers, numbersEnabled } = dialIn;
  536. const phoneNumber = _getDefaultPhoneNumber(numbers);
  537. return Boolean(
  538. conferenceID
  539. && numbers
  540. && numbersEnabled
  541. && phoneNumber);
  542. }
  543. /**
  544. * Returns if multiple dial-in numbers are available.
  545. *
  546. * @param {Array<string>|Object} dialInNumbers - The array or object of
  547. * numbers to check.
  548. * @private
  549. * @returns {boolean}
  550. */
  551. export function hasMultipleNumbers(dialInNumbers: ?Object) {
  552. if (!dialInNumbers) {
  553. return false;
  554. }
  555. if (Array.isArray(dialInNumbers)) {
  556. return dialInNumbers.length > 1;
  557. }
  558. // deprecated and will be removed
  559. const { numbers } = dialInNumbers;
  560. // eslint-disable-next-line no-confusing-arrow
  561. return Boolean(numbers && Object.values(numbers).map(a => Array.isArray(a) ? a.length : 0)
  562. .reduce((a, b) => a + b) > 1);
  563. }
  564. /**
  565. * Sets the internal state of which dial-in number to display.
  566. *
  567. * @param {Array<string>|Object} dialInNumbers - The array or object of
  568. * numbers to choose a number from.
  569. * @private
  570. * @returns {string|null}
  571. */
  572. export function _getDefaultPhoneNumber(
  573. dialInNumbers: ?Object): ?string {
  574. if (!dialInNumbers) {
  575. return null;
  576. }
  577. if (Array.isArray(dialInNumbers)) {
  578. // new syntax follows
  579. // find the default country inside dialInNumbers, US one
  580. // or return the first one
  581. const defaultNumber = dialInNumbers.find(number => number.default);
  582. if (defaultNumber) {
  583. return defaultNumber.formattedNumber;
  584. }
  585. return dialInNumbers.length > 0
  586. ? dialInNumbers[0].formattedNumber : null;
  587. }
  588. const { numbers } = dialInNumbers;
  589. if (numbers && Object.keys(numbers).length > 0) {
  590. // deprecated and will be removed
  591. const firstRegion = Object.keys(numbers)[0];
  592. return firstRegion && numbers[firstRegion][0];
  593. }
  594. return null;
  595. }
  596. /**
  597. * Decodes URI only if doesn't contain a space(' ').
  598. *
  599. * @param {string} url - The string to decode.
  600. * @returns {string} - It the string contains space, encoded value is '%20' returns
  601. * same string, otherwise decoded one.
  602. * @private
  603. */
  604. export function _decodeRoomURI(url: string) {
  605. let roomUrl = url;
  606. // we want to decode urls when the do not contain space, ' ', which url encoded is %20
  607. if (roomUrl && !roomUrl.includes('%20')) {
  608. roomUrl = decodeURI(roomUrl);
  609. }
  610. // Handles a special case where the room name has % encoded, the decoded will have
  611. // % followed by a char (non-digit) which is not a valid URL and room name ... so we do not
  612. // want to show this decoded
  613. if (roomUrl.match(/.*%[^\d].*/)) {
  614. return url;
  615. }
  616. return roomUrl;
  617. }
  618. /**
  619. * Returns the stored conference id.
  620. *
  621. * @param {Object | Function} stateful - The Object or Function that can be
  622. * resolved to a Redux state object with the toState function.
  623. * @returns {string}
  624. */
  625. export function getConferenceId(stateful: Object | Function) {
  626. return toState(stateful)['features/invite'].conferenceID;
  627. }
  628. /**
  629. * Returns the default dial in number from the store.
  630. *
  631. * @param {Object | Function} stateful - The Object or Function that can be
  632. * resolved to a Redux state object with the toState function.
  633. * @returns {string | null}
  634. */
  635. export function getDefaultDialInNumber(stateful: Object | Function) {
  636. return _getDefaultPhoneNumber(toState(stateful)['features/invite'].numbers);
  637. }
  638. /**
  639. * Executes the dial out request.
  640. *
  641. * @param {string} url - The url for dialing out.
  642. * @param {Object} body - The body of the request.
  643. * @param {string} reqId - The unique request id.
  644. * @returns {Object}
  645. */
  646. export async function executeDialOutRequest(url: string, body: Object, reqId: string) {
  647. const res = await fetch(url, {
  648. method: 'POST',
  649. headers: {
  650. 'Content-Type': 'application/json',
  651. 'request-id': reqId
  652. },
  653. body: JSON.stringify(body)
  654. });
  655. const json = await res.json();
  656. return res.ok ? json : Promise.reject(json);
  657. }
  658. /**
  659. * Executes the dial out status request.
  660. *
  661. * @param {string} url - The url for dialing out.
  662. * @param {string} reqId - The unique request id used on the dial out request.
  663. * @returns {Object}
  664. */
  665. export async function executeDialOutStatusRequest(url: string, reqId: string) {
  666. const res = await fetch(url, {
  667. method: 'GET',
  668. headers: {
  669. 'Content-Type': 'application/json',
  670. 'request-id': reqId
  671. }
  672. });
  673. const json = await res.json();
  674. return res.ok ? json : Promise.reject(json);
  675. }
  676. export const sharingFeatures = {
  677. email: 'email',
  678. url: 'url',
  679. dialIn: 'dial-in',
  680. embed: 'embed'
  681. };
  682. /**
  683. * Returns true if a specific sharing feature is enabled in interface configuration.
  684. *
  685. * @param {string} sharingFeature - The sharing feature to check.
  686. * @returns {boolean}
  687. */
  688. export function isSharingEnabled(sharingFeature: string) {
  689. return typeof interfaceConfig === 'undefined'
  690. || typeof interfaceConfig.SHARING_FEATURES === 'undefined'
  691. || (interfaceConfig.SHARING_FEATURES.length && interfaceConfig.SHARING_FEATURES.indexOf(sharingFeature) > -1);
  692. }
  693. /**
  694. * Sends a post request to an invite service.
  695. *
  696. * @param {Array} inviteItems - The list of the "sip" type items to invite.
  697. * @param {URL} locationURL - The URL of the location.
  698. * @param {string} sipInviteUrl - The invite service that generates the invitation.
  699. * @param {string} jwt - The jwt token.
  700. * @param {string} roomName - The name to the conference.
  701. * @param {string} roomPassword - The password of the conference.
  702. * @param {string} displayName - The user display name.
  703. * @returns {Promise} - The promise created by the request.
  704. */
  705. export function inviteSipEndpoints( // eslint-disable-line max-params
  706. inviteItems: Array<Object>,
  707. locationURL: URL,
  708. sipInviteUrl: string,
  709. jwt: string,
  710. roomName: string,
  711. roomPassword: String,
  712. displayName: string
  713. ): Promise<void> {
  714. if (inviteItems.length === 0) {
  715. return Promise.resolve();
  716. }
  717. const regex = new RegExp(`/${roomName}`, 'i');
  718. const baseUrl = Object.assign(new URL(locationURL.toString()), {
  719. pathname: locationURL.pathname.replace(regex, ''),
  720. hash: '',
  721. search: ''
  722. });
  723. return fetch(
  724. sipInviteUrl,
  725. {
  726. body: JSON.stringify({
  727. callParams: {
  728. callUrlInfo: {
  729. baseUrl,
  730. callName: roomName
  731. },
  732. passcode: roomPassword
  733. },
  734. sipClientParams: {
  735. displayName,
  736. sipAddress: inviteItems.map(item => item.address)
  737. }
  738. }),
  739. method: 'POST',
  740. headers: {
  741. 'Authorization': `Bearer ${jwt}`,
  742. 'Content-Type': 'application/json'
  743. }
  744. }
  745. );
  746. }