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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // @flow
  2. import { getAppProp } from '../base/app';
  3. import { isLocalParticipantModerator } from '../base/participants';
  4. import { doGetJSON } from '../base/util';
  5. declare var $: Function;
  6. declare var interfaceConfig: Object;
  7. const logger = require('jitsi-meet-logger').getLogger(__filename);
  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);
  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 confernce dial-in numbers.
  49. * @returns {Promise} - The promise created by the request. The returned numbers
  50. * may be an array of numbers or an object with countries as keys and arrays of
  51. * phone number strings.
  52. */
  53. export function getDialInNumbers(url: string): Promise<*> {
  54. return doGetJSON(url);
  55. }
  56. /**
  57. * Removes all non-numeric characters from a string.
  58. *
  59. * @param {string} text - The string from which to remove all characters except
  60. * numbers.
  61. * @returns {string} A string with only numbers.
  62. */
  63. export function getDigitsOnly(text: string = ''): string {
  64. return text.replace(/\D/g, '');
  65. }
  66. /**
  67. * Type of the options to use when sending a search query.
  68. */
  69. export type GetInviteResultsOptions = {
  70. /**
  71. * The endpoint to use for checking phone number validity.
  72. */
  73. dialOutAuthUrl: string,
  74. /**
  75. * Whether or not to search for people.
  76. */
  77. addPeopleEnabled: boolean,
  78. /**
  79. * Whether or not to check phone numbers.
  80. */
  81. dialOutEnabled: boolean,
  82. /**
  83. * Array with the query types that will be executed -
  84. * "conferenceRooms" | "user" | "room".
  85. */
  86. peopleSearchQueryTypes: Array<string>,
  87. /**
  88. * The url to query for people.
  89. */
  90. peopleSearchUrl: string,
  91. /**
  92. * The jwt token to pass to the search service.
  93. */
  94. jwt: string
  95. };
  96. /**
  97. * Combines directory search with phone number validation to produce a single
  98. * set of invite search results.
  99. *
  100. * @param {string} query - Text to search.
  101. * @param {GetInviteResultsOptions} options - Options to use when searching.
  102. * @returns {Promise<*>}
  103. */
  104. export function getInviteResultsForQuery(
  105. query: string,
  106. options: GetInviteResultsOptions
  107. ): Promise<*> {
  108. const text = query.trim();
  109. const {
  110. dialOutAuthUrl,
  111. addPeopleEnabled,
  112. dialOutEnabled,
  113. peopleSearchQueryTypes,
  114. peopleSearchUrl,
  115. jwt
  116. } = options;
  117. let peopleSearchPromise;
  118. if (addPeopleEnabled && text) {
  119. peopleSearchPromise = searchDirectory(
  120. peopleSearchUrl,
  121. jwt,
  122. text,
  123. peopleSearchQueryTypes);
  124. } else {
  125. peopleSearchPromise = Promise.resolve([]);
  126. }
  127. let hasCountryCode = text.startsWith('+');
  128. let phoneNumberPromise;
  129. // Phone numbers are handled a specially to enable both cases of restricting
  130. // numbers to telephone number-y numbers and accepting any arbitrary string,
  131. // which may be valid for SIP (jigasi) calls. If the dialOutAuthUrl is
  132. // defined, then it is assumed the call is to a telephone number and
  133. // some validation of the number is completed, with the + sign used as a way
  134. // for the UI to detect and enforce the usage of a country code. If the
  135. // dialOutAuthUrl is not defined, accept anything because this is assumed
  136. // to be the SIP (jigasi) case.
  137. if (dialOutEnabled && dialOutAuthUrl && isMaybeAPhoneNumber(text)) {
  138. let numberToVerify = text;
  139. // When the number to verify does not start with a +, we assume no
  140. // proper country code has been entered. In such a case, prepend 1 for
  141. // the country code. The service currently takes care of prepending the
  142. // +.
  143. if (!hasCountryCode && !text.startsWith('1')) {
  144. numberToVerify = `1${numberToVerify}`;
  145. }
  146. // The validation service works properly when the query is digits only
  147. // so ensure only digits get sent.
  148. numberToVerify = getDigitsOnly(numberToVerify);
  149. phoneNumberPromise = checkDialNumber(numberToVerify, dialOutAuthUrl);
  150. } else if (dialOutEnabled && !dialOutAuthUrl) {
  151. // fake having a country code to hide the country code reminder
  152. hasCountryCode = true;
  153. // With no auth url, let's say the text is a valid number
  154. phoneNumberPromise = Promise.resolve({
  155. allow: true,
  156. country: '',
  157. phone: text
  158. });
  159. } else {
  160. phoneNumberPromise = Promise.resolve({});
  161. }
  162. return Promise.all([ peopleSearchPromise, phoneNumberPromise ])
  163. .then(([ peopleResults, phoneResults ]) => {
  164. const results = [
  165. ...peopleResults
  166. ];
  167. /**
  168. * This check for phone results is for the day the call to searching
  169. * people might return phone results as well. When that day comes
  170. * this check will make it so the server checks are honored and the
  171. * local appending of the number is not done. The local appending of
  172. * the phone number can then be cleaned up when convenient.
  173. */
  174. const hasPhoneResult
  175. = peopleResults.find(result => result.type === 'phone');
  176. if (!hasPhoneResult && typeof phoneResults.allow === 'boolean') {
  177. results.push({
  178. allowed: phoneResults.allow,
  179. country: phoneResults.country,
  180. type: 'phone',
  181. number: phoneResults.phone,
  182. originalEntry: text,
  183. showCountryCodeReminder: !hasCountryCode
  184. });
  185. }
  186. return results;
  187. });
  188. }
  189. /**
  190. * Helper for determining how many of each type of user is being invited. Used
  191. * for logging and sending analytics related to invites.
  192. *
  193. * @param {Array} inviteItems - An array with the invite items, as created in
  194. * {@link _parseQueryResults}.
  195. * @returns {Object} An object with keys as user types and values as the number
  196. * of invites for that type.
  197. */
  198. export function getInviteTypeCounts(inviteItems: Array<Object> = []) {
  199. const inviteTypeCounts = {};
  200. inviteItems.forEach(({ type }) => {
  201. if (!inviteTypeCounts[type]) {
  202. inviteTypeCounts[type] = 0;
  203. }
  204. inviteTypeCounts[type]++;
  205. });
  206. return inviteTypeCounts;
  207. }
  208. /**
  209. * Sends a post request to an invite service.
  210. *
  211. * @param {string} inviteServiceUrl - The invite service that generates the
  212. * invitation.
  213. * @param {string} inviteUrl - The url to the conference.
  214. * @param {string} jwt - The jwt token to pass to the search service.
  215. * @param {Immutable.List} inviteItems - The list of the "user" or "room" type
  216. * items to invite.
  217. * @returns {Promise} - The promise created by the request.
  218. */
  219. export function invitePeopleAndChatRooms( // eslint-disable-line max-params
  220. inviteServiceUrl: string,
  221. inviteUrl: string,
  222. jwt: string,
  223. inviteItems: Array<Object>
  224. ): Promise<void> {
  225. if (!inviteItems || inviteItems.length === 0) {
  226. return Promise.resolve();
  227. }
  228. return new Promise((resolve, reject) => {
  229. $.post(
  230. `${inviteServiceUrl}?token=${jwt}`,
  231. JSON.stringify({
  232. 'invited': inviteItems,
  233. 'url': inviteUrl
  234. }),
  235. resolve,
  236. 'json')
  237. .fail((jqxhr, textStatus, error) => reject(error));
  238. });
  239. }
  240. /**
  241. * Determines if adding people is currently enabled.
  242. *
  243. * @param {boolean} state - Current state.
  244. * @returns {boolean} Indication of whether adding people is currently enabled.
  245. */
  246. export function isAddPeopleEnabled(state: Object): boolean {
  247. const { isGuest } = state['features/base/jwt'];
  248. if (!isGuest) {
  249. // XXX The mobile/react-native app is capable of disabling the
  250. // adding/inviting of people in the current conference. Anyway, the
  251. // Web/React app does not have that capability so default appropriately.
  252. const addPeopleEnabled = getAppProp(state, 'addPeopleEnabled');
  253. return (
  254. (typeof addPeopleEnabled === 'undefined')
  255. || Boolean(addPeopleEnabled));
  256. }
  257. return false;
  258. }
  259. /**
  260. * Determines if dial out is currently enabled or not.
  261. *
  262. * @param {boolean} state - Current state.
  263. * @returns {boolean} Indication of whether dial out is currently enabled.
  264. */
  265. export function isDialOutEnabled(state: Object): boolean {
  266. const { conference } = state['features/base/conference'];
  267. let dialOutEnabled = isLocalParticipantModerator(state)
  268. && conference
  269. && conference.isSIPCallingSupported();
  270. if (dialOutEnabled) {
  271. // XXX The mobile/react-native app is capable of disabling of dial-out.
  272. // Anyway, the Web/React app does not have that capability so default
  273. // appropriately.
  274. dialOutEnabled = getAppProp(state, 'dialOutEnabled');
  275. return (
  276. (typeof dialOutEnabled === 'undefined') || Boolean(dialOutEnabled));
  277. }
  278. return false;
  279. }
  280. /**
  281. * Checks whether a string looks like it could be for a phone number.
  282. *
  283. * @param {string} text - The text to check whether or not it could be a phone
  284. * number.
  285. * @private
  286. * @returns {boolean} True if the string looks like it could be a phone number.
  287. */
  288. function isMaybeAPhoneNumber(text: string): boolean {
  289. if (!isPhoneNumberRegex().test(text)) {
  290. return false;
  291. }
  292. const digits = getDigitsOnly(text);
  293. return Boolean(digits.length);
  294. }
  295. /**
  296. * RegExp to use to determine if some text might be a phone number.
  297. *
  298. * @returns {RegExp}
  299. */
  300. function isPhoneNumberRegex(): RegExp {
  301. let regexString = '^[0-9+()-\\s]*$';
  302. if (typeof interfaceConfig !== 'undefined') {
  303. regexString = interfaceConfig.PHONE_NUMBER_REGEX || regexString;
  304. }
  305. return new RegExp(regexString);
  306. }
  307. /**
  308. * Sends an ajax request to a directory service.
  309. *
  310. * @param {string} serviceUrl - The service to query.
  311. * @param {string} jwt - The jwt token to pass to the search service.
  312. * @param {string} text - Text to search.
  313. * @param {Array<string>} queryTypes - Array with the query types that will be
  314. * executed - "conferenceRooms" | "user" | "room".
  315. * @returns {Promise} - The promise created by the request.
  316. */
  317. export function searchDirectory( // eslint-disable-line max-params
  318. serviceUrl: string,
  319. jwt: string,
  320. text: string,
  321. queryTypes: Array<string> = [ 'conferenceRooms', 'user', 'room' ]
  322. ): Promise<Array<Object>> {
  323. const query = encodeURIComponent(text);
  324. const queryTypesString = encodeURIComponent(JSON.stringify(queryTypes));
  325. return fetch(`${serviceUrl}?query=${query}&queryTypes=${
  326. queryTypesString}&jwt=${jwt}`)
  327. .then(response => {
  328. const jsonify = response.json();
  329. if (response.ok) {
  330. return jsonify;
  331. }
  332. return jsonify
  333. .then(result => Promise.reject(result));
  334. })
  335. .catch(error => {
  336. logger.error(
  337. 'Error searching directory:', error);
  338. return Promise.reject(error);
  339. });
  340. }