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.

functions.js 21KB

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