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

conference.js 106KB

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