Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 96KB

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