Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

functions.ts 18KB

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