Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

functions.ts 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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?.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. // not updating disableFocus, as if the room capacity is full the promotion to the main room will fail
  267. // and the visitor will be redirected back to a vnode from jicofo
  268. if (config.oldConfig && username) {
  269. return {
  270. hosts: config.oldConfig.hosts,
  271. focusUserJid: focusJid,
  272. disableLocalStats: false,
  273. bosh: config.oldConfig.bosh && appendURLParam(config.oldConfig.bosh, 'customusername', username),
  274. p2p: config.oldConfig.p2p,
  275. websocket: config.oldConfig.websocket
  276. && appendURLParam(config.oldConfig.websocket, 'customusername', username),
  277. oldConfig: undefined // clears it up
  278. };
  279. }
  280. return;
  281. }
  282. const oldConfig = {
  283. hosts: {
  284. domain: ''
  285. },
  286. focusUserJid: config.focusUserJid,
  287. bosh: config.bosh,
  288. p2p: config.p2p,
  289. websocket: config.websocket
  290. };
  291. // copy original hosts, to make sure we do not use a modified one later
  292. Object.assign(oldConfig.hosts, config.hosts);
  293. const domain = `${vnode}.meet.jitsi`;
  294. return {
  295. oldConfig,
  296. hosts: {
  297. domain,
  298. muc: config.hosts.muc.replace(oldConfig.hosts.domain, domain)
  299. },
  300. focusUserJid: focusJid,
  301. disableFocus: true, // This flag disables sending the initial conference request
  302. disableLocalStats: true,
  303. bosh: config.bosh && appendURLParam(config.bosh, 'vnode', vnode),
  304. p2p: {
  305. ...config.p2p,
  306. enabled: false
  307. },
  308. websocket: config.websocket && appendURLParam(config.websocket, 'vnode', vnode)
  309. };
  310. }
  311. /**
  312. * Returns the UTC timestamp when the first participant joined the conference.
  313. *
  314. * @param {IStateful} stateful - Reference that can be resolved to Redux
  315. * state with the {@code toState} function.
  316. * @returns {number}
  317. */
  318. export function getConferenceTimestamp(stateful: IStateful) {
  319. const state = toState(stateful);
  320. const { conferenceTimestamp } = getConferenceState(state);
  321. return conferenceTimestamp;
  322. }
  323. /**
  324. * Returns the current {@code JitsiConference} which is joining or joined and is
  325. * not leaving. Please note the contrast with merely reading the
  326. * {@code conference} state of the feature base/conference which is not joining
  327. * but may be leaving already.
  328. *
  329. * @param {IStateful} stateful - The redux store, state, or
  330. * {@code getState} function.
  331. * @returns {JitsiConference|undefined}
  332. */
  333. export function getCurrentConference(stateful: IStateful): IJitsiConference | undefined {
  334. const { conference, joining, leaving, membersOnly, passwordRequired }
  335. = getConferenceState(toState(stateful));
  336. // There is a precedence
  337. if (conference) {
  338. return conference === leaving ? undefined : conference;
  339. }
  340. return joining || passwordRequired || membersOnly;
  341. }
  342. /**
  343. * Returns whether the current conference is a P2P connection.
  344. * Will return `false` if it's a JVB one, and `null` if there is no conference.
  345. *
  346. * @param {IStateful} stateful - The redux store, state, or
  347. * {@code getState} function.
  348. * @returns {boolean|null}
  349. */
  350. export function isP2pActive(stateful: IStateful): boolean | null {
  351. const conference = getCurrentConference(toState(stateful));
  352. if (!conference) {
  353. return null;
  354. }
  355. return conference.isP2PActive();
  356. }
  357. /**
  358. * Returns the stored room name.
  359. *
  360. * @param {IReduxState} state - The current state of the app.
  361. * @returns {string}
  362. */
  363. export function getRoomName(state: IReduxState) {
  364. return getConferenceState(state).room;
  365. }
  366. /**
  367. * Get an obfuscated room name or create and persist it if it doesn't exists.
  368. *
  369. * @param {IReduxState} state - The current state of the app.
  370. * @param {Function} dispatch - The Redux dispatch function.
  371. * @returns {string} - Obfuscated room name.
  372. */
  373. export function getOrCreateObfuscatedRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  374. let { obfuscatedRoom } = getConferenceState(state);
  375. const { obfuscatedRoomSource } = getConferenceState(state);
  376. const room = getRoomName(state);
  377. if (!room) {
  378. return;
  379. }
  380. // On native mobile the store doesn't clear when joining a new conference so we might have the obfuscatedRoom
  381. // stored even though a different room was joined.
  382. // Check if the obfuscatedRoom was already computed for the current room.
  383. if (!obfuscatedRoom || (obfuscatedRoomSource !== room)) {
  384. obfuscatedRoom = sha512(room);
  385. dispatch(setObfuscatedRoom(obfuscatedRoom, room));
  386. }
  387. return obfuscatedRoom;
  388. }
  389. /**
  390. * Analytics may require an obfuscated room name, this functions decides based on a config if the normal or
  391. * obfuscated room name should be returned.
  392. *
  393. * @param {IReduxState} state - The current state of the app.
  394. * @param {Function} dispatch - The Redux dispatch function.
  395. * @returns {string} - Analytics room name.
  396. */
  397. export function getAnalyticsRoomName(state: IReduxState, dispatch: IStore['dispatch']) {
  398. const { analysis: { obfuscateRoomName = false } = {} } = state['features/base/config'];
  399. if (obfuscateRoomName) {
  400. return getOrCreateObfuscatedRoomName(state, dispatch);
  401. }
  402. return getRoomName(state);
  403. }
  404. /**
  405. * Handle an error thrown by the backend (i.e. {@code lib-jitsi-meet}) while
  406. * manipulating a conference participant (e.g. Pin or select participant).
  407. *
  408. * @param {Error} err - The Error which was thrown by the backend while
  409. * manipulating a conference participant and which is to be handled.
  410. * @protected
  411. * @returns {void}
  412. */
  413. export function _handleParticipantError(err: Error) {
  414. // XXX DataChannels are initialized at some later point when the conference
  415. // has multiple participants, but code that pins or selects a participant
  416. // might be executed before. So here we're swallowing a particular error.
  417. // TODO Lib-jitsi-meet should be fixed to not throw such an exception in
  418. // these scenarios.
  419. if (err.message !== 'Data channels support is disabled!') {
  420. throw err;
  421. }
  422. }
  423. /**
  424. * Determines whether a specific string is a valid room name.
  425. *
  426. * @param {(string|undefined)} room - The name of the conference room to check
  427. * for validity.
  428. * @returns {boolean} If the specified room name is valid, then true; otherwise,
  429. * false.
  430. */
  431. export function isRoomValid(room?: string) {
  432. return typeof room === 'string' && room !== '';
  433. }
  434. /**
  435. * Remove a set of local tracks from a conference.
  436. *
  437. * @param {JitsiConference} conference - Conference instance.
  438. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  439. * @protected
  440. * @returns {Promise}
  441. */
  442. export function _removeLocalTracksFromConference(
  443. conference: IJitsiConference,
  444. localTracks: Array<Object>) {
  445. return Promise.all(localTracks.map(track =>
  446. conference.removeTrack(track)
  447. .catch((err: Error) => {
  448. // Local track might be already disposed by direct
  449. // JitsiTrack#dispose() call. So we should ignore this error
  450. // here.
  451. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  452. _reportError(
  453. 'Failed to remove local track from conference',
  454. err);
  455. }
  456. })
  457. ));
  458. }
  459. /**
  460. * Reports a specific Error with a specific error message. While the
  461. * implementation merely logs the specified msg and err via the console at the
  462. * time of this writing, the intention of the function is to abstract the
  463. * reporting of errors and facilitate elaborating on it in the future.
  464. *
  465. * @param {string} msg - The error message to report.
  466. * @param {Error} err - The Error to report.
  467. * @private
  468. * @returns {void}
  469. */
  470. function _reportError(msg: string, err: Error) {
  471. // TODO This is a good point to call some global error handler when we have
  472. // one.
  473. logger.error(msg, err);
  474. }
  475. /**
  476. * Sends a representation of the local participant such as her avatar (URL),
  477. * email address, and display name to (the remote participants of) a specific
  478. * conference.
  479. *
  480. * @param {Function|Object} stateful - The redux store, state, or
  481. * {@code getState} function.
  482. * @param {JitsiConference} conference - The {@code JitsiConference} to which
  483. * the representation of the local participant is to be sent.
  484. * @returns {void}
  485. */
  486. export function sendLocalParticipant(
  487. stateful: IStateful,
  488. conference?: IJitsiConference) {
  489. const {
  490. avatarURL,
  491. email,
  492. features,
  493. name
  494. } = getLocalParticipant(stateful) ?? {};
  495. avatarURL && conference?.sendCommand(AVATAR_URL_COMMAND, {
  496. value: avatarURL
  497. });
  498. email && conference?.sendCommand(EMAIL_COMMAND, {
  499. value: email
  500. });
  501. if (features && features['screen-sharing'] === 'true') {
  502. conference?.setLocalParticipantProperty('features_screen-sharing', true);
  503. }
  504. conference?.setDisplayName(name);
  505. }
  506. /**
  507. * A safe implementation of lodash#startCase that doesn't deburr the string.
  508. *
  509. * NOTE: According to lodash roadmap, lodash v5 will have this function.
  510. *
  511. * Code based on https://github.com/lodash/lodash/blob/master/startCase.js.
  512. *
  513. * @param {string} s - The string to do start case on.
  514. * @returns {string}
  515. */
  516. function safeStartCase(s = '') {
  517. return _.words(`${s}`.replace(/['\u2019]/g, '')).reduce(
  518. (result, word, index) => result + (index ? ' ' : '') + _.upperFirst(word)
  519. , '');
  520. }