You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 96KB

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