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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. // @flow
  2. import { sha512_256 as sha512 } from 'js-sha512';
  3. import _ from 'lodash';
  4. import { getName } from '../../app/functions';
  5. import { determineTranscriptionLanguage } from '../../transcribing/functions';
  6. import { JitsiTrackErrors } from '../lib-jitsi-meet';
  7. import {
  8. getLocalParticipant,
  9. hiddenParticipantJoined,
  10. hiddenParticipantLeft,
  11. participantJoined,
  12. participantLeft
  13. } from '../participants';
  14. import { toState } from '../redux';
  15. import {
  16. getBackendSafePath,
  17. getJitsiMeetGlobalNS,
  18. safeDecodeURIComponent
  19. } from '../util';
  20. import { setObfuscatedRoom } from './actions';
  21. import {
  22. AVATAR_URL_COMMAND,
  23. EMAIL_COMMAND,
  24. JITSI_CONFERENCE_URL_KEY
  25. } from './constants';
  26. import logger from './logger';
  27. /**
  28. * Returns root conference state.
  29. *
  30. * @param {Object} state - Global state.
  31. * @returns {Object} Conference state.
  32. */
  33. export const getConferenceState = (state: Object) => state['features/base/conference'];
  34. /**
  35. * Is the conference joined or not.
  36. *
  37. * @param {Object} state - Global state.
  38. * @returns {boolean}
  39. */
  40. export const getIsConferenceJoined = (state: Object) => Boolean(getConferenceState(state).conference);
  41. /**
  42. * Attach a set of local tracks to a conference.
  43. *
  44. * @param {JitsiConference} conference - Conference instance.
  45. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  46. * @protected
  47. * @returns {Promise}
  48. */
  49. export function _addLocalTracksToConference(
  50. conference: { addTrack: Function, getLocalTracks: Function },
  51. localTracks: Array<Object>) {
  52. const conferenceLocalTracks = conference.getLocalTracks();
  53. const promises = [];
  54. for (const track of localTracks) {
  55. // XXX The library lib-jitsi-meet may be draconian, for example, when
  56. // adding one and the same video track multiple times.
  57. if (conferenceLocalTracks.indexOf(track) === -1) {
  58. promises.push(
  59. conference.addTrack(track).catch(err => {
  60. _reportError(
  61. 'Failed to add local track to conference',
  62. err);
  63. }));
  64. }
  65. }
  66. return Promise.all(promises);
  67. }
  68. /**
  69. * Logic shared between web and RN which processes the {@code USER_JOINED}
  70. * conference event and dispatches either {@link participantJoined} or
  71. * {@link hiddenParticipantJoined}.
  72. *
  73. * @param {Object} store - The redux store.
  74. * @param {JitsiMeetConference} conference - The conference for which the
  75. * {@code USER_JOINED} event is being processed.
  76. * @param {JitsiParticipant} user - The user who has just joined.
  77. * @returns {void}
  78. */
  79. export function commonUserJoinedHandling(
  80. { dispatch }: Object,
  81. conference: Object,
  82. user: Object) {
  83. const id = user.getId();
  84. const displayName = user.getDisplayName();
  85. if (user.isHidden()) {
  86. dispatch(hiddenParticipantJoined(id, displayName));
  87. } else {
  88. const isReplacing = user.isReplacing && user.isReplacing();
  89. dispatch(participantJoined({
  90. botType: user.getBotType(),
  91. connectionStatus: user.getConnectionStatus(),
  92. conference,
  93. id,
  94. name: displayName,
  95. presence: user.getStatus(),
  96. role: user.getRole(),
  97. isReplacing
  98. }));
  99. }
  100. }
  101. /**
  102. * Logic shared between web and RN which processes the {@code USER_LEFT}
  103. * conference event and dispatches either {@link participantLeft} or
  104. * {@link hiddenParticipantLeft}.
  105. *
  106. * @param {Object} store - The redux store.
  107. * @param {JitsiMeetConference} conference - The conference for which the
  108. * {@code USER_LEFT} event is being processed.
  109. * @param {JitsiParticipant} user - The user who has just left.
  110. * @returns {void}
  111. */
  112. export function commonUserLeftHandling(
  113. { dispatch }: Object,
  114. conference: Object,
  115. user: Object) {
  116. const id = user.getId();
  117. if (user.isHidden()) {
  118. dispatch(hiddenParticipantLeft(id));
  119. } else {
  120. const isReplaced = user.isReplaced && user.isReplaced();
  121. dispatch(participantLeft(id, conference, isReplaced));
  122. }
  123. }
  124. /**
  125. * Evaluates a specific predicate for each {@link JitsiConference} known to the
  126. * redux state features/base/conference while it returns {@code true}.
  127. *
  128. * @param {Function | Object} stateful - The redux store, state, or
  129. * {@code getState} function.
  130. * @param {Function} predicate - The predicate to evaluate for each
  131. * {@code JitsiConference} know to the redux state features/base/conference
  132. * while it returns {@code true}.
  133. * @returns {boolean} If the specified {@code predicate} returned {@code true}
  134. * for all {@code JitsiConference} instances known to the redux state
  135. * features/base/conference.
  136. */
  137. export function forEachConference(
  138. stateful: Function | Object,
  139. predicate: (Object, URL) => boolean) {
  140. const state = getConferenceState(toState(stateful));
  141. for (const v of Object.values(state)) {
  142. // Does the value of the base/conference's property look like a
  143. // JitsiConference?
  144. if (v && typeof v === 'object') {
  145. // $FlowFixMe
  146. const url: URL = v[JITSI_CONFERENCE_URL_KEY];
  147. // XXX The Web version of Jitsi Meet does not utilize
  148. // JITSI_CONFERENCE_URL_KEY at the time of this writing. An
  149. // alternative is necessary then to recognize JitsiConference
  150. // instances and myUserId is as good as any other property.
  151. if ((url || typeof v.myUserId === 'function')
  152. && !predicate(v, url)) {
  153. return false;
  154. }
  155. }
  156. }
  157. return true;
  158. }
  159. /**
  160. * Returns the display name of the conference.
  161. *
  162. * @param {Function | Object} stateful - Reference that can be resolved to Redux
  163. * state with the {@code toState} function.
  164. * @returns {string}
  165. */
  166. export function getConferenceName(stateful: Function | Object): string {
  167. const state = toState(stateful);
  168. const { callee } = state['features/base/jwt'];
  169. const { callDisplayName } = state['features/base/config'];
  170. const { localSubject, room, subject } = getConferenceState(state);
  171. return localSubject
  172. || subject
  173. || callDisplayName
  174. || (callee && callee.name)
  175. || safeStartCase(safeDecodeURIComponent(room));
  176. }
  177. /**
  178. * Returns the name of the conference formatted for the title.
  179. *
  180. * @param {Function | Object} 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: Function | Object) {
  185. return safeStartCase(safeDecodeURIComponent(getConferenceState(toState(stateful)).room));
  186. }
  187. /**
  188. * Returns an object aggregating the conference options.
  189. *
  190. * @param {Object|Function} stateful - The redux store state.
  191. * @returns {Object} - Options object.
  192. */
  193. export function getConferenceOptions(stateful: Function | Object) {
  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 = { ...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 {Function | Object} stateful - Reference that can be resolved to Redux
  230. * state with the {@code toState} function.
  231. * @returns {number}
  232. */
  233. export function getConferenceTimestamp(stateful: Function | Object): number {
  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 {Function|Object} stateful - The redux store, state, or
  245. * {@code getState} function.
  246. * @returns {JitsiConference|undefined}
  247. */
  248. export function getCurrentConference(stateful: Function | Object) {
  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 {Object} state - The current state of the app.
  261. * @returns {string}
  262. */
  263. export function getRoomName(state: Object): string {
  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 {Object} 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: Object, dispatch: Function) {
  274. let { obfuscatedRoom } = getConferenceState(state);
  275. const { obfuscatedRoomSource } = getConferenceState(state);
  276. const room = getRoomName(state);
  277. // On native mobile the store doesn't clear when joining a new conference so we might have the obfuscatedRoom
  278. // stored even though a different room was joined.
  279. // Check if the obfuscatedRoom was already computed for the current room.
  280. if (!obfuscatedRoom || (obfuscatedRoomSource !== room)) {
  281. obfuscatedRoom = sha512(room);
  282. dispatch(setObfuscatedRoom(obfuscatedRoom, room));
  283. }
  284. return obfuscatedRoom;
  285. }
  286. /**
  287. * Analytics may require an obfuscated room name, this functions decides based on a config if the normal or
  288. * obfuscated room name should be returned.
  289. *
  290. * @param {Object} state - The current state of the app.
  291. * @param {Function} dispatch - The Redux dispatch function.
  292. * @returns {string} - Analytics room name.
  293. */
  294. export function getAnalyticsRoomName(state: Object, dispatch: Function) {
  295. const { analysis: { obfuscateRoomName = false } = {} } = state['features/base/config'];
  296. if (obfuscateRoomName) {
  297. return getOrCreateObfuscatedRoomName(state, dispatch);
  298. }
  299. return getRoomName(state);
  300. }
  301. /**
  302. * Returns the result of getWiFiStats from the global NS or does nothing
  303. * (returns empty result).
  304. * Fixes a concurrency problem where we need to pass a function when creating
  305. * a JitsiConference, but that method is added to the context later.
  306. *
  307. * @returns {Promise}
  308. * @private
  309. */
  310. function getWiFiStatsMethod() {
  311. const gloabalNS = getJitsiMeetGlobalNS();
  312. return gloabalNS.getWiFiStats ? gloabalNS.getWiFiStats() : Promise.resolve('{}');
  313. }
  314. /**
  315. * Handle an error thrown by the backend (i.e. {@code lib-jitsi-meet}) while
  316. * manipulating a conference participant (e.g. Pin or select participant).
  317. *
  318. * @param {Error} err - The Error which was thrown by the backend while
  319. * manipulating a conference participant and which is to be handled.
  320. * @protected
  321. * @returns {void}
  322. */
  323. export function _handleParticipantError(err: { message: ?string }) {
  324. // XXX DataChannels are initialized at some later point when the conference
  325. // has multiple participants, but code that pins or selects a participant
  326. // might be executed before. So here we're swallowing a particular error.
  327. // TODO Lib-jitsi-meet should be fixed to not throw such an exception in
  328. // these scenarios.
  329. if (err.message !== 'Data channels support is disabled!') {
  330. throw err;
  331. }
  332. }
  333. /**
  334. * Determines whether a specific string is a valid room name.
  335. *
  336. * @param {(string|undefined)} room - The name of the conference room to check
  337. * for validity.
  338. * @returns {boolean} If the specified room name is valid, then true; otherwise,
  339. * false.
  340. */
  341. export function isRoomValid(room: ?string) {
  342. return typeof room === 'string' && room !== '';
  343. }
  344. /**
  345. * Remove a set of local tracks from a conference.
  346. *
  347. * @param {JitsiConference} conference - Conference instance.
  348. * @param {JitsiLocalTrack[]} localTracks - List of local media tracks.
  349. * @protected
  350. * @returns {Promise}
  351. */
  352. export function _removeLocalTracksFromConference(
  353. conference: { removeTrack: Function },
  354. localTracks: Array<Object>) {
  355. return Promise.all(localTracks.map(track =>
  356. conference.removeTrack(track)
  357. .catch(err => {
  358. // Local track might be already disposed by direct
  359. // JitsiTrack#dispose() call. So we should ignore this error
  360. // here.
  361. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  362. _reportError(
  363. 'Failed to remove local track from conference',
  364. err);
  365. }
  366. })
  367. ));
  368. }
  369. /**
  370. * Reports a specific Error with a specific error message. While the
  371. * implementation merely logs the specified msg and err via the console at the
  372. * time of this writing, the intention of the function is to abstract the
  373. * reporting of errors and facilitate elaborating on it in the future.
  374. *
  375. * @param {string} msg - The error message to report.
  376. * @param {Error} err - The Error to report.
  377. * @private
  378. * @returns {void}
  379. */
  380. function _reportError(msg, err) {
  381. // TODO This is a good point to call some global error handler when we have
  382. // one.
  383. logger.error(msg, err);
  384. }
  385. /**
  386. * Sends a representation of the local participant such as her avatar (URL),
  387. * email address, and display name to (the remote participants of) a specific
  388. * conference.
  389. *
  390. * @param {Function|Object} stateful - The redux store, state, or
  391. * {@code getState} function.
  392. * @param {JitsiConference} conference - The {@code JitsiConference} to which
  393. * the representation of the local participant is to be sent.
  394. * @returns {void}
  395. */
  396. export function sendLocalParticipant(
  397. stateful: Function | Object,
  398. conference: {
  399. sendCommand: Function,
  400. setDisplayName: Function,
  401. setLocalParticipantProperty: Function }) {
  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. }