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

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