您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

functions.ts 19KB

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