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.

conference.js 95KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import { openConnection } from './connection';
  3. import AuthHandler from './modules/UI/authentication/AuthHandler';
  4. import Recorder from './modules/recorder/Recorder';
  5. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  6. import * as RemoteControlEvents
  7. from './service/remotecontrol/RemoteControlEvents';
  8. import UIEvents from './service/UI/UIEvents';
  9. import UIUtil from './modules/UI/util/UIUtil';
  10. import { createTaskQueue } from './modules/util/helpers';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import {
  13. createDeviceChangedEvent,
  14. createStartSilentEvent,
  15. createScreenSharingEvent,
  16. createStreamSwitchDelayEvent,
  17. createTrackMutedEvent,
  18. sendAnalytics
  19. } from './react/features/analytics';
  20. import {
  21. maybeRedirectToWelcomePage,
  22. redirectToStaticPage,
  23. reloadWithStoredParams
  24. } from './react/features/app';
  25. import EventEmitter from 'events';
  26. import {
  27. AVATAR_ID_COMMAND,
  28. AVATAR_URL_COMMAND,
  29. EMAIL_COMMAND,
  30. authStatusChanged,
  31. commonUserJoinedHandling,
  32. commonUserLeftHandling,
  33. conferenceFailed,
  34. conferenceJoined,
  35. conferenceLeft,
  36. conferenceSubjectChanged,
  37. conferenceWillJoin,
  38. conferenceWillLeave,
  39. dataChannelOpened,
  40. kickedOut,
  41. lockStateChanged,
  42. onStartMutedPolicyChanged,
  43. p2pStatusChanged,
  44. sendLocalParticipant,
  45. setDesktopSharingEnabled
  46. } from './react/features/base/conference';
  47. import {
  48. checkAndNotifyForNewDevice,
  49. getAvailableDevices,
  50. notifyCameraError,
  51. notifyMicError,
  52. setAudioOutputDeviceId,
  53. updateDeviceList
  54. } from './react/features/base/devices';
  55. import {
  56. isFatalJitsiConnectionError,
  57. JitsiConferenceErrors,
  58. JitsiConferenceEvents,
  59. JitsiConnectionErrors,
  60. JitsiConnectionEvents,
  61. JitsiMediaDevicesEvents,
  62. JitsiParticipantConnectionStatus,
  63. JitsiTrackErrors,
  64. JitsiTrackEvents
  65. } from './react/features/base/lib-jitsi-meet';
  66. import {
  67. isVideoMutedByUser,
  68. MEDIA_TYPE,
  69. setAudioAvailable,
  70. setAudioMuted,
  71. setVideoAvailable,
  72. setVideoMuted
  73. } from './react/features/base/media';
  74. import { showNotification } from './react/features/notifications';
  75. import {
  76. dominantSpeakerChanged,
  77. getLocalParticipant,
  78. getNormalizedDisplayName,
  79. getParticipantById,
  80. localParticipantConnectionStatusChanged,
  81. localParticipantRoleChanged,
  82. participantConnectionStatusChanged,
  83. participantKicked,
  84. participantMutedUs,
  85. participantPresenceChanged,
  86. participantRoleChanged,
  87. participantUpdated
  88. } from './react/features/base/participants';
  89. import { updateSettings } from './react/features/base/settings';
  90. import {
  91. createLocalTracksF,
  92. destroyLocalTracks,
  93. isLocalTrackMuted,
  94. isUserInteractionRequiredForUnmute,
  95. replaceLocalTrack,
  96. trackAdded,
  97. trackRemoved
  98. } from './react/features/base/tracks';
  99. import { getJitsiMeetGlobalNS } from './react/features/base/util';
  100. import { showDesktopPicker } from './react/features/desktop-picker';
  101. import { appendSuffix } from './react/features/display-name';
  102. import {
  103. maybeOpenFeedbackDialog,
  104. submitFeedback
  105. } from './react/features/feedback';
  106. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay';
  107. import { suspendDetected } from './react/features/power-monitor';
  108. import { setSharedVideoStatus } from './react/features/shared-video';
  109. import { endpointMessageReceived } from './react/features/subtitles';
  110. const logger = require('jitsi-meet-logger').getLogger(__filename);
  111. const eventEmitter = new EventEmitter();
  112. let room;
  113. let connection;
  114. /*
  115. * Logic to open a desktop picker put on the window global for
  116. * lib-jitsi-meet to detect and invoke
  117. */
  118. window.JitsiMeetScreenObtainer = {
  119. openDesktopPicker(options, onSourceChoose) {
  120. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  121. }
  122. };
  123. /**
  124. * Known custom conference commands.
  125. */
  126. const commands = {
  127. AVATAR_ID: AVATAR_ID_COMMAND,
  128. AVATAR_URL: AVATAR_URL_COMMAND,
  129. CUSTOM_ROLE: 'custom-role',
  130. EMAIL: EMAIL_COMMAND,
  131. ETHERPAD: 'etherpad',
  132. SHARED_VIDEO: 'shared-video'
  133. };
  134. /**
  135. * Open Connection. When authentication failed it shows auth dialog.
  136. * @param roomName the room name to use
  137. * @returns Promise<JitsiConnection>
  138. */
  139. function connect(roomName) {
  140. return openConnection({
  141. retry: true,
  142. roomName
  143. })
  144. .catch(err => {
  145. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  146. APP.UI.notifyTokenAuthFailed();
  147. } else {
  148. APP.UI.notifyConnectionFailed(err);
  149. }
  150. throw err;
  151. });
  152. }
  153. /**
  154. * Share data to other users.
  155. * @param command the command
  156. * @param {string} value new value
  157. */
  158. function sendData(command, value) {
  159. if (!room) {
  160. return;
  161. }
  162. room.removeCommand(command);
  163. room.sendCommand(command, { value });
  164. }
  165. /**
  166. * Get user nickname by user id.
  167. * @param {string} id user id
  168. * @returns {string?} user nickname or undefined if user is unknown.
  169. */
  170. function getDisplayName(id) {
  171. const participant = getParticipantById(APP.store.getState(), id);
  172. return participant && participant.name;
  173. }
  174. /**
  175. * Mute or unmute local audio stream if it exists.
  176. * @param {boolean} muted - if audio stream should be muted or unmuted.
  177. */
  178. function muteLocalAudio(muted) {
  179. APP.store.dispatch(setAudioMuted(muted));
  180. }
  181. /**
  182. * Mute or unmute local video stream if it exists.
  183. * @param {boolean} muted if video stream should be muted or unmuted.
  184. *
  185. */
  186. function muteLocalVideo(muted) {
  187. APP.store.dispatch(setVideoMuted(muted));
  188. }
  189. /**
  190. * A queue for the async replaceLocalTrack action so that multiple audio
  191. * replacements cannot happen simultaneously. This solves the issue where
  192. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  193. * multiple local tracks of the same type to be used.
  194. *
  195. * @private
  196. * @type {Object}
  197. */
  198. const _replaceLocalAudioTrackQueue = createTaskQueue();
  199. /**
  200. * A task queue for replacement local video tracks. This separate queue exists
  201. * so video replacement is not blocked by audio replacement tasks in the queue
  202. * {@link _replaceLocalAudioTrackQueue}.
  203. *
  204. * @private
  205. * @type {Object}
  206. */
  207. const _replaceLocalVideoTrackQueue = createTaskQueue();
  208. /**
  209. *
  210. */
  211. class ConferenceConnector {
  212. /**
  213. *
  214. */
  215. constructor(resolve, reject) {
  216. this._resolve = resolve;
  217. this._reject = reject;
  218. this.reconnectTimeout = null;
  219. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  220. this._handleConferenceJoined.bind(this));
  221. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  222. this._onConferenceFailed.bind(this));
  223. }
  224. /**
  225. *
  226. */
  227. _handleConferenceFailed(err) {
  228. this._unsubscribe();
  229. this._reject(err);
  230. }
  231. /**
  232. *
  233. */
  234. _onConferenceFailed(err, ...params) {
  235. APP.store.dispatch(conferenceFailed(room, err, ...params));
  236. logger.error('CONFERENCE FAILED:', err, ...params);
  237. switch (err) {
  238. case JitsiConferenceErrors.CONNECTION_ERROR: {
  239. const [ msg ] = params;
  240. APP.UI.notifyConnectionFailed(msg);
  241. break;
  242. }
  243. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  244. // let's show some auth not allowed page
  245. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  246. break;
  247. }
  248. // not enough rights to create conference
  249. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  250. // Schedule reconnect to check if someone else created the room.
  251. this.reconnectTimeout = setTimeout(() => {
  252. APP.store.dispatch(conferenceWillJoin(room));
  253. room.join();
  254. }, 5000);
  255. const { password }
  256. = APP.store.getState()['features/base/conference'];
  257. AuthHandler.requireAuth(room, password);
  258. break;
  259. }
  260. case JitsiConferenceErrors.RESERVATION_ERROR: {
  261. const [ code, msg ] = params;
  262. APP.UI.notifyReservationError(code, msg);
  263. break;
  264. }
  265. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  266. APP.UI.notifyGracefulShutdown();
  267. break;
  268. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  269. const [ reason ] = params;
  270. APP.UI.hideStats();
  271. APP.UI.notifyConferenceDestroyed(reason);
  272. break;
  273. }
  274. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  275. // What really happens there is that the library is not ready yet,
  276. // because Jicofo is not available, but it is going to give it another
  277. // try.
  278. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  279. const [ focus, retrySec ] = params;
  280. APP.UI.notifyFocusDisconnected(focus, retrySec);
  281. break;
  282. }
  283. case JitsiConferenceErrors.FOCUS_LEFT:
  284. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  285. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  286. APP.store.dispatch(conferenceWillLeave(room));
  287. // FIXME the conference should be stopped by the library and not by
  288. // the app. Both the errors above are unrecoverable from the library
  289. // perspective.
  290. room.leave().then(() => connection.disconnect());
  291. break;
  292. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  293. connection.disconnect();
  294. APP.UI.notifyMaxUsersLimitReached();
  295. break;
  296. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  297. APP.store.dispatch(reloadWithStoredParams());
  298. break;
  299. default:
  300. this._handleConferenceFailed(err, ...params);
  301. }
  302. }
  303. /**
  304. *
  305. */
  306. _unsubscribe() {
  307. room.off(
  308. JitsiConferenceEvents.CONFERENCE_JOINED,
  309. this._handleConferenceJoined);
  310. room.off(
  311. JitsiConferenceEvents.CONFERENCE_FAILED,
  312. this._onConferenceFailed);
  313. if (this.reconnectTimeout !== null) {
  314. clearTimeout(this.reconnectTimeout);
  315. }
  316. AuthHandler.closeAuth();
  317. }
  318. /**
  319. *
  320. */
  321. _handleConferenceJoined() {
  322. this._unsubscribe();
  323. this._resolve();
  324. }
  325. /**
  326. *
  327. */
  328. connect() {
  329. room.join();
  330. }
  331. }
  332. /**
  333. * Disconnects the connection.
  334. * @returns resolved Promise. We need this in order to make the Promise.all
  335. * call in hangup() to resolve when all operations are finished.
  336. */
  337. function disconnect() {
  338. const onDisconnected = () => {
  339. APP.API.notifyConferenceLeft(APP.conference.roomName);
  340. return Promise.resolve();
  341. };
  342. return connection.disconnect().then(onDisconnected, onDisconnected);
  343. }
  344. /**
  345. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  346. *
  347. * @param {JitsiConnectionError} error - The reported error.
  348. * @returns {void}
  349. * @private
  350. */
  351. function _connectionFailedHandler(error) {
  352. if (isFatalJitsiConnectionError(error)) {
  353. APP.connection.removeEventListener(
  354. JitsiConnectionEvents.CONNECTION_FAILED,
  355. _connectionFailedHandler);
  356. if (room) {
  357. APP.store.dispatch(conferenceWillLeave(room));
  358. room.leave();
  359. }
  360. }
  361. }
  362. export default {
  363. /**
  364. * Flag used to delay modification of the muted status of local media tracks
  365. * until those are created (or not, but at that point it's certain that
  366. * the tracks won't exist).
  367. */
  368. _localTracksInitialized: false,
  369. isModerator: false,
  370. isSharingScreen: false,
  371. /**
  372. * Indicates if the desktop sharing functionality has been enabled.
  373. * It takes into consideration the status returned by
  374. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  375. * either if the desktop sharing is not supported by the current browser
  376. * or if it was disabled through lib-jitsi-meet specific options (check
  377. * config.js for listed options).
  378. */
  379. isDesktopSharingEnabled: false,
  380. /**
  381. * The local audio track (if any).
  382. * FIXME tracks from redux store should be the single source of truth
  383. * @type {JitsiLocalTrack|null}
  384. */
  385. localAudio: null,
  386. /**
  387. * The local video track (if any).
  388. * FIXME tracks from redux store should be the single source of truth, but
  389. * more refactoring is required around screen sharing ('localVideo' usages).
  390. * @type {JitsiLocalTrack|null}
  391. */
  392. localVideo: null,
  393. /**
  394. * Creates local media tracks and connects to a room. Will show error
  395. * dialogs in case accessing the local microphone and/or camera failed. Will
  396. * show guidance overlay for users on how to give access to camera and/or
  397. * microphone.
  398. * @param {string} roomName
  399. * @param {object} options
  400. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  401. * only audio track will be created and the audio only mode will be turned
  402. * on.
  403. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  404. * should start with screensharing instead of camera video.
  405. * @param {boolean} options.startWithAudioMuted - will start the conference
  406. * without any audio tracks.
  407. * @param {boolean} options.startWithVideoMuted - will start the conference
  408. * without any video tracks.
  409. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  410. */
  411. createInitialLocalTracksAndConnect(roomName, options = {}) {
  412. let audioAndVideoError,
  413. audioOnlyError,
  414. screenSharingError,
  415. videoOnlyError;
  416. const initialDevices = [];
  417. let requestedAudio = false;
  418. let requestedVideo = false;
  419. if (!options.startWithAudioMuted) {
  420. initialDevices.push('audio');
  421. requestedAudio = true;
  422. }
  423. if (!options.startWithVideoMuted
  424. && !options.startAudioOnly
  425. && !options.startScreenSharing) {
  426. initialDevices.push('video');
  427. requestedVideo = true;
  428. }
  429. JitsiMeetJS.mediaDevices.addEventListener(
  430. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  431. browser =>
  432. APP.store.dispatch(
  433. mediaPermissionPromptVisibilityChanged(true, browser))
  434. );
  435. let tryCreateLocalTracks;
  436. // FIXME is there any simpler way to rewrite this spaghetti below ?
  437. if (options.startScreenSharing) {
  438. tryCreateLocalTracks = this._createDesktopTrack()
  439. .then(desktopStream => {
  440. if (!requestedAudio) {
  441. return [ desktopStream ];
  442. }
  443. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  444. .then(([ audioStream ]) =>
  445. [ desktopStream, audioStream ])
  446. .catch(error => {
  447. audioOnlyError = error;
  448. return [ desktopStream ];
  449. });
  450. })
  451. .catch(error => {
  452. logger.error('Failed to obtain desktop stream', error);
  453. screenSharingError = error;
  454. return requestedAudio
  455. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  456. : [];
  457. })
  458. .catch(error => {
  459. audioOnlyError = error;
  460. return [];
  461. });
  462. } else if (!requestedAudio && !requestedVideo) {
  463. // Resolve with no tracks
  464. tryCreateLocalTracks = Promise.resolve([]);
  465. } else {
  466. tryCreateLocalTracks = createLocalTracksF({ devices: initialDevices }, true)
  467. .catch(err => {
  468. if (requestedAudio && requestedVideo) {
  469. // Try audio only...
  470. audioAndVideoError = err;
  471. return (
  472. createLocalTracksF({ devices: [ 'audio' ] }, true));
  473. } else if (requestedAudio && !requestedVideo) {
  474. audioOnlyError = err;
  475. return [];
  476. } else if (requestedVideo && !requestedAudio) {
  477. videoOnlyError = err;
  478. return [];
  479. }
  480. logger.error('Should never happen');
  481. })
  482. .catch(err => {
  483. // Log this just in case...
  484. if (!requestedAudio) {
  485. logger.error('The impossible just happened', err);
  486. }
  487. audioOnlyError = err;
  488. // Try video only...
  489. return requestedVideo
  490. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  491. : [];
  492. })
  493. .catch(err => {
  494. // Log this just in case...
  495. if (!requestedVideo) {
  496. logger.error('The impossible just happened', err);
  497. }
  498. videoOnlyError = err;
  499. return [];
  500. });
  501. }
  502. // Hide the permissions prompt/overlay as soon as the tracks are
  503. // created. Don't wait for the connection to be made, since in some
  504. // cases, when auth is rquired, for instance, that won't happen until
  505. // the user inputs their credentials, but the dialog would be
  506. // overshadowed by the overlay.
  507. tryCreateLocalTracks.then(() =>
  508. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false)));
  509. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  510. .then(([ tracks, con ]) => {
  511. // FIXME If there will be microphone error it will cover any
  512. // screensharing dialog, but it's still better than in
  513. // the reverse order where the screensharing dialog will
  514. // sometimes be closing the microphone alert ($.prompt.close();
  515. // is called). Need to figure out dialogs chaining to fix that.
  516. if (screenSharingError) {
  517. this._handleScreenSharingError(screenSharingError);
  518. }
  519. if (audioAndVideoError || audioOnlyError) {
  520. if (audioOnlyError || videoOnlyError) {
  521. // If both requests for 'audio' + 'video' and 'audio'
  522. // only failed, we assume that there are some problems
  523. // with user's microphone and show corresponding dialog.
  524. APP.store.dispatch(notifyMicError(audioOnlyError));
  525. APP.store.dispatch(notifyCameraError(videoOnlyError));
  526. } else {
  527. // If request for 'audio' + 'video' failed, but request
  528. // for 'audio' only was OK, we assume that we had
  529. // problems with camera and show corresponding dialog.
  530. APP.store.dispatch(
  531. notifyCameraError(audioAndVideoError));
  532. }
  533. }
  534. return [ tracks, con ];
  535. });
  536. },
  537. /**
  538. * Open new connection and join to the conference.
  539. * @param {object} options
  540. * @param {string} roomName - The name of the conference.
  541. * @returns {Promise}
  542. */
  543. init(options) {
  544. this.roomName = options.roomName;
  545. return (
  546. // Initialize the device list first. This way, when creating tracks
  547. // based on preferred devices, loose label matching can be done in
  548. // cases where the exact ID match is no longer available, such as
  549. // when the camera device has switched USB ports.
  550. // when in startSilent mode we want to start with audio muted
  551. this._initDeviceList()
  552. .catch(error => logger.warn(
  553. 'initial device list initialization failed', error))
  554. .then(() => this.createInitialLocalTracksAndConnect(
  555. options.roomName, {
  556. startAudioOnly: config.startAudioOnly,
  557. startScreenSharing: config.startScreenSharing,
  558. startWithAudioMuted: config.startWithAudioMuted
  559. || config.startSilent
  560. || isUserInteractionRequiredForUnmute(APP.store.getState()),
  561. startWithVideoMuted: config.startWithVideoMuted
  562. || isUserInteractionRequiredForUnmute(APP.store.getState())
  563. }))
  564. .then(([ tracks, con ]) => {
  565. tracks.forEach(track => {
  566. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  567. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  568. const mediaType = track.getType();
  569. sendAnalytics(
  570. createTrackMutedEvent(mediaType, 'initial mute'));
  571. logger.log(`${mediaType} mute: initially muted.`);
  572. track.mute();
  573. }
  574. });
  575. logger.log(`initialized with ${tracks.length} local tracks`);
  576. this._localTracksInitialized = true;
  577. con.addEventListener(
  578. JitsiConnectionEvents.CONNECTION_FAILED,
  579. _connectionFailedHandler);
  580. APP.connection = connection = con;
  581. // Desktop sharing related stuff:
  582. this.isDesktopSharingEnabled
  583. = JitsiMeetJS.isDesktopSharingEnabled();
  584. eventEmitter.emit(
  585. JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED,
  586. this.isDesktopSharingEnabled);
  587. APP.store.dispatch(
  588. setDesktopSharingEnabled(this.isDesktopSharingEnabled));
  589. this._createRoom(tracks);
  590. APP.remoteControl.init();
  591. // if user didn't give access to mic or camera or doesn't have
  592. // them at all, we mark corresponding toolbar buttons as muted,
  593. // so that the user can try unmute later on and add audio/video
  594. // to the conference
  595. if (!tracks.find(t => t.isAudioTrack())) {
  596. this.setAudioMuteStatus(true);
  597. }
  598. if (!tracks.find(t => t.isVideoTrack())) {
  599. this.setVideoMuteStatus(true);
  600. }
  601. // Initialize device list a second time to ensure device labels
  602. // get populated in case of an initial gUM acceptance; otherwise
  603. // they may remain as empty strings.
  604. this._initDeviceList(true);
  605. if (config.iAmRecorder) {
  606. this.recorder = new Recorder();
  607. }
  608. if (config.startSilent) {
  609. sendAnalytics(createStartSilentEvent());
  610. APP.store.dispatch(showNotification({
  611. descriptionKey: 'notify.startSilentDescription',
  612. titleKey: 'notify.startSilentTitle'
  613. }));
  614. }
  615. // XXX The API will take care of disconnecting from the XMPP
  616. // server (and, thus, leaving the room) on unload.
  617. return new Promise((resolve, reject) => {
  618. (new ConferenceConnector(resolve, reject)).connect();
  619. });
  620. })
  621. );
  622. },
  623. /**
  624. * Check if id is id of the local user.
  625. * @param {string} id id to check
  626. * @returns {boolean}
  627. */
  628. isLocalId(id) {
  629. return this.getMyUserId() === id;
  630. },
  631. /**
  632. * Tells whether the local video is muted or not.
  633. * @return {boolean}
  634. */
  635. isLocalVideoMuted() {
  636. // If the tracks are not ready, read from base/media state
  637. return this._localTracksInitialized
  638. ? isLocalTrackMuted(
  639. APP.store.getState()['features/base/tracks'],
  640. MEDIA_TYPE.VIDEO)
  641. : isVideoMutedByUser(APP.store);
  642. },
  643. /**
  644. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  645. * @param {boolean} mute true for mute and false for unmute.
  646. * @param {boolean} [showUI] when set to false will not display any error
  647. * dialogs in case of media permissions error.
  648. */
  649. muteAudio(mute, showUI = true) {
  650. if (!mute
  651. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  652. logger.error('Unmuting audio requires user interaction');
  653. return;
  654. }
  655. // Not ready to modify track's state yet
  656. if (!this._localTracksInitialized) {
  657. // This will only modify base/media.audio.muted which is then synced
  658. // up with the track at the end of local tracks initialization.
  659. muteLocalAudio(mute);
  660. this.setAudioMuteStatus(mute);
  661. return;
  662. } else if (this.isLocalAudioMuted() === mute) {
  663. // NO-OP
  664. return;
  665. }
  666. if (!this.localAudio && !mute) {
  667. const maybeShowErrorDialog = error => {
  668. showUI && APP.store.dispatch(notifyMicError(error));
  669. };
  670. createLocalTracksF({ devices: [ 'audio' ] }, false)
  671. .then(([ audioTrack ]) => audioTrack)
  672. .catch(error => {
  673. maybeShowErrorDialog(error);
  674. // Rollback the audio muted status by using null track
  675. return null;
  676. })
  677. .then(audioTrack => this.useAudioStream(audioTrack));
  678. } else {
  679. muteLocalAudio(mute);
  680. }
  681. },
  682. /**
  683. * Returns whether local audio is muted or not.
  684. * @returns {boolean}
  685. */
  686. isLocalAudioMuted() {
  687. // If the tracks are not ready, read from base/media state
  688. return this._localTracksInitialized
  689. ? isLocalTrackMuted(
  690. APP.store.getState()['features/base/tracks'],
  691. MEDIA_TYPE.AUDIO)
  692. : Boolean(
  693. APP.store.getState()['features/base/media'].audio.muted);
  694. },
  695. /**
  696. * Simulates toolbar button click for audio mute. Used by shortcuts
  697. * and API.
  698. * @param {boolean} [showUI] when set to false will not display any error
  699. * dialogs in case of media permissions error.
  700. */
  701. toggleAudioMuted(showUI = true) {
  702. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  703. },
  704. /**
  705. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  706. * @param mute true for mute and false for unmute.
  707. * @param {boolean} [showUI] when set to false will not display any error
  708. * dialogs in case of media permissions error.
  709. */
  710. muteVideo(mute, showUI = true) {
  711. if (!mute
  712. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  713. logger.error('Unmuting video requires user interaction');
  714. return;
  715. }
  716. // If not ready to modify track's state yet adjust the base/media
  717. if (!this._localTracksInitialized) {
  718. // This will only modify base/media.video.muted which is then synced
  719. // up with the track at the end of local tracks initialization.
  720. muteLocalVideo(mute);
  721. this.setVideoMuteStatus(mute);
  722. return;
  723. } else if (this.isLocalVideoMuted() === mute) {
  724. // NO-OP
  725. return;
  726. }
  727. if (!this.localVideo && !mute) {
  728. const maybeShowErrorDialog = error => {
  729. showUI && APP.store.dispatch(notifyCameraError(error));
  730. };
  731. // Try to create local video if there wasn't any.
  732. // This handles the case when user joined with no video
  733. // (dismissed screen sharing screen or in audio only mode), but
  734. // decided to add it later on by clicking on muted video icon or
  735. // turning off the audio only mode.
  736. //
  737. // FIXME when local track creation is moved to react/redux
  738. // it should take care of the use case described above
  739. createLocalTracksF({ devices: [ 'video' ] }, false)
  740. .then(([ videoTrack ]) => videoTrack)
  741. .catch(error => {
  742. // FIXME should send some feedback to the API on error ?
  743. maybeShowErrorDialog(error);
  744. // Rollback the video muted status by using null track
  745. return null;
  746. })
  747. .then(videoTrack => this.useVideoStream(videoTrack));
  748. } else {
  749. // FIXME show error dialog if it fails (should be handled by react)
  750. muteLocalVideo(mute);
  751. }
  752. },
  753. /**
  754. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  755. * @param {boolean} [showUI] when set to false will not display any error
  756. * dialogs in case of media permissions error.
  757. */
  758. toggleVideoMuted(showUI = true) {
  759. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  760. },
  761. /**
  762. * Retrieve list of conference participants (without local user).
  763. * @returns {JitsiParticipant[]}
  764. */
  765. listMembers() {
  766. return room.getParticipants();
  767. },
  768. /**
  769. * Retrieve list of ids of conference participants (without local user).
  770. * @returns {string[]}
  771. */
  772. listMembersIds() {
  773. return room.getParticipants().map(p => p.getId());
  774. },
  775. /**
  776. * Checks whether the participant identified by id is a moderator.
  777. * @id id to search for participant
  778. * @return {boolean} whether the participant is moderator
  779. */
  780. isParticipantModerator(id) {
  781. const user = room.getParticipantById(id);
  782. return user && user.isModerator();
  783. },
  784. get membersCount() {
  785. return room.getParticipants().length + 1;
  786. },
  787. /**
  788. * Returns true if the callstats integration is enabled, otherwise returns
  789. * false.
  790. *
  791. * @returns true if the callstats integration is enabled, otherwise returns
  792. * false.
  793. */
  794. isCallstatsEnabled() {
  795. return room && room.isCallstatsEnabled();
  796. },
  797. /**
  798. * Sends the given feedback through CallStats if enabled.
  799. *
  800. * @param overallFeedback an integer between 1 and 5 indicating the
  801. * user feedback
  802. * @param detailedFeedback detailed feedback from the user. Not yet used
  803. */
  804. sendFeedback(overallFeedback, detailedFeedback) {
  805. return room.sendFeedback(overallFeedback, detailedFeedback);
  806. },
  807. /**
  808. * Get speaker stats that track total dominant speaker time.
  809. *
  810. * @returns {object} A hash with keys being user ids and values being the
  811. * library's SpeakerStats model used for calculating time as dominant
  812. * speaker.
  813. */
  814. getSpeakerStats() {
  815. return room.getSpeakerStats();
  816. },
  817. /**
  818. * Returns the connection times stored in the library.
  819. */
  820. getConnectionTimes() {
  821. return room.getConnectionTimes();
  822. },
  823. // used by torture currently
  824. isJoined() {
  825. return room && room.isJoined();
  826. },
  827. getConnectionState() {
  828. return room && room.getConnectionState();
  829. },
  830. /**
  831. * Obtains current P2P ICE connection state.
  832. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  833. * P2P connection
  834. */
  835. getP2PConnectionState() {
  836. return room && room.getP2PConnectionState();
  837. },
  838. /**
  839. * Starts P2P (for tests only)
  840. * @private
  841. */
  842. _startP2P() {
  843. try {
  844. room && room.startP2PSession();
  845. } catch (error) {
  846. logger.error('Start P2P failed', error);
  847. throw error;
  848. }
  849. },
  850. /**
  851. * Stops P2P (for tests only)
  852. * @private
  853. */
  854. _stopP2P() {
  855. try {
  856. room && room.stopP2PSession();
  857. } catch (error) {
  858. logger.error('Stop P2P failed', error);
  859. throw error;
  860. }
  861. },
  862. /**
  863. * Checks whether or not our connection is currently in interrupted and
  864. * reconnect attempts are in progress.
  865. *
  866. * @returns {boolean} true if the connection is in interrupted state or
  867. * false otherwise.
  868. */
  869. isConnectionInterrupted() {
  870. return room.isConnectionInterrupted();
  871. },
  872. /**
  873. * Obtains the local display name.
  874. * @returns {string|undefined}
  875. */
  876. getLocalDisplayName() {
  877. return getDisplayName(this.getMyUserId());
  878. },
  879. /**
  880. * Finds JitsiParticipant for given id.
  881. *
  882. * @param {string} id participant's identifier(MUC nickname).
  883. *
  884. * @returns {JitsiParticipant|null} participant instance for given id or
  885. * null if not found.
  886. */
  887. getParticipantById(id) {
  888. return room ? room.getParticipantById(id) : null;
  889. },
  890. /**
  891. * Get participant connection status for the participant.
  892. *
  893. * @param {string} id participant's identifier(MUC nickname)
  894. *
  895. * @returns {ParticipantConnectionStatus|null} the status of the participant
  896. * or null if no such participant is found or participant is the local user.
  897. */
  898. getParticipantConnectionStatus(id) {
  899. const participant = this.getParticipantById(id);
  900. return participant ? participant.getConnectionStatus() : null;
  901. },
  902. /**
  903. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  904. * the given <tt>id</tt>.
  905. *
  906. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  907. *
  908. * @return {string} the participant's display name or the default string if
  909. * absent.
  910. */
  911. getParticipantDisplayName(id) {
  912. const displayName = getDisplayName(id);
  913. if (displayName) {
  914. return displayName;
  915. }
  916. if (APP.conference.isLocalId(id)) {
  917. return APP.translation.generateTranslationHTML(
  918. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  919. }
  920. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  921. },
  922. getMyUserId() {
  923. return room && room.myUserId();
  924. },
  925. /**
  926. * Will be filled with values only when config.debug is enabled.
  927. * Its used by torture to check audio levels.
  928. */
  929. audioLevelsMap: {},
  930. /**
  931. * Returns the stored audio level (stored only if config.debug is enabled)
  932. * @param id the id for the user audio level to return (the id value is
  933. * returned for the participant using getMyUserId() method)
  934. */
  935. getPeerSSRCAudioLevel(id) {
  936. return this.audioLevelsMap[id];
  937. },
  938. /**
  939. * @return {number} the number of participants in the conference with at
  940. * least one track.
  941. */
  942. getNumberOfParticipantsWithTracks() {
  943. return room.getParticipants()
  944. .filter(p => p.getTracks().length > 0)
  945. .length;
  946. },
  947. /**
  948. * Returns the stats.
  949. */
  950. getStats() {
  951. return room.connectionQuality.getStats();
  952. },
  953. // end used by torture
  954. getLogs() {
  955. return room.getLogs();
  956. },
  957. /**
  958. * Download logs, a function that can be called from console while
  959. * debugging.
  960. * @param filename (optional) specify target filename
  961. */
  962. saveLogs(filename = 'meetlog.json') {
  963. // this can be called from console and will not have reference to this
  964. // that's why we reference the global var
  965. const logs = APP.conference.getLogs();
  966. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  967. const elem = document.createElement('a');
  968. elem.download = filename;
  969. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  970. elem.dataset.downloadurl
  971. = [ 'text/json', elem.download, elem.href ].join(':');
  972. elem.dispatchEvent(new MouseEvent('click', {
  973. view: window,
  974. bubbles: true,
  975. cancelable: false
  976. }));
  977. },
  978. /**
  979. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  980. * desire to keep room private to this instance and (2) the need of other
  981. * modules to send and receive commands to and from participants.
  982. * Eventually, this instance remains in control with respect to the
  983. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  984. * JitsiConference) is to be used in the implementation of the Command(s)
  985. * API of this instance.
  986. */
  987. commands: {
  988. /**
  989. * Known custom conference commands.
  990. */
  991. defaults: commands,
  992. /**
  993. * Receives notifications from other participants about commands aka
  994. * custom events (sent by sendCommand or sendCommandOnce methods).
  995. * @param command {String} the name of the command
  996. * @param handler {Function} handler for the command
  997. */
  998. addCommandListener() {
  999. // eslint-disable-next-line prefer-rest-params
  1000. room.addCommandListener(...arguments);
  1001. },
  1002. /**
  1003. * Removes command.
  1004. * @param name {String} the name of the command.
  1005. */
  1006. removeCommand() {
  1007. // eslint-disable-next-line prefer-rest-params
  1008. room.removeCommand(...arguments);
  1009. },
  1010. /**
  1011. * Sends command.
  1012. * @param name {String} the name of the command.
  1013. * @param values {Object} with keys and values that will be sent.
  1014. */
  1015. sendCommand() {
  1016. // eslint-disable-next-line prefer-rest-params
  1017. room.sendCommand(...arguments);
  1018. },
  1019. /**
  1020. * Sends command one time.
  1021. * @param name {String} the name of the command.
  1022. * @param values {Object} with keys and values that will be sent.
  1023. */
  1024. sendCommandOnce() {
  1025. // eslint-disable-next-line prefer-rest-params
  1026. room.sendCommandOnce(...arguments);
  1027. }
  1028. },
  1029. _createRoom(localTracks) {
  1030. room
  1031. = connection.initJitsiConference(
  1032. APP.conference.roomName,
  1033. this._getConferenceOptions());
  1034. APP.store.dispatch(conferenceWillJoin(room));
  1035. this._setLocalAudioVideoStreams(localTracks);
  1036. this._room = room; // FIXME do not use this
  1037. sendLocalParticipant(APP.store, room);
  1038. this._setupListeners();
  1039. },
  1040. /**
  1041. * Sets local video and audio streams.
  1042. * @param {JitsiLocalTrack[]} tracks=[]
  1043. * @returns {Promise[]}
  1044. * @private
  1045. */
  1046. _setLocalAudioVideoStreams(tracks = []) {
  1047. return tracks.map(track => {
  1048. if (track.isAudioTrack()) {
  1049. return this.useAudioStream(track);
  1050. } else if (track.isVideoTrack()) {
  1051. return this.useVideoStream(track);
  1052. }
  1053. logger.error(
  1054. 'Ignored not an audio nor a video track: ', track);
  1055. return Promise.resolve();
  1056. });
  1057. },
  1058. _getConferenceOptions() {
  1059. const options = config;
  1060. const { email, name: nick } = getLocalParticipant(APP.store.getState());
  1061. const { locationURL } = APP.store.getState()['features/base/connection'];
  1062. if (options.enableDisplayNameInStats && nick) {
  1063. options.statisticsDisplayName = nick;
  1064. }
  1065. if (options.enableEmailInStats && email) {
  1066. options.statisticsId = email;
  1067. }
  1068. options.applicationName = interfaceConfig.APP_NAME;
  1069. options.getWiFiStatsMethod = this._getWiFiStatsMethod;
  1070. options.confID = `${locationURL.host}${locationURL.pathname}`;
  1071. return options;
  1072. },
  1073. /**
  1074. * Returns the result of getWiFiStats from the global NS or does nothing
  1075. * (returns empty result).
  1076. * Fixes a concurrency problem where we need to pass a function when creating
  1077. * JitsiConference, but that method is added to the context later.
  1078. *
  1079. * @returns {Promise}
  1080. * @private
  1081. */
  1082. _getWiFiStatsMethod() {
  1083. const gloabalNS = getJitsiMeetGlobalNS();
  1084. return gloabalNS.getWiFiStats ? gloabalNS.getWiFiStats() : Promise.resolve('{}');
  1085. },
  1086. /**
  1087. * Start using provided video stream.
  1088. * Stops previous video stream.
  1089. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1090. * @returns {Promise}
  1091. */
  1092. useVideoStream(newStream) {
  1093. return new Promise((resolve, reject) => {
  1094. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1095. APP.store.dispatch(
  1096. replaceLocalTrack(this.localVideo, newStream, room))
  1097. .then(() => {
  1098. this.localVideo = newStream;
  1099. this._setSharingScreen(newStream);
  1100. if (newStream) {
  1101. APP.UI.addLocalVideoStream(newStream);
  1102. }
  1103. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1104. })
  1105. .then(resolve)
  1106. .catch(reject)
  1107. .then(onFinish);
  1108. });
  1109. });
  1110. },
  1111. /**
  1112. * Sets `this.isSharingScreen` depending on provided video stream.
  1113. * In case new screen sharing status is not equal previous one
  1114. * it updates desktop sharing buttons in UI
  1115. * and notifies external application.
  1116. *
  1117. * @param {JitsiLocalTrack} [newStream] new stream to use or null
  1118. * @private
  1119. * @returns {void}
  1120. */
  1121. _setSharingScreen(newStream) {
  1122. const wasSharingScreen = this.isSharingScreen;
  1123. this.isSharingScreen = newStream && newStream.videoType === 'desktop';
  1124. if (wasSharingScreen !== this.isSharingScreen) {
  1125. const details = {};
  1126. if (this.isSharingScreen) {
  1127. details.sourceType = newStream.sourceType;
  1128. }
  1129. APP.API.notifyScreenSharingStatusChanged(
  1130. this.isSharingScreen, details);
  1131. }
  1132. },
  1133. /**
  1134. * Start using provided audio stream.
  1135. * Stops previous audio stream.
  1136. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1137. * @returns {Promise}
  1138. */
  1139. useAudioStream(newStream) {
  1140. return new Promise((resolve, reject) => {
  1141. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1142. APP.store.dispatch(
  1143. replaceLocalTrack(this.localAudio, newStream, room))
  1144. .then(() => {
  1145. this.localAudio = newStream;
  1146. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1147. })
  1148. .then(resolve)
  1149. .catch(reject)
  1150. .then(onFinish);
  1151. });
  1152. });
  1153. },
  1154. /**
  1155. * Returns whether or not the conference is currently in audio only mode.
  1156. *
  1157. * @returns {boolean}
  1158. */
  1159. isAudioOnly() {
  1160. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1161. },
  1162. videoSwitchInProgress: false,
  1163. /**
  1164. * This fields stores a handler which will create a Promise which turns off
  1165. * the screen sharing and restores the previous video state (was there
  1166. * any video, before switching to screen sharing ? was it muted ?).
  1167. *
  1168. * Once called this fields is cleared to <tt>null</tt>.
  1169. * @type {Function|null}
  1170. */
  1171. _untoggleScreenSharing: null,
  1172. /**
  1173. * Creates a Promise which turns off the screen sharing and restores
  1174. * the previous state described by the arguments.
  1175. *
  1176. * This method is bound to the appropriate values, after switching to screen
  1177. * sharing and stored in {@link _untoggleScreenSharing}.
  1178. *
  1179. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1180. * used, before switching to screen sharing.
  1181. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1182. * switching to screen sharing.
  1183. * @return {Promise} resolved after the screen sharing is turned off, or
  1184. * rejected with some error (no idea what kind of error, possible GUM error)
  1185. * in case it fails.
  1186. * @private
  1187. */
  1188. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1189. this._untoggleScreenSharing = null;
  1190. this.videoSwitchInProgress = true;
  1191. const { receiver } = APP.remoteControl;
  1192. if (receiver) {
  1193. receiver.stop();
  1194. }
  1195. this._stopProxyConnection();
  1196. let promise = null;
  1197. if (didHaveVideo) {
  1198. promise = createLocalTracksF({ devices: [ 'video' ] })
  1199. .then(([ stream ]) => this.useVideoStream(stream))
  1200. .then(() => {
  1201. sendAnalytics(createScreenSharingEvent('stopped'));
  1202. logger.log('Screen sharing stopped, switching to video.');
  1203. if (!this.localVideo && wasVideoMuted) {
  1204. return Promise.reject('No local video to be muted!');
  1205. } else if (wasVideoMuted && this.localVideo) {
  1206. return this.localVideo.mute();
  1207. }
  1208. })
  1209. .catch(error => {
  1210. logger.error('failed to switch back to local video', error);
  1211. return this.useVideoStream(null).then(() =>
  1212. // Still fail with the original err
  1213. Promise.reject(error)
  1214. );
  1215. });
  1216. } else {
  1217. promise = this.useVideoStream(null);
  1218. }
  1219. return promise.then(
  1220. () => {
  1221. this.videoSwitchInProgress = false;
  1222. },
  1223. error => {
  1224. this.videoSwitchInProgress = false;
  1225. throw error;
  1226. });
  1227. },
  1228. /**
  1229. * Toggles between screen sharing and camera video if the toggle parameter
  1230. * is not specified and starts the procedure for obtaining new screen
  1231. * sharing/video track otherwise.
  1232. *
  1233. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1234. * obtained. If false - new video track will be obtain. If not specified -
  1235. * toggles between screen sharing and camera video.
  1236. * @param {Object} [options] - Screen sharing options that will be passed to
  1237. * createLocalTracks.
  1238. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1239. * sources that have to be displayed in the desktop picker window ('screen',
  1240. * 'window', etc.).
  1241. * @return {Promise.<T>}
  1242. */
  1243. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1244. if (this.videoSwitchInProgress) {
  1245. return Promise.reject('Switch in progress.');
  1246. }
  1247. if (!this.isDesktopSharingEnabled) {
  1248. return Promise.reject(
  1249. 'Cannot toggle screen sharing: not supported.');
  1250. }
  1251. if (this.isAudioOnly()) {
  1252. return Promise.reject('No screensharing in audio only mode');
  1253. }
  1254. if (toggle) {
  1255. return this._switchToScreenSharing(options);
  1256. }
  1257. return this._untoggleScreenSharing
  1258. ? this._untoggleScreenSharing()
  1259. : Promise.resolve();
  1260. },
  1261. /**
  1262. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1263. *
  1264. * @param {Object} [options] - Screen sharing options that will be passed to
  1265. * createLocalTracks.
  1266. * @param {Object} [options.desktopSharing]
  1267. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1268. * use instead of creating a new desktop stream.
  1269. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1270. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1271. * {@link JitsiTrackError}.
  1272. *
  1273. * @private
  1274. */
  1275. _createDesktopTrack(options = {}) {
  1276. let externalInstallation = false;
  1277. let DSExternalInstallationInProgress = false;
  1278. const didHaveVideo = Boolean(this.localVideo);
  1279. const wasVideoMuted = this.isLocalVideoMuted();
  1280. const getDesktopStreamPromise = options.desktopStream
  1281. ? Promise.resolve([ options.desktopStream ])
  1282. : createLocalTracksF({
  1283. desktopSharingSourceDevice: options.desktopSharingSources
  1284. ? null : config._desktopSharingSourceDevice,
  1285. desktopSharingSources: options.desktopSharingSources,
  1286. devices: [ 'desktop' ],
  1287. desktopSharingExtensionExternalInstallation: {
  1288. interval: 500,
  1289. checkAgain: () => DSExternalInstallationInProgress,
  1290. listener: (status, url) => {
  1291. switch (status) {
  1292. case 'waitingForExtension': {
  1293. DSExternalInstallationInProgress = true;
  1294. externalInstallation = true;
  1295. const listener = () => {
  1296. // Wait a little bit more just to be sure that
  1297. // we won't miss the extension installation
  1298. setTimeout(() => {
  1299. DSExternalInstallationInProgress = false;
  1300. },
  1301. 500);
  1302. APP.UI.removeListener(
  1303. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1304. listener);
  1305. };
  1306. APP.UI.addListener(
  1307. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1308. listener);
  1309. APP.UI.showExtensionExternalInstallationDialog(url);
  1310. break;
  1311. }
  1312. case 'extensionFound':
  1313. // Close the dialog.
  1314. externalInstallation && $.prompt.close();
  1315. break;
  1316. default:
  1317. // Unknown status
  1318. }
  1319. }
  1320. }
  1321. });
  1322. return getDesktopStreamPromise.then(([ desktopStream ]) => {
  1323. // Stores the "untoggle" handler which remembers whether was
  1324. // there any video before and whether was it muted.
  1325. this._untoggleScreenSharing
  1326. = this._turnScreenSharingOff
  1327. .bind(this, didHaveVideo, wasVideoMuted);
  1328. desktopStream.on(
  1329. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1330. () => {
  1331. // If the stream was stopped during screen sharing
  1332. // session then we should switch back to video.
  1333. this.isSharingScreen
  1334. && this._untoggleScreenSharing
  1335. && this._untoggleScreenSharing();
  1336. }
  1337. );
  1338. // close external installation dialog on success.
  1339. externalInstallation && $.prompt.close();
  1340. return desktopStream;
  1341. }, error => {
  1342. DSExternalInstallationInProgress = false;
  1343. // close external installation dialog on success.
  1344. externalInstallation && $.prompt.close();
  1345. throw error;
  1346. });
  1347. },
  1348. /**
  1349. * Tries to switch to the screensharing mode by disposing camera stream and
  1350. * replacing it with a desktop one.
  1351. *
  1352. * @param {Object} [options] - Screen sharing options that will be passed to
  1353. * createLocalTracks.
  1354. *
  1355. * @return {Promise} - A Promise resolved if the operation succeeds or
  1356. * rejected with some unknown type of error in case it fails. Promise will
  1357. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1358. *
  1359. * @private
  1360. */
  1361. _switchToScreenSharing(options = {}) {
  1362. if (this.videoSwitchInProgress) {
  1363. return Promise.reject('Switch in progress.');
  1364. }
  1365. this.videoSwitchInProgress = true;
  1366. return this._createDesktopTrack(options)
  1367. .then(stream => this.useVideoStream(stream))
  1368. .then(() => {
  1369. this.videoSwitchInProgress = false;
  1370. sendAnalytics(createScreenSharingEvent('started'));
  1371. logger.log('Screen sharing started');
  1372. })
  1373. .catch(error => {
  1374. this.videoSwitchInProgress = false;
  1375. // Pawel: With this call I'm trying to preserve the original
  1376. // behaviour although it is not clear why would we "untoggle"
  1377. // on failure. I suppose it was to restore video in case there
  1378. // was some problem during "this.useVideoStream(desktopStream)".
  1379. // It's important to note that the handler will not be available
  1380. // if we fail early on trying to get desktop media (which makes
  1381. // sense, because the camera video is still being used, so
  1382. // nothing to "untoggle").
  1383. if (this._untoggleScreenSharing) {
  1384. this._untoggleScreenSharing();
  1385. }
  1386. // FIXME the code inside of _handleScreenSharingError is
  1387. // asynchronous, but does not return a Promise and is not part
  1388. // of the current Promise chain.
  1389. this._handleScreenSharingError(error);
  1390. return Promise.reject(error);
  1391. });
  1392. },
  1393. /**
  1394. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1395. * trying to create screensharing track. It will either do nothing if
  1396. * the dialog was canceled on user's request or display inline installation
  1397. * dialog and ask the user to install the extension, once the extension is
  1398. * installed it will switch the conference to screensharing. The last option
  1399. * is that an unrecoverable error dialog will be displayed.
  1400. * @param {JitsiTrackError} error - The error returned by
  1401. * {@link _createDesktopTrack} Promise.
  1402. * @private
  1403. */
  1404. _handleScreenSharingError(error) {
  1405. if (error.name === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1406. return;
  1407. }
  1408. logger.error('failed to share local desktop', error);
  1409. if (error.name
  1410. === JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1411. // If start with screen sharing the extension will fail to install
  1412. // (if not found), because the request has been triggered by the
  1413. // script. Show a dialog which asks user to click "install" and try
  1414. // again switching to the screen sharing.
  1415. APP.UI.showExtensionInlineInstallationDialog(
  1416. () => {
  1417. // eslint-disable-next-line no-empty-function
  1418. this.toggleScreenSharing().catch(() => {});
  1419. }
  1420. );
  1421. return;
  1422. }
  1423. // Handling:
  1424. // JitsiTrackErrors.PERMISSION_DENIED
  1425. // JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1426. // JitsiTrackErrors.CONSTRAINT_FAILED
  1427. // JitsiTrackErrors.GENERAL
  1428. // and any other
  1429. let descriptionKey;
  1430. let titleKey;
  1431. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1432. // in FF the only option for user is to deny access temporary or
  1433. // permanently and we only receive permission_denied
  1434. // we always show some info cause in case of permanently, no info
  1435. // shown will be bad experience
  1436. //
  1437. // TODO: detect interval between requesting permissions and received
  1438. // error, this way we can detect user interaction which will have
  1439. // longer delay
  1440. if (JitsiMeetJS.util.browser.isFirefox()) {
  1441. descriptionKey
  1442. = 'dialog.screenSharingFirefoxPermissionDeniedError';
  1443. titleKey = 'dialog.screenSharingFirefoxPermissionDeniedTitle';
  1444. } else {
  1445. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1446. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1447. }
  1448. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1449. descriptionKey = 'dialog.cameraConstraintFailedError';
  1450. titleKey = 'deviceError.cameraError';
  1451. } else {
  1452. descriptionKey = 'dialog.screenSharingFailedToInstall';
  1453. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1454. }
  1455. APP.UI.messageHandler.showError({
  1456. descriptionKey,
  1457. titleKey
  1458. });
  1459. },
  1460. /**
  1461. * Setup interaction between conference and UI.
  1462. */
  1463. _setupListeners() {
  1464. // add local streams when joined to the conference
  1465. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1466. this._onConferenceJoined();
  1467. });
  1468. room.on(
  1469. JitsiConferenceEvents.CONFERENCE_LEFT,
  1470. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1471. room.on(
  1472. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1473. (authEnabled, authLogin) =>
  1474. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1475. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1476. user => APP.UI.onUserFeaturesChanged(user));
  1477. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1478. // The logic shared between RN and web.
  1479. commonUserJoinedHandling(APP.store, room, user);
  1480. if (user.isHidden()) {
  1481. return;
  1482. }
  1483. logger.log(`USER ${id} connnected:`, user);
  1484. APP.UI.addUser(user);
  1485. // check the roles for the new user and reflect them
  1486. APP.UI.updateUserRole(user);
  1487. });
  1488. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1489. // The logic shared between RN and web.
  1490. commonUserLeftHandling(APP.store, room, user);
  1491. if (user.isHidden()) {
  1492. return;
  1493. }
  1494. logger.log(`USER ${id} LEFT:`, user);
  1495. APP.UI.onSharedVideoStop(id);
  1496. });
  1497. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1498. APP.store.dispatch(participantPresenceChanged(id, status));
  1499. const user = room.getParticipantById(id);
  1500. if (user) {
  1501. APP.UI.updateUserStatus(user, status);
  1502. }
  1503. });
  1504. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1505. if (this.isLocalId(id)) {
  1506. logger.info(`My role changed, new role: ${role}`);
  1507. APP.store.dispatch(localParticipantRoleChanged(role));
  1508. if (this.isModerator !== room.isModerator()) {
  1509. this.isModerator = room.isModerator();
  1510. APP.UI.updateLocalRole(room.isModerator());
  1511. }
  1512. } else {
  1513. APP.store.dispatch(participantRoleChanged(id, role));
  1514. const user = room.getParticipantById(id);
  1515. if (user) {
  1516. APP.UI.updateUserRole(user);
  1517. }
  1518. }
  1519. });
  1520. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1521. if (!track || track.isLocal()) {
  1522. return;
  1523. }
  1524. APP.store.dispatch(trackAdded(track));
  1525. });
  1526. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1527. if (!track || track.isLocal()) {
  1528. return;
  1529. }
  1530. APP.store.dispatch(trackRemoved(track));
  1531. });
  1532. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1533. let newLvl = lvl;
  1534. if (this.isLocalId(id)
  1535. && this.localAudio && this.localAudio.isMuted()) {
  1536. newLvl = 0;
  1537. }
  1538. if (config.debug) {
  1539. this.audioLevelsMap[id] = newLvl;
  1540. if (config.debugAudioLevels) {
  1541. logger.log(`AudioLevel:${id}/${newLvl}`);
  1542. }
  1543. }
  1544. APP.UI.setAudioLevel(id, newLvl);
  1545. });
  1546. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1547. if (participantThatMutedUs) {
  1548. APP.store.dispatch(participantMutedUs(participantThatMutedUs));
  1549. }
  1550. });
  1551. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1552. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1553. room.on(
  1554. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1555. (leavingIds, enteringIds) =>
  1556. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1557. room.on(
  1558. JitsiConferenceEvents.P2P_STATUS,
  1559. (jitsiConference, p2p) =>
  1560. APP.store.dispatch(p2pStatusChanged(p2p)));
  1561. room.on(
  1562. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1563. (id, connectionStatus) => APP.store.dispatch(
  1564. participantConnectionStatusChanged(id, connectionStatus)));
  1565. room.on(
  1566. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1567. id => APP.store.dispatch(dominantSpeakerChanged(id, room)));
  1568. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1569. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1570. JitsiParticipantConnectionStatus.INTERRUPTED));
  1571. });
  1572. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1573. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1574. JitsiParticipantConnectionStatus.ACTIVE));
  1575. });
  1576. room.on(
  1577. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1578. (id, displayName) => {
  1579. const formattedDisplayName
  1580. = getNormalizedDisplayName(displayName);
  1581. APP.store.dispatch(participantUpdated({
  1582. conference: room,
  1583. id,
  1584. name: formattedDisplayName
  1585. }));
  1586. APP.API.notifyDisplayNameChanged(id, {
  1587. displayName: formattedDisplayName,
  1588. formattedDisplayName:
  1589. appendSuffix(
  1590. formattedDisplayName
  1591. || interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME)
  1592. });
  1593. APP.UI.changeDisplayName(id, formattedDisplayName);
  1594. }
  1595. );
  1596. room.on(
  1597. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1598. (id, botType) => {
  1599. APP.store.dispatch(participantUpdated({
  1600. conference: room,
  1601. id,
  1602. botType
  1603. }));
  1604. }
  1605. );
  1606. room.on(
  1607. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1608. (...args) => APP.store.dispatch(endpointMessageReceived(...args)));
  1609. room.on(
  1610. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1611. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1612. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1613. room.setLocalParticipantProperty(
  1614. 'remoteControlSessionStatus',
  1615. isActive
  1616. );
  1617. APP.UI.setLocalRemoteControlActiveChanged();
  1618. });
  1619. /* eslint-disable max-params */
  1620. room.on(
  1621. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1622. (participant, name, oldValue, newValue) => {
  1623. switch (name) {
  1624. case 'remoteControlSessionStatus':
  1625. APP.UI.setRemoteControlActiveStatus(
  1626. participant.getId(),
  1627. newValue);
  1628. break;
  1629. default:
  1630. // ignore
  1631. }
  1632. });
  1633. room.on(JitsiConferenceEvents.KICKED, participant => {
  1634. APP.UI.hideStats();
  1635. APP.store.dispatch(kickedOut(room, participant));
  1636. // FIXME close
  1637. });
  1638. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1639. APP.store.dispatch(participantKicked(kicker, kicked));
  1640. });
  1641. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1642. APP.store.dispatch(suspendDetected());
  1643. });
  1644. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1645. this.muteAudio(muted);
  1646. });
  1647. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1648. this.muteVideo(muted);
  1649. });
  1650. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1651. ({ value }) => {
  1652. APP.UI.initEtherpad(value);
  1653. }
  1654. );
  1655. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1656. this.changeLocalEmail.bind(this));
  1657. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1658. APP.store.dispatch(participantUpdated({
  1659. conference: room,
  1660. id: from,
  1661. email: data.value
  1662. }));
  1663. });
  1664. room.addCommandListener(
  1665. this.commands.defaults.AVATAR_URL,
  1666. (data, from) => {
  1667. APP.store.dispatch(
  1668. participantUpdated({
  1669. conference: room,
  1670. id: from,
  1671. avatarURL: data.value
  1672. }));
  1673. });
  1674. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1675. (data, from) => {
  1676. APP.store.dispatch(
  1677. participantUpdated({
  1678. conference: room,
  1679. id: from,
  1680. avatarID: data.value
  1681. }));
  1682. });
  1683. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1684. this.changeLocalDisplayName.bind(this));
  1685. room.on(
  1686. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1687. ({ audio, video }) => {
  1688. APP.store.dispatch(
  1689. onStartMutedPolicyChanged(audio, video));
  1690. }
  1691. );
  1692. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1693. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1694. && APP.UI.notifyInitiallyMuted();
  1695. });
  1696. room.on(
  1697. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1698. APP.store.dispatch(dataChannelOpened());
  1699. }
  1700. );
  1701. // call hangup
  1702. APP.UI.addListener(UIEvents.HANGUP, () => {
  1703. this.hangup(true);
  1704. });
  1705. // logout
  1706. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1707. AuthHandler.logout(room).then(url => {
  1708. if (url) {
  1709. UIUtil.redirect(url);
  1710. } else {
  1711. this.hangup(true);
  1712. }
  1713. });
  1714. });
  1715. /* eslint-disable max-params */
  1716. APP.UI.addListener(
  1717. UIEvents.RESOLUTION_CHANGED,
  1718. (id, oldResolution, newResolution, delay) => {
  1719. sendAnalytics(createStreamSwitchDelayEvent(
  1720. {
  1721. 'old_resolution': oldResolution,
  1722. 'new_resolution': newResolution,
  1723. value: delay
  1724. }));
  1725. });
  1726. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1727. AuthHandler.authenticate(room);
  1728. });
  1729. APP.UI.addListener(
  1730. UIEvents.VIDEO_DEVICE_CHANGED,
  1731. cameraDeviceId => {
  1732. const videoWasMuted = this.isLocalVideoMuted();
  1733. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  1734. createLocalTracksF({
  1735. devices: [ 'video' ],
  1736. cameraDeviceId,
  1737. micDeviceId: null
  1738. })
  1739. .then(([ stream ]) => {
  1740. // if we are in audio only mode or video was muted before
  1741. // changing device, then mute
  1742. if (this.isAudioOnly() || videoWasMuted) {
  1743. return stream.mute()
  1744. .then(() => stream);
  1745. }
  1746. return stream;
  1747. })
  1748. .then(stream => {
  1749. // if we are screen sharing we do not want to stop it
  1750. if (this.isSharingScreen) {
  1751. return Promise.resolve();
  1752. }
  1753. return this.useVideoStream(stream);
  1754. })
  1755. .then(() => {
  1756. logger.log('switched local video device');
  1757. this._updateVideoDeviceId();
  1758. })
  1759. .catch(err => {
  1760. APP.store.dispatch(notifyCameraError(err));
  1761. });
  1762. }
  1763. );
  1764. APP.UI.addListener(
  1765. UIEvents.AUDIO_DEVICE_CHANGED,
  1766. micDeviceId => {
  1767. const audioWasMuted = this.isLocalAudioMuted();
  1768. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  1769. createLocalTracksF({
  1770. devices: [ 'audio' ],
  1771. cameraDeviceId: null,
  1772. micDeviceId
  1773. })
  1774. .then(([ stream ]) => {
  1775. // if audio was muted before changing the device, mute
  1776. // with the new device
  1777. if (audioWasMuted) {
  1778. return stream.mute()
  1779. .then(() => stream);
  1780. }
  1781. return stream;
  1782. })
  1783. .then(stream => this.useAudioStream(stream))
  1784. .then(() => {
  1785. logger.log('switched local audio device');
  1786. this._updateAudioDeviceId();
  1787. })
  1788. .catch(err => {
  1789. APP.store.dispatch(notifyMicError(err));
  1790. });
  1791. }
  1792. );
  1793. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1794. // FIXME On web video track is stored both in redux and in
  1795. // 'localVideo' field, video is attempted to be unmuted twice when
  1796. // turning off the audio only mode. This will crash the app with
  1797. // 'unmute operation is already in progress'.
  1798. // Because there's no logic in redux about creating new track in
  1799. // case unmute when not track exists the things have to go through
  1800. // muteVideo logic in such case.
  1801. const tracks = APP.store.getState()['features/base/tracks'];
  1802. const isTrackInRedux
  1803. = Boolean(
  1804. tracks.find(
  1805. track => track.jitsiTrack
  1806. && track.jitsiTrack.getType() === 'video'));
  1807. if (!isTrackInRedux) {
  1808. this.muteVideo(audioOnly);
  1809. }
  1810. // Immediately update the UI by having remote videos and the large
  1811. // video update themselves instead of waiting for some other event
  1812. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1813. // There is no guarantee another event will trigger the update
  1814. // immediately and in all situations, for example because a remote
  1815. // participant is having connection trouble so no status changes.
  1816. APP.UI.updateAllVideos();
  1817. });
  1818. APP.UI.addListener(
  1819. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1820. );
  1821. /* eslint-disable max-params */
  1822. APP.UI.addListener(
  1823. UIEvents.UPDATE_SHARED_VIDEO,
  1824. (url, state, time, isMuted, volume) => {
  1825. /* eslint-enable max-params */
  1826. // send start and stop commands once, and remove any updates
  1827. // that had left
  1828. if (state === 'stop'
  1829. || state === 'start'
  1830. || state === 'playing') {
  1831. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1832. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1833. value: url,
  1834. attributes: {
  1835. state,
  1836. time,
  1837. muted: isMuted,
  1838. volume
  1839. }
  1840. });
  1841. } else {
  1842. // in case of paused, in order to allow late users to join
  1843. // paused
  1844. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1845. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1846. value: url,
  1847. attributes: {
  1848. state,
  1849. time,
  1850. muted: isMuted,
  1851. volume
  1852. }
  1853. });
  1854. }
  1855. APP.store.dispatch(setSharedVideoStatus(state));
  1856. });
  1857. room.addCommandListener(
  1858. this.commands.defaults.SHARED_VIDEO,
  1859. ({ value, attributes }, id) => {
  1860. if (attributes.state === 'stop') {
  1861. APP.UI.onSharedVideoStop(id, attributes);
  1862. } else if (attributes.state === 'start') {
  1863. APP.UI.onSharedVideoStart(id, value, attributes);
  1864. } else if (attributes.state === 'playing'
  1865. || attributes.state === 'pause') {
  1866. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1867. }
  1868. });
  1869. },
  1870. /**
  1871. * Cleanups local conference on suspend.
  1872. */
  1873. onSuspendDetected() {
  1874. // After wake up, we will be in a state where conference is left
  1875. // there will be dialog shown to user.
  1876. // We do not want video/audio as we show an overlay and after it
  1877. // user need to rejoin or close, while waking up we can detect
  1878. // camera wakeup as a problem with device.
  1879. // We also do not care about device change, which happens
  1880. // on resume after suspending PC.
  1881. if (this.deviceChangeListener) {
  1882. JitsiMeetJS.mediaDevices.removeEventListener(
  1883. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1884. this.deviceChangeListener);
  1885. }
  1886. this.localVideo = null;
  1887. this.localAudio = null;
  1888. },
  1889. /**
  1890. * Callback invoked when the conference has been successfully joined.
  1891. * Initializes the UI and various other features.
  1892. *
  1893. * @private
  1894. * @returns {void}
  1895. */
  1896. _onConferenceJoined() {
  1897. APP.UI.initConference();
  1898. APP.keyboardshortcut.init();
  1899. APP.store.dispatch(conferenceJoined(room));
  1900. const displayName
  1901. = APP.store.getState()['features/base/settings'].displayName;
  1902. APP.UI.changeDisplayName('localVideoContainer', displayName);
  1903. },
  1904. /**
  1905. * Adds any room listener.
  1906. * @param {string} eventName one of the JitsiConferenceEvents
  1907. * @param {Function} listener the function to be called when the event
  1908. * occurs
  1909. */
  1910. addConferenceListener(eventName, listener) {
  1911. room.on(eventName, listener);
  1912. },
  1913. /**
  1914. * Removes any room listener.
  1915. * @param {string} eventName one of the JitsiConferenceEvents
  1916. * @param {Function} listener the listener to be removed.
  1917. */
  1918. removeConferenceListener(eventName, listener) {
  1919. room.off(eventName, listener);
  1920. },
  1921. /**
  1922. * Updates the list of current devices.
  1923. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  1924. * @private
  1925. * @returns {Promise}
  1926. */
  1927. _initDeviceList(setDeviceListChangeHandler = false) {
  1928. const { mediaDevices } = JitsiMeetJS;
  1929. if (mediaDevices.isDeviceListAvailable()
  1930. && mediaDevices.isDeviceChangeAvailable()) {
  1931. if (setDeviceListChangeHandler) {
  1932. this.deviceChangeListener = devices =>
  1933. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  1934. mediaDevices.addEventListener(
  1935. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1936. this.deviceChangeListener);
  1937. }
  1938. const { dispatch } = APP.store;
  1939. return dispatch(getAvailableDevices())
  1940. .then(devices => {
  1941. // Ugly way to synchronize real device IDs with local
  1942. // storage and settings menu. This is a workaround until
  1943. // getConstraints() method will be implemented in browsers.
  1944. this._updateAudioDeviceId();
  1945. this._updateVideoDeviceId();
  1946. APP.UI.onAvailableDevicesChanged(devices);
  1947. });
  1948. }
  1949. return Promise.resolve();
  1950. },
  1951. /**
  1952. * Updates the settings for the currently used video device, extracting
  1953. * the device id from the used track.
  1954. * @private
  1955. */
  1956. _updateVideoDeviceId() {
  1957. if (this.localVideo
  1958. && this.localVideo.videoType === 'camera') {
  1959. APP.store.dispatch(updateSettings({
  1960. cameraDeviceId: this.localVideo.getDeviceId()
  1961. }));
  1962. }
  1963. },
  1964. /**
  1965. * Updates the settings for the currently used audio device, extracting
  1966. * the device id from the used track.
  1967. * @private
  1968. */
  1969. _updateAudioDeviceId() {
  1970. if (this.localAudio) {
  1971. APP.store.dispatch(updateSettings({
  1972. micDeviceId: this.localAudio.getDeviceId()
  1973. }));
  1974. }
  1975. },
  1976. /**
  1977. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1978. * handle change of available media devices.
  1979. * @private
  1980. * @param {MediaDeviceInfo[]} devices
  1981. * @returns {Promise}
  1982. */
  1983. _onDeviceListChanged(devices) {
  1984. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  1985. APP.store.dispatch(updateDeviceList(devices));
  1986. const newDevices
  1987. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1988. devices,
  1989. this.isSharingScreen,
  1990. this.localVideo,
  1991. this.localAudio);
  1992. const promises = [];
  1993. const audioWasMuted = this.isLocalAudioMuted();
  1994. const videoWasMuted = this.isLocalVideoMuted();
  1995. const requestedInput = {
  1996. audio: Boolean(newDevices.audioinput),
  1997. video: Boolean(newDevices.videoinput)
  1998. };
  1999. if (typeof newDevices.audiooutput !== 'undefined') {
  2000. const { dispatch } = APP.store;
  2001. const setAudioOutputPromise
  2002. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2003. .catch(); // Just ignore any errors in catch block.
  2004. promises.push(setAudioOutputPromise);
  2005. }
  2006. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2007. // simpler):
  2008. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2009. // will return a stream using the old default device.
  2010. if (requestedInput.audio && this.localAudio) {
  2011. this.localAudio.stopStream();
  2012. }
  2013. if (requestedInput.video && this.localVideo) {
  2014. this.localVideo.stopStream();
  2015. }
  2016. // Let's handle unknown/non-preferred devices
  2017. const newAvailDevices
  2018. = APP.store.getState()['features/base/devices'].availableDevices;
  2019. let newAudioDevices = [];
  2020. let oldAudioDevices = [];
  2021. if (typeof newDevices.audiooutput === 'undefined') {
  2022. newAudioDevices = newAvailDevices.audioOutput;
  2023. oldAudioDevices = oldDevices.audioOutput;
  2024. }
  2025. if (!requestedInput.audio) {
  2026. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2027. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2028. }
  2029. // check for audio
  2030. if (newAudioDevices.length > 0) {
  2031. APP.store.dispatch(
  2032. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2033. }
  2034. // check for video
  2035. if (!requestedInput.video) {
  2036. APP.store.dispatch(
  2037. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2038. }
  2039. promises.push(
  2040. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2041. createLocalTracksF,
  2042. newDevices.videoinput,
  2043. newDevices.audioinput)
  2044. .then(tracks => {
  2045. // If audio or video muted before, or we unplugged current
  2046. // device and selected new one, then mute new track.
  2047. const muteSyncPromises = tracks.map(track => {
  2048. if ((track.isVideoTrack() && videoWasMuted)
  2049. || (track.isAudioTrack() && audioWasMuted)) {
  2050. return track.mute();
  2051. }
  2052. return Promise.resolve();
  2053. });
  2054. return Promise.all(muteSyncPromises)
  2055. .then(() =>
  2056. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2057. if (requestedInput[mediaType]) {
  2058. const useStream
  2059. = mediaType === 'audio'
  2060. ? this.useAudioStream.bind(this)
  2061. : this.useVideoStream.bind(this);
  2062. // Use the new stream or null if we failed to obtain it.
  2063. return useStream(tracks.find(track => track.getType() === mediaType) || null)
  2064. .then(() => {
  2065. mediaType === 'audio'
  2066. ? this._updateAudioDeviceId()
  2067. : this._updateVideoDeviceId();
  2068. });
  2069. }
  2070. return Promise.resolve();
  2071. })));
  2072. })
  2073. .then(() => {
  2074. // Log and sync known mute state.
  2075. if (audioWasMuted) {
  2076. sendAnalytics(createTrackMutedEvent(
  2077. 'audio',
  2078. 'device list changed'));
  2079. logger.log('Audio mute: device list changed');
  2080. muteLocalAudio(true);
  2081. }
  2082. if (!this.isSharingScreen && videoWasMuted) {
  2083. sendAnalytics(createTrackMutedEvent(
  2084. 'video',
  2085. 'device list changed'));
  2086. logger.log('Video mute: device list changed');
  2087. muteLocalVideo(true);
  2088. }
  2089. }));
  2090. return Promise.all(promises)
  2091. .then(() => {
  2092. APP.UI.onAvailableDevicesChanged(devices);
  2093. });
  2094. },
  2095. /**
  2096. * Determines whether or not the audio button should be enabled.
  2097. */
  2098. updateAudioIconEnabled() {
  2099. const audioMediaDevices
  2100. = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2101. const audioDeviceCount
  2102. = audioMediaDevices ? audioMediaDevices.length : 0;
  2103. // The audio functionality is considered available if there are any
  2104. // audio devices detected or if the local audio stream already exists.
  2105. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2106. logger.debug(
  2107. `Microphone button enabled: ${available}`,
  2108. `local audio: ${this.localAudio}`,
  2109. `audio devices: ${audioMediaDevices}`,
  2110. `device count: ${audioDeviceCount}`);
  2111. APP.store.dispatch(setAudioAvailable(available));
  2112. APP.API.notifyAudioAvailabilityChanged(available);
  2113. },
  2114. /**
  2115. * Determines whether or not the video button should be enabled.
  2116. */
  2117. updateVideoIconEnabled() {
  2118. const videoMediaDevices
  2119. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2120. const videoDeviceCount
  2121. = videoMediaDevices ? videoMediaDevices.length : 0;
  2122. // The video functionality is considered available if there are any
  2123. // video devices detected or if there is local video stream already
  2124. // active which could be either screensharing stream or a video track
  2125. // created before the permissions were rejected (through browser
  2126. // config).
  2127. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2128. logger.debug(
  2129. `Camera button enabled: ${available}`,
  2130. `local video: ${this.localVideo}`,
  2131. `video devices: ${videoMediaDevices}`,
  2132. `device count: ${videoDeviceCount}`);
  2133. APP.store.dispatch(setVideoAvailable(available));
  2134. APP.API.notifyVideoAvailabilityChanged(available);
  2135. },
  2136. /**
  2137. * Disconnect from the conference and optionally request user feedback.
  2138. * @param {boolean} [requestFeedback=false] if user feedback should be
  2139. * requested
  2140. */
  2141. hangup(requestFeedback = false) {
  2142. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2143. this._stopProxyConnection();
  2144. APP.store.dispatch(destroyLocalTracks());
  2145. this._localTracksInitialized = false;
  2146. this.localVideo = null;
  2147. this.localAudio = null;
  2148. // Remove unnecessary event listeners from firing callbacks.
  2149. if (this.deviceChangeListener) {
  2150. JitsiMeetJS.mediaDevices.removeEventListener(
  2151. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2152. this.deviceChangeListener);
  2153. }
  2154. APP.UI.removeAllListeners();
  2155. APP.remoteControl.removeAllListeners();
  2156. let requestFeedbackPromise;
  2157. if (requestFeedback) {
  2158. requestFeedbackPromise
  2159. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2160. // false because the thank you dialog shouldn't be displayed
  2161. .catch(() => Promise.resolve(false));
  2162. } else {
  2163. requestFeedbackPromise = Promise.resolve(true);
  2164. }
  2165. // All promises are returning Promise.resolve to make Promise.all to
  2166. // be resolved when both Promises are finished. Otherwise Promise.all
  2167. // will reject on first rejected Promise and we can redirect the page
  2168. // before all operations are done.
  2169. Promise.all([
  2170. requestFeedbackPromise,
  2171. this.leaveRoomAndDisconnect()
  2172. ]).then(values => {
  2173. this._room = undefined;
  2174. room = undefined;
  2175. APP.API.notifyReadyToClose();
  2176. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2177. });
  2178. },
  2179. /**
  2180. * Leaves the room and calls JitsiConnection.disconnect.
  2181. *
  2182. * @returns {Promise}
  2183. */
  2184. leaveRoomAndDisconnect() {
  2185. APP.store.dispatch(conferenceWillLeave(room));
  2186. if (room.isJoined()) {
  2187. return room.leave().then(disconnect, disconnect);
  2188. }
  2189. return disconnect();
  2190. },
  2191. /**
  2192. * Changes the email for the local user
  2193. * @param email {string} the new email
  2194. */
  2195. changeLocalEmail(email = '') {
  2196. const localParticipant = getLocalParticipant(APP.store.getState());
  2197. const formattedEmail = String(email).trim();
  2198. if (formattedEmail === localParticipant.email) {
  2199. return;
  2200. }
  2201. const localId = localParticipant.id;
  2202. APP.store.dispatch(participantUpdated({
  2203. // XXX Only the local participant is allowed to update without
  2204. // stating the JitsiConference instance (i.e. participant property
  2205. // `conference` for a remote participant) because the local
  2206. // participant is uniquely identified by the very fact that there is
  2207. // only one local participant.
  2208. id: localId,
  2209. local: true,
  2210. email: formattedEmail
  2211. }));
  2212. APP.store.dispatch(updateSettings({
  2213. email: formattedEmail
  2214. }));
  2215. APP.API.notifyEmailChanged(localId, {
  2216. email: formattedEmail
  2217. });
  2218. sendData(commands.EMAIL, formattedEmail);
  2219. },
  2220. /**
  2221. * Changes the avatar url for the local user
  2222. * @param url {string} the new url
  2223. */
  2224. changeLocalAvatarUrl(url = '') {
  2225. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2226. const formattedUrl = String(url).trim();
  2227. if (formattedUrl === avatarURL) {
  2228. return;
  2229. }
  2230. APP.store.dispatch(participantUpdated({
  2231. // XXX Only the local participant is allowed to update without
  2232. // stating the JitsiConference instance (i.e. participant property
  2233. // `conference` for a remote participant) because the local
  2234. // participant is uniquely identified by the very fact that there is
  2235. // only one local participant.
  2236. id,
  2237. local: true,
  2238. avatarURL: formattedUrl
  2239. }));
  2240. APP.store.dispatch(updateSettings({
  2241. avatarURL: formattedUrl
  2242. }));
  2243. sendData(commands.AVATAR_URL, url);
  2244. },
  2245. /**
  2246. * Sends a message via the data channel.
  2247. * @param {string} to the id of the endpoint that should receive the
  2248. * message. If "" - the message will be sent to all participants.
  2249. * @param {object} payload the payload of the message.
  2250. * @throws NetworkError or InvalidStateError or Error if the operation
  2251. * fails.
  2252. */
  2253. sendEndpointMessage(to, payload) {
  2254. room.sendEndpointMessage(to, payload);
  2255. },
  2256. /**
  2257. * Adds new listener.
  2258. * @param {String} eventName the name of the event
  2259. * @param {Function} listener the listener.
  2260. */
  2261. addListener(eventName, listener) {
  2262. eventEmitter.addListener(eventName, listener);
  2263. },
  2264. /**
  2265. * Removes listener.
  2266. * @param {String} eventName the name of the event that triggers the
  2267. * listener
  2268. * @param {Function} listener the listener.
  2269. */
  2270. removeListener(eventName, listener) {
  2271. eventEmitter.removeListener(eventName, listener);
  2272. },
  2273. /**
  2274. * Changes the display name for the local user
  2275. * @param nickname {string} the new display name
  2276. */
  2277. changeLocalDisplayName(nickname = '') {
  2278. const formattedNickname = getNormalizedDisplayName(nickname);
  2279. const { id, name } = getLocalParticipant(APP.store.getState());
  2280. if (formattedNickname === name) {
  2281. return;
  2282. }
  2283. APP.store.dispatch(participantUpdated({
  2284. // XXX Only the local participant is allowed to update without
  2285. // stating the JitsiConference instance (i.e. participant property
  2286. // `conference` for a remote participant) because the local
  2287. // participant is uniquely identified by the very fact that there is
  2288. // only one local participant.
  2289. id,
  2290. local: true,
  2291. name: formattedNickname
  2292. }));
  2293. APP.store.dispatch(updateSettings({
  2294. displayName: formattedNickname
  2295. }));
  2296. if (room) {
  2297. APP.UI.changeDisplayName(id, formattedNickname);
  2298. }
  2299. },
  2300. /**
  2301. * Returns the desktop sharing source id or undefined if the desktop sharing
  2302. * is not active at the moment.
  2303. *
  2304. * @returns {string|undefined} - The source id. If the track is not desktop
  2305. * track or the source id is not available, undefined will be returned.
  2306. */
  2307. getDesktopSharingSourceId() {
  2308. return this.localVideo.sourceId;
  2309. },
  2310. /**
  2311. * Returns the desktop sharing source type or undefined if the desktop
  2312. * sharing is not active at the moment.
  2313. *
  2314. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2315. * not desktop track or the source type is not available, undefined will be
  2316. * returned.
  2317. */
  2318. getDesktopSharingSourceType() {
  2319. return this.localVideo.sourceType;
  2320. },
  2321. /**
  2322. * Callback invoked by the external api create or update a direct connection
  2323. * from the local client to an external client.
  2324. *
  2325. * @param {Object} event - The object containing information that should be
  2326. * passed to the {@code ProxyConnectionService}.
  2327. * @returns {void}
  2328. */
  2329. onProxyConnectionEvent(event) {
  2330. if (!this._proxyConnection) {
  2331. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2332. /**
  2333. * Pass the {@code JitsiConnection} instance which will be used
  2334. * to fetch TURN credentials.
  2335. */
  2336. jitsiConnection: APP.connection,
  2337. /**
  2338. * The proxy connection feature is currently tailored towards
  2339. * taking a proxied video stream and showing it as a local
  2340. * desktop screen.
  2341. */
  2342. convertVideoToDesktop: true,
  2343. /**
  2344. * Callback invoked when the connection has been closed
  2345. * automatically. Triggers cleanup of screensharing if active.
  2346. *
  2347. * @returns {void}
  2348. */
  2349. onConnectionClosed: () => {
  2350. if (this._untoggleScreenSharing) {
  2351. this._untoggleScreenSharing();
  2352. }
  2353. },
  2354. /**
  2355. * Callback invoked to pass messages from the local client back
  2356. * out to the external client.
  2357. *
  2358. * @param {string} peerJid - The jid of the intended recipient
  2359. * of the message.
  2360. * @param {Object} data - The message that should be sent. For
  2361. * screensharing this is an iq.
  2362. * @returns {void}
  2363. */
  2364. onSendMessage: (peerJid, data) =>
  2365. APP.API.sendProxyConnectionEvent({
  2366. data,
  2367. to: peerJid
  2368. }),
  2369. /**
  2370. * Callback invoked when the remote peer of the proxy connection
  2371. * has provided a video stream, intended to be used as a local
  2372. * desktop stream.
  2373. *
  2374. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2375. * stream to use as a local desktop stream.
  2376. * @returns {void}
  2377. */
  2378. onRemoteStream: desktopStream => {
  2379. if (desktopStream.videoType !== 'desktop') {
  2380. logger.warn('Received a non-desktop stream to proxy.');
  2381. desktopStream.dispose();
  2382. return;
  2383. }
  2384. this.toggleScreenSharing(undefined, { desktopStream });
  2385. }
  2386. });
  2387. }
  2388. this._proxyConnection.processMessage(event);
  2389. },
  2390. /**
  2391. * Sets the video muted status.
  2392. *
  2393. * @param {boolean} muted - New muted status.
  2394. */
  2395. setVideoMuteStatus(muted) {
  2396. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2397. APP.API.notifyVideoMutedStatusChanged(muted);
  2398. },
  2399. /**
  2400. * Sets the audio muted status.
  2401. *
  2402. * @param {boolean} muted - New muted status.
  2403. */
  2404. setAudioMuteStatus(muted) {
  2405. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2406. APP.API.notifyAudioMutedStatusChanged(muted);
  2407. },
  2408. /**
  2409. * Dispatches the passed in feedback for submission. The submitted score
  2410. * should be a number inclusively between 1 through 5, or -1 for no score.
  2411. *
  2412. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2413. * score.
  2414. * @param {string} message - An optional message to attach to the feedback
  2415. * in addition to the score.
  2416. * @returns {void}
  2417. */
  2418. submitFeedback(score = -1, message = '') {
  2419. if (score === -1 || (score >= 1 && score <= 5)) {
  2420. APP.store.dispatch(submitFeedback(score, message, room));
  2421. }
  2422. },
  2423. /**
  2424. * Terminates any proxy screensharing connection that is active.
  2425. *
  2426. * @private
  2427. * @returns {void}
  2428. */
  2429. _stopProxyConnection() {
  2430. if (this._proxyConnection) {
  2431. this._proxyConnection.stop();
  2432. }
  2433. this._proxyConnection = null;
  2434. }
  2435. };