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 91KB

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