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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. // $FlowFixMe
  148. const url: URL = v[JITSI_CONFERENCE_URL_KEY];
  149. // XXX The Web version of Jitsi Meet does not utilize
  150. // JITSI_CONFERENCE_URL_KEY at the time of this writing. An
  151. // alternative is necessary then to recognize JitsiConference
  152. // instances and myUserId is as good as any other property.
  153. if ((url || typeof v.myUserId === 'function')
  154. && !predicate(v, url)) {
  155. return false;
  156. }
  157. }
  158. }
  159. return true;
  160. }
  161. /**
  162. * Returns the display name of the conference.
  163. *
  164. * @param {IStateful} stateful - Reference that can be resolved to Redux
  165. * state with the {@code toState} function.
  166. * @returns {string}
  167. */
  168. export function getConferenceName(stateful: IStateful): string {
  169. const state = toState(stateful);
  170. const { callee } = state['features/base/jwt'];
  171. const { callDisplayName } = state['features/base/config'];
  172. const { localSubject, pendingSubjectChange, room, subject } = getConferenceState(state);
  173. return (pendingSubjectChange
  174. || localSubject
  175. || subject
  176. || callDisplayName
  177. || callee?.name
  178. || (room && safeStartCase(safeDecodeURIComponent(room)))) ?? '';
  179. }
  180. /**
  181. * Returns the name of the conference formatted for the title.
  182. *
  183. * @param {IStateful} stateful - Reference that can be resolved to Redux state with the {@code toState}
  184. * function.
  185. * @returns {string} - The name of the conference formatted for the title.
  186. */
  187. export function getConferenceNameForTitle(stateful: IStateful) {
  188. return safeStartCase(safeDecodeURIComponent(getConferenceState(toState(stateful)).room ?? ''));
  189. }
  190. /**
  191. * Returns an object aggregating the conference options.
  192. *
  193. * @param {IStateful} stateful - The redux store state.
  194. * @returns {Object} - Options object.
  195. */
  196. export function getConferenceOptions(stateful: IStateful) {
  197. const state = toState(stateful);
  198. const config = state['features/base/config'];
  199. const { locationURL } = state['features/base/connection'];
  200. const { tenant } = state['features/base/jwt'];
  201. const { email, name: nick } = getLocalParticipant(state) ?? {};
  202. const options: any = { ...config };
  203. if (tenant) {
  204. options.siteID = tenant;
  205. }
  206. if (options.enableDisplayNameInStats && nick) {
  207. options.statisticsDisplayName = nick;
  208. }
  209. if (options.enableEmailInStats && email) {
  210. options.statisticsId = email;
  211. }
  212. if (locationURL) {
  213. options.confID = `${locationURL.host}${getBackendSafePath(locationURL.pathname)}`;
  214. }
  215. options.applicationName = getName();
  216. options.transcriptionLanguage = determineTranscriptionLanguage(options);
  217. // Disable analytics, if requested.
  218. if (options.disableThirdPartyRequests) {
  219. delete config.analytics?.scriptURLs;
  220. delete config.analytics?.amplitudeAPPKey;
  221. delete config.analytics?.googleAnalyticsTrackingId;
  222. delete options.callStatsID;
  223. delete options.callStatsSecret;
  224. }
  225. return options;
  226. }
  227. /**
  228. * Override the global config (that is, window.config) with XMPP configuration required to join as a visitor.
  229. *
  230. * @param {IStateful} stateful - The redux store state.
  231. * @param {Array<string>} params - The received parameters.
  232. * @returns {void}
  233. */
  234. export function generateVisitorConfig(stateful: IStateful, params: Array<string>) {
  235. const [ vnode, focusJid ] = params;
  236. const config = toState(stateful)['features/base/config'];
  237. if (!config || !config.hosts) {
  238. logger.warn('Wrong configuration, missing hosts.');
  239. return;
  240. }
  241. const oldDomain = config.hosts.domain;
  242. config.hosts.domain = `${vnode}.meet.jitsi`;
  243. config.hosts.muc = config.hosts.muc.replace(oldDomain, config.hosts.domain);
  244. config.focusUserJid = focusJid;
  245. // This flag disables sending the initial conference request
  246. config.disableFocus = true;
  247. if (config.bosh) {
  248. config.bosh = appendURLParam(config.bosh, 'vnode', vnode);
  249. }
  250. if (config.websocket) {
  251. config.websocket = appendURLParam(config.websocket, 'vnode', vnode);
  252. }
  253. }
  254. /**
  255. * Returns the UTC timestamp when the first participant joined the conference.
  256. *
  257. * @param {IStateful} stateful - Reference that can be resolved to Redux
  258. * state with the {@code toState} function.
  259. * @returns {number}
  260. */
  261. export function getConferenceTimestamp(stateful: IStateful) {
  262. const state = toState(stateful);
  263. const { conferenceTimestamp } = getConferenceState(state);
  264. return conferenceTimestamp;
  265. }
  266. /**
  267. * Returns the current {@code JitsiConference} which is joining or joined and is
  268. * not leaving. Please note the contrast with merely reading the
  269. * {@code conference} state of the feature base/conference which is not joining
  270. * but may be leaving already.
  271. *
  272. * @param {IStateful} stateful - The redux store, state, or
  273. * {@code getState} function.
  274. * @returns {JitsiConference|undefined}
  275. */
  276. export function getCurrentConference(stateful: IStateful): any {
  277. const { conference, joining, leaving, membersOnly, passwordRequired }
  278. = getConferenceState(toState(stateful));
  279. // There is a precedence
  280. if (conference) {
  281. return conference === leaving ? undefined : conference;
  282. }
  283. return joining || passwordRequired || membersOnly;
  284. }
  285. /**
  286. * Returns the stored room name.
  287. *
  288. * @param {IReduxState} state - The current state of the app.
  289. * @returns {string}
  290. */
  291. export function getRoomName(state: IReduxState) {
  292. return getConferenceState(state).room;
  293. }
  294. /**
  295. * Get an obfuscated room name or create and persist it if it doesn't exists.
  296. *
  297. * @param {IReduxState} state - The current state of the app.
  298. * @param {Function} dispatch - The Redux dispatch function.
  299. * @returns {string} - Obfuscated room name.
  300. */
  301. export function getOrCreateObfuscatedRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  302. let { obfuscatedRoom } = getConferenceState(state);
  303. const { obfuscatedRoomSource } = getConferenceState(state);
  304. const room = getRoomName(state);
  305. if (!room) {
  306. return;
  307. }
  308. // On native mobile the store doesn't clear when joining a new conference so we might have the obfuscatedRoom
  309. // stored even though a different room was joined.
  310. // Check if the obfuscatedRoom was already computed for the current room.
  311. if (!obfuscatedRoom || (obfuscatedRoomSource !== room)) {
  312. obfuscatedRoom = sha512(room);
  313. dispatch(setObfuscatedRoom(obfuscatedRoom, room));
  314. }
  315. return obfuscatedRoom;
  316. }
  317. /**
  318. * Analytics may require an obfuscated room name, this functions decides based on a config if the normal or
  319. * obfuscated room name should be returned.
  320. *
  321. * @param {IReduxState} state - The current state of the app.
  322. * @param {Function} dispatch - The Redux dispatch function.
  323. * @returns {string} - Analytics room name.
  324. */
  325. export function getAnalyticsRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  326. const { analysis: { obfuscateRoomName = false } = {} } = state['features/base/config'];
  327. if (obfuscateRoomName) {
  328. return getOrCreateObfuscatedRoomName(state, dispatch);
  329. }
  330. return getRoomName(state);
  331. }
  332. /**
  333. * Handle an error thrown by the backend (i.e. {@code lib-jitsi-meet}) while
  334. * manipulating a conference participant (e.g. Pin or select participant).
  335. *
  336. * @param {Error} err - The Error which was thrown by the backend while
  337. * manipulating a conference participant and which is to be handled.
  338. * @protected
  339. * @returns {void}
  340. */
  341. export function _handleParticipantError(err: Error) {
  342. // XXX DataChannels are initialized at some later point when the conference
  343. // has multiple participants, but code that pins or selects a participant
  344. // might be executed before. So here we're swallowing a particular error.
  345. // TODO Lib-jitsi-meet should be fixed to not throw such an exception in
  346. // these scenarios.
  347. if (err.message !== 'Data channels support is disabled!') {
  348. throw err;
  349. }
  350. }
  351. /**
  352. * Determines whether a specific string is a valid room name.
  353. *
  354. * @param {(string|undefined)} room - The name of the conference room to check
  355. * for validity.
  356. * @returns {boolean} If the specified room name is valid, then true; otherwise,
  357. * false.
  358. */
  359. export function isRoomValid(room?: string) {
  360. return typeof room === 'string' && room !== '';
  361. }
  362. /**
  363. * Remove a set of local tracks from a conference.
  364. *
  365. * @param {JitsiConference} conference - Conference instance.
  366. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  367. * @protected
  368. * @returns {Promise}
  369. */
  370. export function _removeLocalTracksFromConference(
  371. conference: IJitsiConference,
  372. localTracks: Array<Object>) {
  373. return Promise.all(localTracks.map(track =>
  374. conference.removeTrack(track)
  375. .catch((err: Error) => {
  376. // Local track might be already disposed by direct
  377. // JitsiTrack#dispose() call. So we should ignore this error
  378. // here.
  379. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  380. _reportError(
  381. 'Failed to remove local track from conference',
  382. err);
  383. }
  384. })
  385. ));
  386. }
  387. /**
  388. * Reports a specific Error with a specific error message. While the
  389. * implementation merely logs the specified msg and err via the console at the
  390. * time of this writing, the intention of the function is to abstract the
  391. * reporting of errors and facilitate elaborating on it in the future.
  392. *
  393. * @param {string} msg - The error message to report.
  394. * @param {Error} err - The Error to report.
  395. * @private
  396. * @returns {void}
  397. */
  398. function _reportError(msg: string, err: Error) {
  399. // TODO This is a good point to call some global error handler when we have
  400. // one.
  401. logger.error(msg, err);
  402. }
  403. /**
  404. * Sends a representation of the local participant such as her avatar (URL),
  405. * email address, and display name to (the remote participants of) a specific
  406. * conference.
  407. *
  408. * @param {Function|Object} stateful - The redux store, state, or
  409. * {@code getState} function.
  410. * @param {JitsiConference} conference - The {@code JitsiConference} to which
  411. * the representation of the local participant is to be sent.
  412. * @returns {void}
  413. */
  414. export function sendLocalParticipant(
  415. stateful: IStateful,
  416. conference: IJitsiConference) {
  417. const {
  418. avatarURL,
  419. email,
  420. features,
  421. name
  422. } = getLocalParticipant(stateful) ?? {};
  423. avatarURL && conference?.sendCommand(AVATAR_URL_COMMAND, {
  424. value: avatarURL
  425. });
  426. email && conference?.sendCommand(EMAIL_COMMAND, {
  427. value: email
  428. });
  429. if (features && features['screen-sharing'] === 'true') {
  430. conference?.setLocalParticipantProperty('features_screen-sharing', true);
  431. }
  432. conference?.setDisplayName(name);
  433. }
  434. /**
  435. * A safe implementation of lodash#startCase that doesn't deburr the string.
  436. *
  437. * NOTE: According to lodash roadmap, lodash v5 will have this function.
  438. *
  439. * Code based on https://github.com/lodash/lodash/blob/master/startCase.js.
  440. *
  441. * @param {string} s - The string to do start case on.
  442. * @returns {string}
  443. */
  444. function safeStartCase(s = '') {
  445. return _.words(`${s}`.replace(/['\u2019]/g, '')).reduce(
  446. (result, word, index) => result + (index ? ' ' : '') + _.upperFirst(word)
  447. , '');
  448. }