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.ts 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. import { sha512_256 as sha512 } from 'js-sha512';
  2. import { upperFirst, words } from 'lodash-es';
  3. import { getName } from '../../app/functions';
  4. import { IReduxState, IStore } from '../../app/types';
  5. import { determineTranscriptionLanguage } from '../../transcribing/functions';
  6. import { IStateful } from '../app/types';
  7. import { JitsiTrackErrors } from '../lib-jitsi-meet';
  8. import {
  9. hiddenParticipantJoined,
  10. hiddenParticipantLeft,
  11. participantJoined,
  12. participantLeft
  13. } from '../participants/actions';
  14. import { getLocalParticipant } from '../participants/functions';
  15. import { toState } from '../redux/functions';
  16. import {
  17. appendURLParam,
  18. getBackendSafePath,
  19. safeDecodeURIComponent
  20. } from '../util/uri';
  21. import { setObfuscatedRoom } from './actions';
  22. import {
  23. AVATAR_URL_COMMAND,
  24. EMAIL_COMMAND,
  25. JITSI_CONFERENCE_URL_KEY
  26. } from './constants';
  27. import logger from './logger';
  28. import { IJitsiConference } from './reducer';
  29. /**
  30. * Returns root conference state.
  31. *
  32. * @param {IReduxState} state - Global state.
  33. * @returns {Object} Conference state.
  34. */
  35. export const getConferenceState = (state: IReduxState) => state['features/base/conference'];
  36. /**
  37. * Attach a set of local tracks to a conference.
  38. *
  39. * @param {JitsiConference} conference - Conference instance.
  40. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  41. * @protected
  42. * @returns {Promise}
  43. */
  44. export function _addLocalTracksToConference(
  45. conference: IJitsiConference,
  46. localTracks: Array<Object>) {
  47. const conferenceLocalTracks = conference.getLocalTracks();
  48. const promises = [];
  49. for (const track of localTracks) {
  50. // XXX The library lib-jitsi-meet may be draconian, for example, when
  51. // adding one and the same video track multiple times.
  52. if (conferenceLocalTracks.indexOf(track) === -1) {
  53. promises.push(
  54. conference.addTrack(track).catch((err: Error) => {
  55. _reportError(
  56. 'Failed to add local track to conference',
  57. err);
  58. }));
  59. }
  60. }
  61. return Promise.all(promises);
  62. }
  63. /**
  64. * Logic shared between web and RN which processes the {@code USER_JOINED}
  65. * conference event and dispatches either {@link participantJoined} or
  66. * {@link hiddenParticipantJoined}.
  67. *
  68. * @param {Object} store - The redux store.
  69. * @param {JitsiMeetConference} conference - The conference for which the
  70. * {@code USER_JOINED} event is being processed.
  71. * @param {JitsiParticipant} user - The user who has just joined.
  72. * @returns {void}
  73. */
  74. export function commonUserJoinedHandling(
  75. { dispatch }: { dispatch: IStore['dispatch']; },
  76. conference: IJitsiConference,
  77. user: any) {
  78. const id = user.getId();
  79. const displayName = user.getDisplayName();
  80. if (user.isHidden()) {
  81. dispatch(hiddenParticipantJoined(id, displayName));
  82. } else {
  83. const isReplacing = user?.isReplacing();
  84. dispatch(participantJoined({
  85. botType: user.getBotType(),
  86. conference,
  87. id,
  88. name: displayName,
  89. presence: user.getStatus(),
  90. role: user.getRole(),
  91. isReplacing,
  92. sources: user.getSources()
  93. }));
  94. }
  95. }
  96. /**
  97. * Logic shared between web and RN which processes the {@code USER_LEFT}
  98. * conference event and dispatches either {@link participantLeft} or
  99. * {@link hiddenParticipantLeft}.
  100. *
  101. * @param {Object} store - The redux store.
  102. * @param {JitsiMeetConference} conference - The conference for which the
  103. * {@code USER_LEFT} event is being processed.
  104. * @param {JitsiParticipant} user - The user who has just left.
  105. * @returns {void}
  106. */
  107. export function commonUserLeftHandling(
  108. { dispatch }: { dispatch: IStore['dispatch']; },
  109. conference: IJitsiConference,
  110. user: any) {
  111. const id = user.getId();
  112. if (user.isHidden()) {
  113. dispatch(hiddenParticipantLeft(id));
  114. } else {
  115. const isReplaced = user.isReplaced?.();
  116. dispatch(participantLeft(id, conference, { isReplaced }));
  117. }
  118. }
  119. /**
  120. * Evaluates a specific predicate for each {@link JitsiConference} known to the
  121. * redux state features/base/conference while it returns {@code true}.
  122. *
  123. * @param {IStateful} stateful - The redux store, state, or
  124. * {@code getState} function.
  125. * @param {Function} predicate - The predicate to evaluate for each
  126. * {@code JitsiConference} know to the redux state features/base/conference
  127. * while it returns {@code true}.
  128. * @returns {boolean} If the specified {@code predicate} returned {@code true}
  129. * for all {@code JitsiConference} instances known to the redux state
  130. * features/base/conference.
  131. */
  132. export function forEachConference(
  133. stateful: IStateful,
  134. predicate: (a: any, b: URL) => boolean) {
  135. const state = getConferenceState(toState(stateful));
  136. for (const v of Object.values(state)) {
  137. // Does the value of the base/conference's property look like a
  138. // JitsiConference?
  139. if (v && typeof v === 'object') {
  140. const url: URL = v[JITSI_CONFERENCE_URL_KEY];
  141. // XXX The Web version of Jitsi Meet does not utilize
  142. // JITSI_CONFERENCE_URL_KEY at the time of this writing. An
  143. // alternative is necessary then to recognize JitsiConference
  144. // instances and myUserId is as good as any other property.
  145. if ((url || typeof v.myUserId === 'function')
  146. && !predicate(v, url)) {
  147. return false;
  148. }
  149. }
  150. }
  151. return true;
  152. }
  153. /**
  154. * Returns the display name of the conference.
  155. *
  156. * @param {IStateful} stateful - Reference that can be resolved to Redux
  157. * state with the {@code toState} function.
  158. * @returns {string}
  159. */
  160. export function getConferenceName(stateful: IStateful): string {
  161. const state = toState(stateful);
  162. const { callee } = state['features/base/jwt'];
  163. const { callDisplayName } = state['features/base/config'];
  164. const { localSubject, pendingSubjectChange, room, subject } = getConferenceState(state);
  165. return (localSubject
  166. || pendingSubjectChange
  167. || subject
  168. || callDisplayName
  169. || callee?.name
  170. || (room && safeStartCase(safeDecodeURIComponent(room)))) ?? '';
  171. }
  172. /**
  173. * Returns the name of the conference formatted for the title.
  174. *
  175. * @param {IStateful} stateful - Reference that can be resolved to Redux state with the {@code toState}
  176. * function.
  177. * @returns {string} - The name of the conference formatted for the title.
  178. */
  179. export function getConferenceNameForTitle(stateful: IStateful) {
  180. return safeStartCase(safeDecodeURIComponent(getConferenceState(toState(stateful)).room ?? ''));
  181. }
  182. /**
  183. * Returns an object aggregating the conference options.
  184. *
  185. * @param {IStateful} stateful - The redux store state.
  186. * @returns {Object} - Options object.
  187. */
  188. export function getConferenceOptions(stateful: IStateful) {
  189. const state = toState(stateful);
  190. const config = state['features/base/config'];
  191. const { locationURL } = state['features/base/connection'];
  192. const { tenant } = state['features/base/jwt'];
  193. const { email, name: nick } = getLocalParticipant(state) ?? {};
  194. const options: any = { ...config };
  195. if (tenant) {
  196. options.siteID = tenant;
  197. }
  198. if (options.enableDisplayNameInStats && nick) {
  199. options.statisticsDisplayName = nick;
  200. }
  201. if (options.enableEmailInStats && email) {
  202. options.statisticsId = email;
  203. }
  204. if (locationURL) {
  205. options.confID = `${locationURL.host}${getBackendSafePath(locationURL.pathname)}`;
  206. }
  207. options.applicationName = getName();
  208. options.transcriptionLanguage = determineTranscriptionLanguage(options);
  209. // Disable analytics, if requested.
  210. if (options.disableThirdPartyRequests) {
  211. delete config.analytics?.scriptURLs;
  212. delete config.analytics?.amplitudeAPPKey;
  213. delete config.analytics?.googleAnalyticsTrackingId;
  214. }
  215. return options;
  216. }
  217. /**
  218. * Returns the restored conference options if anything is available to be restored or undefined.
  219. *
  220. * @param {IStateful} stateful - The redux store state.
  221. * @returns {Object?}
  222. */
  223. export function restoreConferenceOptions(stateful: IStateful) {
  224. const config = toState(stateful)['features/base/config'];
  225. if (config.oldConfig) {
  226. return {
  227. hosts: {
  228. domain: config.oldConfig.hosts.domain,
  229. muc: config.oldConfig.hosts.muc
  230. },
  231. focusUserJid: config.oldConfig.focusUserJid,
  232. disableFocus: false,
  233. bosh: config.oldConfig.bosh,
  234. websocket: config.oldConfig.websocket,
  235. oldConfig: undefined
  236. };
  237. }
  238. // nothing to return
  239. return;
  240. }
  241. /**
  242. * Override the global config (that is, window.config) with XMPP configuration required to join as a visitor.
  243. *
  244. * @param {IStateful} stateful - The redux store state.
  245. * @param {string|undefined} vnode - The received parameters.
  246. * @param {string} focusJid - The received parameters.
  247. * @param {string|undefined} username - The received parameters.
  248. * @returns {Object}
  249. */
  250. export function getVisitorOptions(stateful: IStateful, vnode: string, focusJid: string, username: string) {
  251. const config = toState(stateful)['features/base/config'];
  252. if (!config?.hosts) {
  253. logger.warn('Wrong configuration, missing hosts.');
  254. return;
  255. }
  256. if (!vnode) {
  257. // this is redirecting back to main, lets restore config
  258. // not updating disableFocus, as if the room capacity is full the promotion to the main room will fail
  259. // and the visitor will be redirected back to a vnode from jicofo
  260. if (config.oldConfig && username) {
  261. return {
  262. hosts: config.oldConfig.hosts,
  263. focusUserJid: focusJid,
  264. disableLocalStats: false,
  265. bosh: config.oldConfig.bosh && appendURLParam(config.oldConfig.bosh, 'customusername', username),
  266. p2p: config.oldConfig.p2p,
  267. websocket: config.oldConfig.websocket
  268. && appendURLParam(config.oldConfig.websocket, 'customusername', username),
  269. oldConfig: undefined // clears it up
  270. };
  271. }
  272. return;
  273. }
  274. const oldConfig = {
  275. hosts: {
  276. domain: ''
  277. },
  278. focusUserJid: config.focusUserJid,
  279. bosh: config.bosh,
  280. p2p: config.p2p,
  281. websocket: config.websocket
  282. };
  283. // copy original hosts, to make sure we do not use a modified one later
  284. Object.assign(oldConfig.hosts, config.hosts);
  285. const domain = `${vnode}.meet.jitsi`;
  286. return {
  287. oldConfig,
  288. hosts: {
  289. domain,
  290. muc: config.hosts.muc.replace(oldConfig.hosts.domain, domain)
  291. },
  292. focusUserJid: focusJid,
  293. disableFocus: true, // This flag disables sending the initial conference request
  294. disableLocalStats: true,
  295. bosh: config.bosh && appendURLParam(config.bosh, 'vnode', vnode),
  296. p2p: {
  297. ...config.p2p,
  298. enabled: false
  299. },
  300. websocket: config.websocket && appendURLParam(config.websocket, 'vnode', vnode)
  301. };
  302. }
  303. /**
  304. * Returns the UTC timestamp when the first participant joined the conference.
  305. *
  306. * @param {IStateful} stateful - Reference that can be resolved to Redux
  307. * state with the {@code toState} function.
  308. * @returns {number}
  309. */
  310. export function getConferenceTimestamp(stateful: IStateful) {
  311. const state = toState(stateful);
  312. const { conferenceTimestamp } = getConferenceState(state);
  313. return conferenceTimestamp;
  314. }
  315. /**
  316. * Returns the current {@code JitsiConference} which is joining or joined and is
  317. * not leaving. Please note the contrast with merely reading the
  318. * {@code conference} state of the feature base/conference which is not joining
  319. * but may be leaving already.
  320. *
  321. * @param {IStateful} stateful - The redux store, state, or
  322. * {@code getState} function.
  323. * @returns {JitsiConference|undefined}
  324. */
  325. export function getCurrentConference(stateful: IStateful): IJitsiConference | undefined {
  326. const { conference, joining, leaving, membersOnly, passwordRequired }
  327. = getConferenceState(toState(stateful));
  328. // There is a precedence
  329. if (conference) {
  330. return conference === leaving ? undefined : conference;
  331. }
  332. return joining || passwordRequired || membersOnly;
  333. }
  334. /**
  335. * Returns whether the current conference is a P2P connection.
  336. * Will return `false` if it's a JVB one, and `null` if there is no conference.
  337. *
  338. * @param {IStateful} stateful - The redux store, state, or
  339. * {@code getState} function.
  340. * @returns {boolean|null}
  341. */
  342. export function isP2pActive(stateful: IStateful): boolean | null {
  343. const conference = getCurrentConference(toState(stateful));
  344. if (!conference) {
  345. return null;
  346. }
  347. return conference.isP2PActive();
  348. }
  349. /**
  350. * Returns the stored room name.
  351. *
  352. * @param {IReduxState} state - The current state of the app.
  353. * @returns {string}
  354. */
  355. export function getRoomName(state: IReduxState) {
  356. return getConferenceState(state).room;
  357. }
  358. /**
  359. * Get an obfuscated room name or create and persist it if it doesn't exists.
  360. *
  361. * @param {IReduxState} state - The current state of the app.
  362. * @param {Function} dispatch - The Redux dispatch function.
  363. * @returns {string} - Obfuscated room name.
  364. */
  365. export function getOrCreateObfuscatedRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  366. let { obfuscatedRoom } = getConferenceState(state);
  367. const { obfuscatedRoomSource } = getConferenceState(state);
  368. const room = getRoomName(state);
  369. if (!room) {
  370. return;
  371. }
  372. // On native mobile the store doesn't clear when joining a new conference so we might have the obfuscatedRoom
  373. // stored even though a different room was joined.
  374. // Check if the obfuscatedRoom was already computed for the current room.
  375. if (!obfuscatedRoom || (obfuscatedRoomSource !== room)) {
  376. obfuscatedRoom = sha512(room);
  377. dispatch(setObfuscatedRoom(obfuscatedRoom, room));
  378. }
  379. return obfuscatedRoom;
  380. }
  381. /**
  382. * Analytics may require an obfuscated room name, this functions decides based on a config if the normal or
  383. * obfuscated room name should be returned.
  384. *
  385. * @param {IReduxState} state - The current state of the app.
  386. * @param {Function} dispatch - The Redux dispatch function.
  387. * @returns {string} - Analytics room name.
  388. */
  389. export function getAnalyticsRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  390. const { analysis: { obfuscateRoomName = false } = {} } = state['features/base/config'];
  391. if (obfuscateRoomName) {
  392. return getOrCreateObfuscatedRoomName(state, dispatch);
  393. }
  394. return getRoomName(state);
  395. }
  396. /**
  397. * Handle an error thrown by the backend (i.e. {@code lib-jitsi-meet}) while
  398. * manipulating a conference participant (e.g. Pin or select participant).
  399. *
  400. * @param {Error} err - The Error which was thrown by the backend while
  401. * manipulating a conference participant and which is to be handled.
  402. * @protected
  403. * @returns {void}
  404. */
  405. export function _handleParticipantError(err: Error) {
  406. // XXX DataChannels are initialized at some later point when the conference
  407. // has multiple participants, but code that pins or selects a participant
  408. // might be executed before. So here we're swallowing a particular error.
  409. // TODO Lib-jitsi-meet should be fixed to not throw such an exception in
  410. // these scenarios.
  411. if (err.message !== 'Data channels support is disabled!') {
  412. throw err;
  413. }
  414. }
  415. /**
  416. * Determines whether a specific string is a valid room name.
  417. *
  418. * @param {(string|undefined)} room - The name of the conference room to check
  419. * for validity.
  420. * @returns {boolean} If the specified room name is valid, then true; otherwise,
  421. * false.
  422. */
  423. export function isRoomValid(room?: string) {
  424. return typeof room === 'string' && room !== '';
  425. }
  426. /**
  427. * Remove a set of local tracks from a conference.
  428. *
  429. * @param {JitsiConference} conference - Conference instance.
  430. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  431. * @protected
  432. * @returns {Promise}
  433. */
  434. export function _removeLocalTracksFromConference(
  435. conference: IJitsiConference,
  436. localTracks: Array<Object>) {
  437. return Promise.all(localTracks.map(track =>
  438. conference.removeTrack(track)
  439. .catch((err: Error) => {
  440. // Local track might be already disposed by direct
  441. // JitsiTrack#dispose() call. So we should ignore this error
  442. // here.
  443. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  444. _reportError(
  445. 'Failed to remove local track from conference',
  446. err);
  447. }
  448. })
  449. ));
  450. }
  451. /**
  452. * Reports a specific Error with a specific error message. While the
  453. * implementation merely logs the specified msg and err via the console at the
  454. * time of this writing, the intention of the function is to abstract the
  455. * reporting of errors and facilitate elaborating on it in the future.
  456. *
  457. * @param {string} msg - The error message to report.
  458. * @param {Error} err - The Error to report.
  459. * @private
  460. * @returns {void}
  461. */
  462. function _reportError(msg: string, err: Error) {
  463. // TODO This is a good point to call some global error handler when we have
  464. // one.
  465. logger.error(msg, err);
  466. }
  467. /**
  468. * Sends a representation of the local participant such as her avatar (URL),
  469. * email address, and display name to (the remote participants of) a specific
  470. * conference.
  471. *
  472. * @param {Function|Object} stateful - The redux store, state, or
  473. * {@code getState} function.
  474. * @param {JitsiConference} conference - The {@code JitsiConference} to which
  475. * the representation of the local participant is to be sent.
  476. * @returns {void}
  477. */
  478. export function sendLocalParticipant(
  479. stateful: IStateful,
  480. conference?: IJitsiConference) {
  481. const {
  482. avatarURL,
  483. email,
  484. features,
  485. name
  486. } = getLocalParticipant(stateful) ?? {};
  487. avatarURL && conference?.sendCommand(AVATAR_URL_COMMAND, {
  488. value: avatarURL
  489. });
  490. email && conference?.sendCommand(EMAIL_COMMAND, {
  491. value: email
  492. });
  493. if (features && features['screen-sharing'] === 'true') {
  494. conference?.setLocalParticipantProperty('features_screen-sharing', true);
  495. }
  496. conference?.setDisplayName(name);
  497. }
  498. /**
  499. * A safe implementation of lodash#startCase that doesn't deburr the string.
  500. *
  501. * NOTE: According to lodash roadmap, lodash v5 will have this function.
  502. *
  503. * Code based on https://github.com/lodash/lodash/blob/master/startCase.js.
  504. *
  505. * @param {string} s - The string to do start case on.
  506. * @returns {string}
  507. */
  508. function safeStartCase(s = '') {
  509. return words(`${s}`.replace(/['\u2019]/g, '')).reduce(
  510. (result, word, index) => result + (index ? ' ' : '') + upperFirst(word)
  511. , '');
  512. }