Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

functions.ts 19KB

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