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

actions.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. import {
  2. createTrackMutedEvent,
  3. sendAnalytics
  4. } from '../../analytics';
  5. import { JitsiTrackErrors, JitsiTrackEvents } from '../lib-jitsi-meet';
  6. import { showErrorNotification, showNotification } from '../../notifications';
  7. import {
  8. CAMERA_FACING_MODE,
  9. MEDIA_TYPE,
  10. setAudioMuted,
  11. setVideoMuted,
  12. VIDEO_MUTISM_AUTHORITY
  13. } from '../media';
  14. import { getLocalParticipant } from '../participants';
  15. import {
  16. TOGGLE_SCREENSHARING,
  17. TRACK_ADDED,
  18. TRACK_CREATE_CANCELED,
  19. TRACK_CREATE_ERROR,
  20. TRACK_NO_DATA_FROM_SOURCE,
  21. TRACK_REMOVED,
  22. TRACK_UPDATED,
  23. TRACK_WILL_CREATE
  24. } from './actionTypes';
  25. import { createLocalTracksF, getLocalTrack, getLocalTracks, getTrackByJitsiTrack } from './functions';
  26. const logger = require('jitsi-meet-logger').getLogger(__filename);
  27. /**
  28. * Requests the creating of the desired media type tracks. Desire is expressed
  29. * by base/media unless the function caller specifies desired media types
  30. * explicitly and thus override base/media. Dispatches a
  31. * {@code createLocalTracksA} action for the desired media types for which there
  32. * are no existing tracks yet.
  33. *
  34. * @returns {Function}
  35. */
  36. export function createDesiredLocalTracks(...desiredTypes) {
  37. return (dispatch, getState) => {
  38. const state = getState();
  39. if (desiredTypes.length === 0) {
  40. const { audio, video } = state['features/base/media'];
  41. audio.muted || desiredTypes.push(MEDIA_TYPE.AUDIO);
  42. // XXX When the app is coming into the foreground from the
  43. // background in order to handle a URL, it may realize the new
  44. // background state soon after it has tried to create the local
  45. // tracks requested by the URL. Ignore
  46. // VIDEO_MUTISM_AUTHORITY.BACKGROUND and create the local video
  47. // track if no other VIDEO_MUTISM_AUTHORITY has muted it. The local
  48. // video track will be muted until the app realizes the new
  49. // background state.
  50. // eslint-disable-next-line no-bitwise
  51. (video.muted & ~VIDEO_MUTISM_AUTHORITY.BACKGROUND)
  52. || desiredTypes.push(MEDIA_TYPE.VIDEO);
  53. }
  54. const availableTypes
  55. = getLocalTracks(
  56. state['features/base/tracks'],
  57. /* includePending */ true)
  58. .map(t => t.mediaType);
  59. // We need to create the desired tracks which are not already available.
  60. const createTypes
  61. = desiredTypes.filter(type => availableTypes.indexOf(type) === -1);
  62. createTypes.length
  63. && dispatch(createLocalTracksA({ devices: createTypes }));
  64. };
  65. }
  66. /**
  67. * Request to start capturing local audio and/or video. By default, the user
  68. * facing camera will be selected.
  69. *
  70. * @param {Object} [options] - For info @see JitsiMeetJS.createLocalTracks.
  71. * @returns {Function}
  72. */
  73. export function createLocalTracksA(options = {}) {
  74. return (dispatch, getState) => {
  75. const devices
  76. = options.devices || [ MEDIA_TYPE.AUDIO, MEDIA_TYPE.VIDEO ];
  77. const store = {
  78. dispatch,
  79. getState
  80. };
  81. // The following executes on React Native only at the time of this
  82. // writing. The effort to port Web's createInitialLocalTracksAndConnect
  83. // is significant and that's where the function createLocalTracksF got
  84. // born. I started with the idea a porting so that we could inherit the
  85. // ability to getUserMedia for audio only or video only if getUserMedia
  86. // for audio and video fails. Eventually though, I realized that on
  87. // mobile we do not have combined permission prompts implemented anyway
  88. // (either because there are no such prompts or it does not make sense
  89. // to implement them) and the right thing to do is to ask for each
  90. // device separately.
  91. for (const device of devices) {
  92. if (getLocalTrack(
  93. getState()['features/base/tracks'],
  94. device,
  95. /* includePending */ true)) {
  96. throw new Error(`Local track for ${device} already exists`);
  97. }
  98. const gumProcess
  99. = createLocalTracksF(
  100. {
  101. cameraDeviceId: options.cameraDeviceId,
  102. devices: [ device ],
  103. facingMode:
  104. options.facingMode || CAMERA_FACING_MODE.USER,
  105. micDeviceId: options.micDeviceId
  106. },
  107. /* firePermissionPromptIsShownEvent */ false,
  108. store)
  109. .then(
  110. localTracks => {
  111. // Because GUM is called for 1 device (which is actually
  112. // a media type 'audio', 'video', 'screen', etc.) we
  113. // should not get more than one JitsiTrack.
  114. if (localTracks.length !== 1) {
  115. throw new Error(
  116. `Expected exactly 1 track, but was given ${
  117. localTracks.length} tracks for device: ${
  118. device}.`);
  119. }
  120. if (gumProcess.canceled) {
  121. return _disposeTracks(localTracks)
  122. .then(() =>
  123. dispatch(_trackCreateCanceled(device)));
  124. }
  125. return dispatch(trackAdded(localTracks[0]));
  126. },
  127. reason =>
  128. dispatch(
  129. gumProcess.canceled
  130. ? _trackCreateCanceled(device)
  131. : _onCreateLocalTracksRejected(
  132. reason,
  133. device)));
  134. /**
  135. * Cancels the {@code getUserMedia} process represented by this
  136. * {@code Promise}.
  137. *
  138. * @returns {Promise} This {@code Promise} i.e. {@code gumProcess}.
  139. */
  140. gumProcess.cancel = () => {
  141. gumProcess.canceled = true;
  142. return gumProcess;
  143. };
  144. dispatch({
  145. type: TRACK_WILL_CREATE,
  146. track: {
  147. gumProcess,
  148. local: true,
  149. mediaType: device
  150. }
  151. });
  152. }
  153. };
  154. }
  155. /**
  156. * Calls JitsiLocalTrack#dispose() on all local tracks ignoring errors when
  157. * track is already disposed. After that signals tracks to be removed.
  158. *
  159. * @returns {Function}
  160. */
  161. export function destroyLocalTracks() {
  162. return (dispatch, getState) => {
  163. // First wait until any getUserMedia in progress is settled and then get
  164. // rid of all local tracks.
  165. _cancelGUMProcesses(getState)
  166. .then(() =>
  167. dispatch(
  168. _disposeAndRemoveTracks(
  169. getState()['features/base/tracks']
  170. .filter(t => t.local)
  171. .map(t => t.jitsiTrack))));
  172. };
  173. }
  174. /**
  175. * Signals that the passed JitsiLocalTrack has triggered a no data from source event.
  176. *
  177. * @param {JitsiLocalTrack} track - The track.
  178. * @returns {{
  179. * type: TRACK_NO_DATA_FROM_SOURCE,
  180. * track: Track
  181. * }}
  182. */
  183. export function noDataFromSource(track) {
  184. return {
  185. type: TRACK_NO_DATA_FROM_SOURCE,
  186. track
  187. };
  188. }
  189. /**
  190. * Displays a no data from source video error if needed.
  191. *
  192. * @param {JitsiLocalTrack} jitsiTrack - The track.
  193. * @returns {Function}
  194. */
  195. export function showNoDataFromSourceVideoError(jitsiTrack) {
  196. return (dispatch, getState) => {
  197. let notificationInfo;
  198. const track = getTrackByJitsiTrack(getState()['features/base/tracks'], jitsiTrack);
  199. if (!track) {
  200. return;
  201. }
  202. if (track.isReceivingData) {
  203. notificationInfo = undefined;
  204. } else {
  205. const notificationAction = showErrorNotification({
  206. descriptionKey: 'dialog.cameraNotSendingData',
  207. titleKey: 'dialog.cameraNotSendingDataTitle'
  208. });
  209. dispatch(notificationAction);
  210. notificationInfo = {
  211. uid: notificationAction.uid
  212. };
  213. }
  214. dispatch(trackNoDataFromSourceNotificationInfoChanged(jitsiTrack, notificationInfo));
  215. };
  216. }
  217. /**
  218. * Signals that the local participant is ending screensharing or beginning the
  219. * screensharing flow.
  220. *
  221. * @returns {{
  222. * type: TOGGLE_SCREENSHARING,
  223. * }}
  224. */
  225. export function toggleScreensharing() {
  226. return {
  227. type: TOGGLE_SCREENSHARING
  228. };
  229. }
  230. /**
  231. * Replaces one track with another for one renegotiation instead of invoking
  232. * two renegotiations with a separate removeTrack and addTrack. Disposes the
  233. * removed track as well.
  234. *
  235. * @param {JitsiLocalTrack|null} oldTrack - The track to dispose.
  236. * @param {JitsiLocalTrack|null} newTrack - The track to use instead.
  237. * @param {JitsiConference} [conference] - The conference from which to remove
  238. * and add the tracks. If one is not provided, the conference in the redux store
  239. * will be used.
  240. * @returns {Function}
  241. */
  242. export function replaceLocalTrack(oldTrack, newTrack, conference) {
  243. return (dispatch, getState) => {
  244. conference
  245. // eslint-disable-next-line no-param-reassign
  246. || (conference = getState()['features/base/conference'].conference);
  247. return conference.replaceTrack(oldTrack, newTrack)
  248. .then(() => {
  249. // We call dispose after doing the replace because dispose will
  250. // try and do a new o/a after the track removes itself. Doing it
  251. // after means the JitsiLocalTrack.conference is already
  252. // cleared, so it won't try and do the o/a.
  253. const disposePromise
  254. = oldTrack
  255. ? dispatch(_disposeAndRemoveTracks([ oldTrack ]))
  256. : Promise.resolve();
  257. return disposePromise
  258. .then(() => {
  259. if (newTrack) {
  260. // The mute state of the new track should be
  261. // reflected in the app's mute state. For example,
  262. // if the app is currently muted and changing to a
  263. // new track that is not muted, the app's mute
  264. // state should be falsey. As such, emit a mute
  265. // event here to set up the app to reflect the
  266. // track's mute state. If this is not done, the
  267. // current mute state of the app will be reflected
  268. // on the track, not vice-versa.
  269. const setMuted
  270. = newTrack.isVideoTrack()
  271. ? setVideoMuted
  272. : setAudioMuted;
  273. const isMuted = newTrack.isMuted();
  274. sendAnalytics(createTrackMutedEvent(
  275. newTrack.getType(),
  276. 'track.replaced',
  277. isMuted));
  278. logger.log(`Replace ${newTrack.getType()} track - ${
  279. isMuted ? 'muted' : 'unmuted'}`);
  280. return dispatch(setMuted(isMuted));
  281. }
  282. })
  283. .then(() => {
  284. if (newTrack) {
  285. return dispatch(_addTracks([ newTrack ]));
  286. }
  287. });
  288. });
  289. };
  290. }
  291. /**
  292. * Create an action for when a new track has been signaled to be added to the
  293. * conference.
  294. *
  295. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  296. * @returns {{ type: TRACK_ADDED, track: Track }}
  297. */
  298. export function trackAdded(track) {
  299. return (dispatch, getState) => {
  300. track.on(
  301. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  302. () => dispatch(trackMutedChanged(track)));
  303. track.on(
  304. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  305. type => dispatch(trackVideoTypeChanged(track, type)));
  306. // participantId
  307. const local = track.isLocal();
  308. const mediaType = track.getType();
  309. let isReceivingData, noDataFromSourceNotificationInfo, participantId;
  310. if (local) {
  311. const participant = getLocalParticipant(getState);
  312. if (participant) {
  313. participantId = participant.id;
  314. }
  315. isReceivingData = track.isReceivingData();
  316. track.on(JitsiTrackEvents.NO_DATA_FROM_SOURCE, () => dispatch(noDataFromSource({ jitsiTrack: track })));
  317. if (!isReceivingData) {
  318. if (mediaType === MEDIA_TYPE.AUDIO) {
  319. const notificationAction = showNotification({
  320. descriptionKey: 'dialog.micNotSendingData',
  321. titleKey: 'dialog.micNotSendingDataTitle'
  322. });
  323. dispatch(notificationAction);
  324. noDataFromSourceNotificationInfo = { uid: notificationAction.uid };
  325. } else {
  326. const timeout = setTimeout(() => dispatch(showNoDataFromSourceVideoError(track)), 5000);
  327. noDataFromSourceNotificationInfo = { timeout };
  328. }
  329. }
  330. } else {
  331. participantId = track.getParticipantId();
  332. isReceivingData = true;
  333. }
  334. return dispatch({
  335. type: TRACK_ADDED,
  336. track: {
  337. jitsiTrack: track,
  338. isReceivingData,
  339. local,
  340. mediaType,
  341. mirror: _shouldMirror(track),
  342. muted: track.isMuted(),
  343. noDataFromSourceNotificationInfo,
  344. participantId,
  345. videoStarted: false,
  346. videoType: track.videoType
  347. }
  348. });
  349. };
  350. }
  351. /**
  352. * Create an action for when a track's muted state has been signaled to be
  353. * changed.
  354. *
  355. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  356. * @returns {{
  357. * type: TRACK_UPDATED,
  358. * track: Track
  359. * }}
  360. */
  361. export function trackMutedChanged(track) {
  362. return {
  363. type: TRACK_UPDATED,
  364. track: {
  365. jitsiTrack: track,
  366. muted: track.isMuted()
  367. }
  368. };
  369. }
  370. /**
  371. * Create an action for when a track's no data from source notification information changes.
  372. *
  373. * @param {JitsiLocalTrack} track - JitsiTrack instance.
  374. * @param {Object} noDataFromSourceNotificationInfo - Information about no data from source notification.
  375. * @returns {{
  376. * type: TRACK_UPDATED,
  377. * track: Track
  378. * }}
  379. */
  380. export function trackNoDataFromSourceNotificationInfoChanged(track, noDataFromSourceNotificationInfo) {
  381. return {
  382. type: TRACK_UPDATED,
  383. track: {
  384. jitsiTrack: track,
  385. noDataFromSourceNotificationInfo
  386. }
  387. };
  388. }
  389. /**
  390. * Create an action for when a track has been signaled for removal from the
  391. * conference.
  392. *
  393. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  394. * @returns {{
  395. * type: TRACK_REMOVED,
  396. * track: Track
  397. * }}
  398. */
  399. export function trackRemoved(track) {
  400. track.removeAllListeners(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  401. track.removeAllListeners(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED);
  402. track.removeAllListeners(JitsiTrackEvents.NO_DATA_FROM_SOURCE);
  403. return {
  404. type: TRACK_REMOVED,
  405. track: {
  406. jitsiTrack: track
  407. }
  408. };
  409. }
  410. /**
  411. * Signal that track's video started to play.
  412. *
  413. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  414. * @returns {{
  415. * type: TRACK_UPDATED,
  416. * track: Track
  417. * }}
  418. */
  419. export function trackVideoStarted(track) {
  420. return {
  421. type: TRACK_UPDATED,
  422. track: {
  423. jitsiTrack: track,
  424. videoStarted: true
  425. }
  426. };
  427. }
  428. /**
  429. * Create an action for when participant video type changes.
  430. *
  431. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  432. * @param {VIDEO_TYPE|undefined} videoType - Video type.
  433. * @returns {{
  434. * type: TRACK_UPDATED,
  435. * track: Track
  436. * }}
  437. */
  438. export function trackVideoTypeChanged(track, videoType) {
  439. return {
  440. type: TRACK_UPDATED,
  441. track: {
  442. jitsiTrack: track,
  443. videoType
  444. }
  445. };
  446. }
  447. /**
  448. * Signals passed tracks to be added.
  449. *
  450. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  451. * @private
  452. * @returns {Function}
  453. */
  454. function _addTracks(tracks) {
  455. return dispatch => Promise.all(tracks.map(t => dispatch(trackAdded(t))));
  456. }
  457. /**
  458. * Cancels and waits for any {@code getUserMedia} process/currently in progress
  459. * to complete/settle.
  460. *
  461. * @param {Function} getState - The redux store {@code getState} function used
  462. * to obtain the state.
  463. * @private
  464. * @returns {Promise} - A {@code Promise} resolved once all
  465. * {@code gumProcess.cancel()} {@code Promise}s are settled because all we care
  466. * about here is to be sure that the {@code getUserMedia} callbacks have
  467. * completed (i.e. Returned from the native side).
  468. */
  469. function _cancelGUMProcesses(getState) {
  470. const logError
  471. = error =>
  472. logger.error('gumProcess.cancel failed', JSON.stringify(error));
  473. return Promise.all(
  474. getState()['features/base/tracks']
  475. .filter(t => t.local)
  476. .map(({ gumProcess }) =>
  477. gumProcess && gumProcess.cancel().catch(logError)));
  478. }
  479. /**
  480. * Disposes passed tracks and signals them to be removed.
  481. *
  482. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  483. * @protected
  484. * @returns {Function}
  485. */
  486. export function _disposeAndRemoveTracks(tracks) {
  487. return dispatch =>
  488. _disposeTracks(tracks)
  489. .then(() =>
  490. Promise.all(tracks.map(t => dispatch(trackRemoved(t)))));
  491. }
  492. /**
  493. * Disposes passed tracks.
  494. *
  495. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  496. * @private
  497. * @returns {Promise} - A Promise resolved once {@link JitsiTrack.dispose()} is
  498. * done for every track from the list.
  499. */
  500. function _disposeTracks(tracks) {
  501. return Promise.all(
  502. tracks.map(t =>
  503. t.dispose()
  504. .catch(err => {
  505. // Track might be already disposed so ignore such an error.
  506. // Of course, re-throw any other error(s).
  507. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  508. throw err;
  509. }
  510. })));
  511. }
  512. /**
  513. * Implements the {@code Promise} rejection handler of
  514. * {@code createLocalTracksA} and {@code createLocalTracksF}.
  515. *
  516. * @param {Object} reason - The {@code Promise} rejection reason.
  517. * @param {string} device - The device/{@code MEDIA_TYPE} associated with the
  518. * rejection.
  519. * @private
  520. * @returns {Function}
  521. */
  522. function _onCreateLocalTracksRejected({ gum }, device) {
  523. return dispatch => {
  524. // If permissions are not allowed, alert the user.
  525. if (gum) {
  526. const { error } = gum;
  527. if (error) {
  528. dispatch({
  529. type: TRACK_CREATE_ERROR,
  530. permissionDenied: error.name === 'SecurityError',
  531. trackType: device
  532. });
  533. }
  534. }
  535. };
  536. }
  537. /**
  538. * Returns true if the provided {@code JitsiTrack} should be rendered as a
  539. * mirror.
  540. *
  541. * We only want to show a video in mirrored mode when:
  542. * 1) The video source is local, and not remote.
  543. * 2) The video source is a camera, not a desktop (capture).
  544. * 3) The camera is capturing the user, not the environment.
  545. *
  546. * TODO Similar functionality is part of lib-jitsi-meet. This function should be
  547. * removed after https://github.com/jitsi/lib-jitsi-meet/pull/187 is merged.
  548. *
  549. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  550. * @private
  551. * @returns {boolean}
  552. */
  553. function _shouldMirror(track) {
  554. return (
  555. track
  556. && track.isLocal()
  557. && track.isVideoTrack()
  558. // XXX The type of the return value of JitsiLocalTrack's
  559. // getCameraFacingMode happens to be named CAMERA_FACING_MODE as
  560. // well, it's defined by lib-jitsi-meet. Note though that the type
  561. // of the value on the right side of the equality check is defined
  562. // by jitsi-meet. The type definitions are surely compatible today
  563. // but that may not be the case tomorrow.
  564. && track.getCameraFacingMode() === CAMERA_FACING_MODE.USER);
  565. }
  566. /**
  567. * Signals that track create operation for given media track has been canceled.
  568. * Will clean up local track stub from the redux state which holds the
  569. * {@code gumProcess} reference.
  570. *
  571. * @param {MEDIA_TYPE} mediaType - The type of the media for which the track was
  572. * being created.
  573. * @private
  574. * @returns {{
  575. * type,
  576. * trackType: MEDIA_TYPE
  577. * }}
  578. */
  579. function _trackCreateCanceled(mediaType) {
  580. return {
  581. type: TRACK_CREATE_CANCELED,
  582. trackType: mediaType
  583. };
  584. }