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

functions.ts 16KB

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