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.

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