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.js 14KB

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