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

conference.js 109KB

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