Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 92KB

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