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

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