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

conference.js 109KB

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