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 18KB

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