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.

actions.js 22KB

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