Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 a GET request to obtain the conference ID necessary for identifying
  9. * which conference to join after diaing the dial-in service.
  10. *
  11. * @param {string} baseUrl - The url for obtaining the conference ID (pin) for
  12. * dialing into a conference.
  13. * @param {string} roomName - The conference name to find the associated
  14. * conference ID.
  15. * @param {string} mucURL - In which MUC the conference exists.
  16. * @returns {Promise} - The promise created by the request.
  17. */
  18. export function getDialInConferenceID(
  19. baseUrl: string,
  20. roomName: string,
  21. mucURL: string): Promise<Object> {
  22. const conferenceIDURL = `${baseUrl}?conference=${roomName}@${mucURL}`;
  23. return doGetJSON(conferenceIDURL);
  24. }
  25. /**
  26. * Sends a GET request for phone numbers used to dial into a conference.
  27. *
  28. * @param {string} url - The service that returns confernce dial-in numbers.
  29. * @returns {Promise} - The promise created by the request. The returned numbers
  30. * may be an array of numbers or an object with countries as keys and arrays of
  31. * phone number strings.
  32. */
  33. export function getDialInNumbers(url: string): Promise<*> {
  34. return doGetJSON(url);
  35. }
  36. /**
  37. * Sends a post request to an invite service.
  38. *
  39. * @param {string} inviteServiceUrl - The invite service that generates the
  40. * invitation.
  41. * @param {string} inviteUrl - The url to the conference.
  42. * @param {string} jwt - The jwt token to pass to the search service.
  43. * @param {Immutable.List} inviteItems - The list of the "user" or "room"
  44. * type items to invite.
  45. * @returns {Promise} - The promise created by the request.
  46. */
  47. function invitePeopleAndChatRooms( // eslint-disable-line max-params
  48. inviteServiceUrl: string,
  49. inviteUrl: string,
  50. jwt: string,
  51. inviteItems: Array<Object>): Promise<void> {
  52. if (!inviteItems || inviteItems.length === 0) {
  53. return Promise.resolve();
  54. }
  55. return new Promise((resolve, reject) => {
  56. $.post(
  57. `${inviteServiceUrl}?token=${jwt}`,
  58. JSON.stringify({
  59. 'invited': inviteItems,
  60. 'url': inviteUrl
  61. }),
  62. resolve,
  63. 'json')
  64. .fail((jqxhr, textStatus, error) => reject(error));
  65. });
  66. }
  67. /**
  68. * Sends an ajax request to a directory service.
  69. *
  70. * @param {string} serviceUrl - The service to query.
  71. * @param {string} jwt - The jwt token to pass to the search service.
  72. * @param {string} text - Text to search.
  73. * @param {Array<string>} queryTypes - Array with the query types that will be
  74. * executed - "conferenceRooms" | "user" | "room".
  75. * @returns {Promise} - The promise created by the request.
  76. */
  77. export function searchDirectory( // eslint-disable-line max-params
  78. serviceUrl: string,
  79. jwt: string,
  80. text: string,
  81. queryTypes: Array<string> = [ 'conferenceRooms', 'user', 'room' ]
  82. ): Promise<Array<Object>> {
  83. const query = encodeURIComponent(text);
  84. const queryTypesString = encodeURIComponent(JSON.stringify(queryTypes));
  85. return fetch(`${serviceUrl}?query=${query}&queryTypes=${
  86. queryTypesString}&jwt=${jwt}`)
  87. .then(response => {
  88. const jsonify = response.json();
  89. if (response.ok) {
  90. return jsonify;
  91. }
  92. return jsonify
  93. .then(result => Promise.reject(result));
  94. })
  95. .catch(error => {
  96. logger.error(
  97. 'Error searching directory:', error);
  98. return Promise.reject(error);
  99. });
  100. }
  101. /**
  102. * RegExp to use to determine if some text might be a phone number.
  103. *
  104. * @returns {RegExp}
  105. */
  106. function isPhoneNumberRegex(): RegExp {
  107. let regexString = '^[0-9+()-\\s]*$';
  108. if (typeof interfaceConfig !== 'undefined') {
  109. regexString = interfaceConfig.PHONE_NUMBER_REGEX || regexString;
  110. }
  111. return new RegExp(regexString);
  112. }
  113. /**
  114. * Sends an ajax request to check if the phone number can be called.
  115. *
  116. * @param {string} dialNumber - The dial number to check for validity.
  117. * @param {string} dialOutAuthUrl - The endpoint to use for checking validity.
  118. * @returns {Promise} - The promise created by the request.
  119. */
  120. export function checkDialNumber(
  121. dialNumber: string, dialOutAuthUrl: string): Promise<Object> {
  122. if (!dialOutAuthUrl) {
  123. // no auth url, let's say it is valid
  124. const response = {
  125. allow: true,
  126. phone: `+${dialNumber}`
  127. };
  128. return Promise.resolve(response);
  129. }
  130. const fullUrl = `${dialOutAuthUrl}?phone=${dialNumber}`;
  131. return new Promise((resolve, reject) => {
  132. $.getJSON(fullUrl)
  133. .then(resolve)
  134. .catch(reject);
  135. });
  136. }
  137. /**
  138. * Removes all non-numeric characters from a string.
  139. *
  140. * @param {string} text - The string from which to remove all characters
  141. * except numbers.
  142. * @private
  143. * @returns {string} A string with only numbers.
  144. */
  145. function getDigitsOnly(text: string = ''): string {
  146. return text.replace(/\D/g, '');
  147. }
  148. /**
  149. * Type of the options to use when sending a search query.
  150. */
  151. export type GetInviteResultsOptions = {
  152. /**
  153. * The endpoint to use for checking phone number validity.
  154. */
  155. dialOutAuthUrl: string,
  156. /**
  157. * Whether or not to search for people.
  158. */
  159. enableAddPeople: boolean,
  160. /**
  161. * Whether or not to check phone numbers.
  162. */
  163. enableDialOut: boolean,
  164. /**
  165. * Array with the query types that will be executed -
  166. * "conferenceRooms" | "user" | "room".
  167. */
  168. peopleSearchQueryTypes: Array<string>,
  169. /**
  170. * The url to query for people.
  171. */
  172. peopleSearchUrl: string,
  173. /**
  174. * The jwt token to pass to the search service.
  175. */
  176. jwt: string
  177. };
  178. /**
  179. * Combines directory search with phone number validation to produce a single
  180. * set of invite search results.
  181. *
  182. * @param {string} query - Text to search.
  183. * @param {GetInviteResultsOptions} options - Options to use when searching.
  184. * @returns {Promise<*>}
  185. */
  186. export function getInviteResultsForQuery(
  187. query: string,
  188. options: GetInviteResultsOptions): Promise<*> {
  189. const text = query.trim();
  190. const {
  191. dialOutAuthUrl,
  192. enableAddPeople,
  193. enableDialOut,
  194. peopleSearchQueryTypes,
  195. peopleSearchUrl,
  196. jwt
  197. } = options;
  198. let peopleSearchPromise;
  199. if (enableAddPeople && text) {
  200. peopleSearchPromise = searchDirectory(
  201. peopleSearchUrl,
  202. jwt,
  203. text,
  204. peopleSearchQueryTypes);
  205. } else {
  206. peopleSearchPromise = Promise.resolve([]);
  207. }
  208. const hasCountryCode = text.startsWith('+');
  209. let phoneNumberPromise;
  210. if (enableDialOut && isMaybeAPhoneNumber(text)) {
  211. let numberToVerify = text;
  212. // When the number to verify does not start with a +, we assume no
  213. // proper country code has been entered. In such a case, prepend 1
  214. // for the country code. The service currently takes care of
  215. // prepending the +.
  216. if (!hasCountryCode && !text.startsWith('1')) {
  217. numberToVerify = `1${numberToVerify}`;
  218. }
  219. // The validation service works properly when the query is digits
  220. // only so ensure only digits get sent.
  221. numberToVerify = getDigitsOnly(numberToVerify);
  222. phoneNumberPromise
  223. = checkDialNumber(numberToVerify, dialOutAuthUrl);
  224. } else {
  225. phoneNumberPromise = Promise.resolve({});
  226. }
  227. return Promise.all([ peopleSearchPromise, phoneNumberPromise ])
  228. .then(([ peopleResults, phoneResults ]) => {
  229. const results = [
  230. ...peopleResults
  231. ];
  232. /**
  233. * This check for phone results is for the day the call to
  234. * searching people might return phone results as well. When
  235. * that day comes this check will make it so the server checks
  236. * are honored and the local appending of the number is not
  237. * done. The local appending of the phone number can then be
  238. * cleaned up when convenient.
  239. */
  240. const hasPhoneResult = peopleResults.find(
  241. result => result.type === 'phone');
  242. if (!hasPhoneResult
  243. && typeof phoneResults.allow === 'boolean') {
  244. results.push({
  245. allowed: phoneResults.allow,
  246. country: phoneResults.country,
  247. type: 'phone',
  248. number: phoneResults.phone,
  249. originalEntry: text,
  250. showCountryCodeReminder: !hasCountryCode
  251. });
  252. }
  253. return results;
  254. });
  255. }
  256. /**
  257. * Checks whether a string looks like it could be for a phone number.
  258. *
  259. * @param {string} text - The text to check whether or not it could be a
  260. * phone number.
  261. * @private
  262. * @returns {boolean} True if the string looks like it could be a phone
  263. * number.
  264. */
  265. function isMaybeAPhoneNumber(text: string): boolean {
  266. if (!isPhoneNumberRegex().test(text)) {
  267. return false;
  268. }
  269. const digits = getDigitsOnly(text);
  270. return Boolean(digits.length);
  271. }
  272. /**
  273. * Type of the options to use when sending invites.
  274. */
  275. export type SendInvitesOptions = {
  276. /**
  277. * Conference object used to dial out.
  278. */
  279. conference: Object,
  280. /**
  281. * The URL to send invites through.
  282. */
  283. inviteServiceUrl: string,
  284. /**
  285. * The URL sent with each invite.
  286. */
  287. inviteUrl: string,
  288. /**
  289. * The function to use to invite video rooms.
  290. *
  291. * @param {Object} The conference to which the video rooms should be
  292. * invited.
  293. * @param {Array<Object>} The list of rooms that should be invited.
  294. * @returns {void}
  295. */
  296. inviteVideoRooms: (Object, Array<Object>) => void,
  297. /**
  298. * The jwt token to pass to the invite service.
  299. */
  300. jwt: string
  301. };
  302. /**
  303. * Send invites for a list of items (may be a combination of users, rooms, phone
  304. * numbers, and video rooms).
  305. *
  306. * @param {Array<Object>} invites - Items for which invites should be sent.
  307. * @param {SendInvitesOptions} options - Options to use when sending the
  308. * provided invites.
  309. * @returns {Promise} Promise containing the list of invites that were not sent.
  310. */
  311. export function sendInvitesForItems(
  312. invites: Array<Object>,
  313. options: SendInvitesOptions
  314. ): Promise<Array<Object>> {
  315. const {
  316. conference,
  317. inviteServiceUrl,
  318. inviteUrl,
  319. inviteVideoRooms,
  320. jwt
  321. } = options;
  322. let allInvitePromises = [];
  323. let invitesLeftToSend = [ ...invites ];
  324. // First create all promises for dialing out.
  325. if (conference) {
  326. const phoneNumbers = invitesLeftToSend.filter(
  327. item => item.type === 'phone');
  328. // For each number, dial out. On success, remove the number from
  329. // {@link invitesLeftToSend}.
  330. const phoneInvitePromises = phoneNumbers.map(item => {
  331. const numberToInvite = getDigitsOnly(item.number);
  332. return conference.dial(numberToInvite)
  333. .then(() => {
  334. invitesLeftToSend
  335. = invitesLeftToSend.filter(invite =>
  336. invite !== item);
  337. })
  338. .catch(error => logger.error(
  339. 'Error inviting phone number:', error));
  340. });
  341. allInvitePromises = allInvitePromises.concat(phoneInvitePromises);
  342. }
  343. const usersAndRooms = invitesLeftToSend.filter(item =>
  344. item.type === 'user' || item.type === 'room');
  345. if (usersAndRooms.length) {
  346. // Send a request to invite all the rooms and users. On success,
  347. // filter all rooms and users from {@link invitesLeftToSend}.
  348. const peopleInvitePromise = invitePeopleAndChatRooms(
  349. inviteServiceUrl,
  350. inviteUrl,
  351. jwt,
  352. usersAndRooms)
  353. .then(() => {
  354. invitesLeftToSend = invitesLeftToSend.filter(item =>
  355. item.type !== 'user' && item.type !== 'room');
  356. })
  357. .catch(error => logger.error(
  358. 'Error inviting people:', error));
  359. allInvitePromises.push(peopleInvitePromise);
  360. }
  361. // Sipgw calls are fire and forget. Invite them to the conference
  362. // then immediately remove them from {@link invitesLeftToSend}.
  363. const vrooms = invitesLeftToSend.filter(item =>
  364. item.type === 'videosipgw');
  365. conference
  366. && vrooms.length > 0
  367. && inviteVideoRooms(conference, vrooms);
  368. invitesLeftToSend = invitesLeftToSend.filter(item =>
  369. item.type !== 'videosipgw');
  370. return Promise.all(allInvitePromises)
  371. .then(() => invitesLeftToSend);
  372. }
  373. /**
  374. * Determines if adding people is currently enabled.
  375. *
  376. * @param {boolean} state - Current state.
  377. * @returns {boolean} Indication of whether adding people is currently enabled.
  378. */
  379. export function isAddPeopleEnabled(state: Object): boolean {
  380. const { app } = state['features/app'];
  381. const { isGuest } = state['features/base/jwt'];
  382. return !isGuest && Boolean(app && app.props.addPeopleEnabled);
  383. }
  384. /**
  385. * Determines if dial out is currently enabled or not.
  386. *
  387. * @param {boolean} state - Current state.
  388. * @returns {boolean} Indication of whether dial out is currently enabled.
  389. */
  390. export function isDialOutEnabled(state: Object): boolean {
  391. const { conference } = state['features/base/conference'];
  392. const { isGuest } = state['features/base/jwt'];
  393. const { enableUserRolesBasedOnToken } = state['features/base/config'];
  394. const participant = getLocalParticipant(state);
  395. return participant && participant.role === PARTICIPANT_ROLE.MODERATOR
  396. && conference && conference.isSIPCallingSupported()
  397. && (!enableUserRolesBasedOnToken || !isGuest);
  398. }