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

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