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

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