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

conference.js 112KB

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