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

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