Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import {
  2. createTrackMutedEvent,
  3. sendAnalytics
  4. } from '../../analytics';
  5. import { showErrorNotification, showNotification } from '../../notifications';
  6. import { JitsiTrackErrors, JitsiTrackEvents } from '../lib-jitsi-meet';
  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_NOTIFICATION_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 async (dispatch, getState) => {
  245. conference
  246. // eslint-disable-next-line no-param-reassign
  247. || (conference = getState()['features/base/conference'].conference);
  248. if (conference) {
  249. await conference.replaceTrack(oldTrack, newTrack);
  250. }
  251. return dispatch(replaceStoredTracks(oldTrack, newTrack));
  252. };
  253. }
  254. /**
  255. * Replaces a stored track with another.
  256. *
  257. * @param {JitsiLocalTrack|null} oldTrack - The track to dispose.
  258. * @param {JitsiLocalTrack|null} newTrack - The track to use instead.
  259. * @returns {Function}
  260. */
  261. function replaceStoredTracks(oldTrack, newTrack) {
  262. return dispatch => {
  263. // We call dispose after doing the replace because dispose will
  264. // try and do a new o/a after the track removes itself. Doing it
  265. // after means the JitsiLocalTrack.conference is already
  266. // cleared, so it won't try and do the o/a.
  267. const disposePromise
  268. = oldTrack
  269. ? dispatch(_disposeAndRemoveTracks([ oldTrack ]))
  270. : Promise.resolve();
  271. return disposePromise
  272. .then(() => {
  273. if (newTrack) {
  274. // The mute state of the new track should be
  275. // reflected in the app's mute state. For example,
  276. // if the app is currently muted and changing to a
  277. // new track that is not muted, the app's mute
  278. // state should be falsey. As such, emit a mute
  279. // event here to set up the app to reflect the
  280. // track's mute state. If this is not done, the
  281. // current mute state of the app will be reflected
  282. // on the track, not vice-versa.
  283. const setMuted
  284. = newTrack.isVideoTrack()
  285. ? setVideoMuted
  286. : setAudioMuted;
  287. const isMuted = newTrack.isMuted();
  288. sendAnalytics(createTrackMutedEvent(
  289. newTrack.getType(),
  290. 'track.replaced',
  291. isMuted));
  292. logger.log(`Replace ${newTrack.getType()} track - ${
  293. isMuted ? 'muted' : 'unmuted'}`);
  294. return dispatch(setMuted(isMuted));
  295. }
  296. })
  297. .then(() => {
  298. if (newTrack) {
  299. return dispatch(_addTracks([ newTrack ]));
  300. }
  301. });
  302. };
  303. }
  304. /**
  305. * Create an action for when a new track has been signaled to be added to the
  306. * conference.
  307. *
  308. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  309. * @returns {{ type: TRACK_ADDED, track: Track }}
  310. */
  311. export function trackAdded(track) {
  312. return (dispatch, getState) => {
  313. track.on(
  314. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  315. () => dispatch(trackMutedChanged(track)));
  316. track.on(
  317. JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED,
  318. type => dispatch(trackVideoTypeChanged(track, type)));
  319. // participantId
  320. const local = track.isLocal();
  321. const mediaType = track.getType();
  322. let isReceivingData, noDataFromSourceNotificationInfo, participantId;
  323. if (local) {
  324. // Reset the no data from src notification state when we change the track, as it's context is set
  325. // on a per device basis.
  326. dispatch(setNoSrcDataNotificationUid());
  327. const participant = getLocalParticipant(getState);
  328. if (participant) {
  329. participantId = participant.id;
  330. }
  331. isReceivingData = track.isReceivingData();
  332. track.on(JitsiTrackEvents.NO_DATA_FROM_SOURCE, () => dispatch(noDataFromSource({ jitsiTrack: track })));
  333. if (!isReceivingData) {
  334. if (mediaType === MEDIA_TYPE.AUDIO) {
  335. const notificationAction = showNotification({
  336. descriptionKey: 'dialog.micNotSendingData',
  337. titleKey: 'dialog.micNotSendingDataTitle'
  338. });
  339. dispatch(notificationAction);
  340. // Set the notification ID so that other parts of the application know that this was
  341. // displayed in the context of the current device.
  342. // I.E. The no-audio-signal notification shouldn't be displayed if this was already shown.
  343. dispatch(setNoSrcDataNotificationUid(notificationAction.uid));
  344. noDataFromSourceNotificationInfo = { uid: notificationAction.uid };
  345. } else {
  346. const timeout = setTimeout(() => dispatch(showNoDataFromSourceVideoError(track)), 5000);
  347. noDataFromSourceNotificationInfo = { timeout };
  348. }
  349. }
  350. } else {
  351. participantId = track.getParticipantId();
  352. isReceivingData = true;
  353. }
  354. return dispatch({
  355. type: TRACK_ADDED,
  356. track: {
  357. jitsiTrack: track,
  358. isReceivingData,
  359. local,
  360. mediaType,
  361. mirror: _shouldMirror(track),
  362. muted: track.isMuted(),
  363. noDataFromSourceNotificationInfo,
  364. participantId,
  365. videoStarted: false,
  366. videoType: track.videoType
  367. }
  368. });
  369. };
  370. }
  371. /**
  372. * Create an action for when a track's muted state has been signaled to be
  373. * changed.
  374. *
  375. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  376. * @returns {{
  377. * type: TRACK_UPDATED,
  378. * track: Track
  379. * }}
  380. */
  381. export function trackMutedChanged(track) {
  382. return {
  383. type: TRACK_UPDATED,
  384. track: {
  385. jitsiTrack: track,
  386. muted: track.isMuted()
  387. }
  388. };
  389. }
  390. /**
  391. * Create an action for when a track's no data from source notification information changes.
  392. *
  393. * @param {JitsiLocalTrack} track - JitsiTrack instance.
  394. * @param {Object} noDataFromSourceNotificationInfo - Information about no data from source notification.
  395. * @returns {{
  396. * type: TRACK_UPDATED,
  397. * track: Track
  398. * }}
  399. */
  400. export function trackNoDataFromSourceNotificationInfoChanged(track, noDataFromSourceNotificationInfo) {
  401. return {
  402. type: TRACK_UPDATED,
  403. track: {
  404. jitsiTrack: track,
  405. noDataFromSourceNotificationInfo
  406. }
  407. };
  408. }
  409. /**
  410. * Create an action for when a track has been signaled for removal from the
  411. * conference.
  412. *
  413. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  414. * @returns {{
  415. * type: TRACK_REMOVED,
  416. * track: Track
  417. * }}
  418. */
  419. export function trackRemoved(track) {
  420. track.removeAllListeners(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  421. track.removeAllListeners(JitsiTrackEvents.TRACK_VIDEOTYPE_CHANGED);
  422. track.removeAllListeners(JitsiTrackEvents.NO_DATA_FROM_SOURCE);
  423. return {
  424. type: TRACK_REMOVED,
  425. track: {
  426. jitsiTrack: track
  427. }
  428. };
  429. }
  430. /**
  431. * Signal that track's video started to play.
  432. *
  433. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  434. * @returns {{
  435. * type: TRACK_UPDATED,
  436. * track: Track
  437. * }}
  438. */
  439. export function trackVideoStarted(track) {
  440. return {
  441. type: TRACK_UPDATED,
  442. track: {
  443. jitsiTrack: track,
  444. videoStarted: true
  445. }
  446. };
  447. }
  448. /**
  449. * Create an action for when participant video type changes.
  450. *
  451. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  452. * @param {VIDEO_TYPE|undefined} videoType - Video type.
  453. * @returns {{
  454. * type: TRACK_UPDATED,
  455. * track: Track
  456. * }}
  457. */
  458. export function trackVideoTypeChanged(track, videoType) {
  459. return {
  460. type: TRACK_UPDATED,
  461. track: {
  462. jitsiTrack: track,
  463. videoType
  464. }
  465. };
  466. }
  467. /**
  468. * Signals passed tracks to be added.
  469. *
  470. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  471. * @private
  472. * @returns {Function}
  473. */
  474. function _addTracks(tracks) {
  475. return dispatch => Promise.all(tracks.map(t => dispatch(trackAdded(t))));
  476. }
  477. /**
  478. * Cancels and waits for any {@code getUserMedia} process/currently in progress
  479. * to complete/settle.
  480. *
  481. * @param {Function} getState - The redux store {@code getState} function used
  482. * to obtain the state.
  483. * @private
  484. * @returns {Promise} - A {@code Promise} resolved once all
  485. * {@code gumProcess.cancel()} {@code Promise}s are settled because all we care
  486. * about here is to be sure that the {@code getUserMedia} callbacks have
  487. * completed (i.e. Returned from the native side).
  488. */
  489. function _cancelGUMProcesses(getState) {
  490. const logError
  491. = error =>
  492. logger.error('gumProcess.cancel failed', JSON.stringify(error));
  493. return Promise.all(
  494. getState()['features/base/tracks']
  495. .filter(t => t.local)
  496. .map(({ gumProcess }) =>
  497. gumProcess && gumProcess.cancel().catch(logError)));
  498. }
  499. /**
  500. * Disposes passed tracks and signals them to be removed.
  501. *
  502. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  503. * @protected
  504. * @returns {Function}
  505. */
  506. export function _disposeAndRemoveTracks(tracks) {
  507. return dispatch =>
  508. _disposeTracks(tracks)
  509. .then(() =>
  510. Promise.all(tracks.map(t => dispatch(trackRemoved(t)))));
  511. }
  512. /**
  513. * Disposes passed tracks.
  514. *
  515. * @param {(JitsiLocalTrack|JitsiRemoteTrack)[]} tracks - List of tracks.
  516. * @private
  517. * @returns {Promise} - A Promise resolved once {@link JitsiTrack.dispose()} is
  518. * done for every track from the list.
  519. */
  520. function _disposeTracks(tracks) {
  521. return Promise.all(
  522. tracks.map(t =>
  523. t.dispose()
  524. .catch(err => {
  525. // Track might be already disposed so ignore such an error.
  526. // Of course, re-throw any other error(s).
  527. if (err.name !== JitsiTrackErrors.TRACK_IS_DISPOSED) {
  528. throw err;
  529. }
  530. })));
  531. }
  532. /**
  533. * Implements the {@code Promise} rejection handler of
  534. * {@code createLocalTracksA} and {@code createLocalTracksF}.
  535. *
  536. * @param {Object} reason - The {@code Promise} rejection reason.
  537. * @param {string} device - The device/{@code MEDIA_TYPE} associated with the
  538. * rejection.
  539. * @private
  540. * @returns {Function}
  541. */
  542. function _onCreateLocalTracksRejected({ gum }, device) {
  543. return dispatch => {
  544. // If permissions are not allowed, alert the user.
  545. if (gum) {
  546. const { error } = gum;
  547. if (error) {
  548. dispatch({
  549. type: TRACK_CREATE_ERROR,
  550. permissionDenied: error.name === 'SecurityError',
  551. trackType: device
  552. });
  553. }
  554. }
  555. };
  556. }
  557. /**
  558. * Returns true if the provided {@code JitsiTrack} should be rendered as a
  559. * mirror.
  560. *
  561. * We only want to show a video in mirrored mode when:
  562. * 1) The video source is local, and not remote.
  563. * 2) The video source is a camera, not a desktop (capture).
  564. * 3) The camera is capturing the user, not the environment.
  565. *
  566. * TODO Similar functionality is part of lib-jitsi-meet. This function should be
  567. * removed after https://github.com/jitsi/lib-jitsi-meet/pull/187 is merged.
  568. *
  569. * @param {(JitsiLocalTrack|JitsiRemoteTrack)} track - JitsiTrack instance.
  570. * @private
  571. * @returns {boolean}
  572. */
  573. function _shouldMirror(track) {
  574. return (
  575. track
  576. && track.isLocal()
  577. && track.isVideoTrack()
  578. // XXX The type of the return value of JitsiLocalTrack's
  579. // getCameraFacingMode happens to be named CAMERA_FACING_MODE as
  580. // well, it's defined by lib-jitsi-meet. Note though that the type
  581. // of the value on the right side of the equality check is defined
  582. // by jitsi-meet. The type definitions are surely compatible today
  583. // but that may not be the case tomorrow.
  584. && track.getCameraFacingMode() === CAMERA_FACING_MODE.USER);
  585. }
  586. /**
  587. * Signals that track create operation for given media track has been canceled.
  588. * Will clean up local track stub from the redux state which holds the
  589. * {@code gumProcess} reference.
  590. *
  591. * @param {MEDIA_TYPE} mediaType - The type of the media for which the track was
  592. * being created.
  593. * @private
  594. * @returns {{
  595. * type,
  596. * trackType: MEDIA_TYPE
  597. * }}
  598. */
  599. function _trackCreateCanceled(mediaType) {
  600. return {
  601. type: TRACK_CREATE_CANCELED,
  602. trackType: mediaType
  603. };
  604. }
  605. /**
  606. * Sets UID of the displayed no data from source notification. Used to track
  607. * if the notification was previously displayed in this context.
  608. *
  609. * @param {number} uid - Notification UID.
  610. * @returns {{
  611. * type: SET_NO_AUDIO_SIGNAL_UID,
  612. * uid: number
  613. * }}
  614. */
  615. export function setNoSrcDataNotificationUid(uid) {
  616. return {
  617. type: SET_NO_SRC_DATA_NOTIFICATION_UID,
  618. uid
  619. };
  620. }