您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

functions.js 12KB

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