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

conference.js 95KB

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