Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 106KB

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