Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conference.js 92KB

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