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

conference.js 92KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import { openConnection } from './connection';
  3. import AuthHandler from './modules/UI/authentication/AuthHandler';
  4. import Recorder from './modules/recorder/Recorder';
  5. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  6. import { reload, reportError } from './modules/util/helpers';
  7. import * as RemoteControlEvents
  8. from './service/remotecontrol/RemoteControlEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. import UIUtil from './modules/UI/util/UIUtil';
  11. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  12. import { initAnalytics, sendEvent } from './react/features/analytics';
  13. import EventEmitter from 'events';
  14. import {
  15. AVATAR_ID_COMMAND,
  16. AVATAR_URL_COMMAND,
  17. conferenceFailed,
  18. conferenceJoined,
  19. conferenceLeft,
  20. dataChannelOpened,
  21. EMAIL_COMMAND,
  22. lockStateChanged,
  23. p2pStatusChanged,
  24. sendLocalParticipant,
  25. toggleAudioOnly
  26. } from './react/features/base/conference';
  27. import { updateDeviceList } from './react/features/base/devices';
  28. import {
  29. isAnalyticsEnabled,
  30. isFatalJitsiConnectionError,
  31. JitsiConferenceErrors,
  32. JitsiConferenceEvents,
  33. JitsiConnectionErrors,
  34. JitsiConnectionEvents,
  35. JitsiMediaDevicesEvents,
  36. JitsiParticipantConnectionStatus,
  37. JitsiTrackErrors,
  38. JitsiTrackEvents
  39. } from './react/features/base/lib-jitsi-meet';
  40. import {
  41. isVideoMutedByUser,
  42. MEDIA_TYPE,
  43. setAudioAvailable,
  44. setAudioMuted,
  45. setVideoAvailable,
  46. setVideoMuted
  47. } from './react/features/base/media';
  48. import {
  49. dominantSpeakerChanged,
  50. getLocalParticipant,
  51. getParticipantById,
  52. localParticipantConnectionStatusChanged,
  53. localParticipantRoleChanged,
  54. MAX_DISPLAY_NAME_LENGTH,
  55. participantConnectionStatusChanged,
  56. participantJoined,
  57. participantLeft,
  58. participantPresenceChanged,
  59. participantRoleChanged,
  60. participantUpdated
  61. } from './react/features/base/participants';
  62. import {
  63. createLocalTracksF,
  64. isLocalTrackMuted,
  65. replaceLocalTrack,
  66. trackAdded,
  67. trackRemoved
  68. } from './react/features/base/tracks';
  69. import { getLocationContextRoot } from './react/features/base/util';
  70. import { statsEmitter } from './react/features/connection-indicator';
  71. import { showDesktopPicker } from './react/features/desktop-picker';
  72. import { maybeOpenFeedbackDialog } from './react/features/feedback';
  73. import {
  74. mediaPermissionPromptVisibilityChanged,
  75. suspendDetected
  76. } from './react/features/overlay';
  77. import {
  78. isButtonEnabled,
  79. showDesktopSharingButton
  80. } from './react/features/toolbox';
  81. const logger = require('jitsi-meet-logger').getLogger(__filename);
  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. () => {
  192. APP.settings.setWelcomePageEnabled(true);
  193. assignWindowLocationPathname('./');
  194. },
  195. 3000);
  196. }
  197. }
  198. /**
  199. * Assigns a specific pathname to window.location.pathname taking into account
  200. * the context root of the Web app.
  201. *
  202. * @param {string} pathname - The pathname to assign to
  203. * window.location.pathname. If the specified pathname is relative, the context
  204. * root of the Web app will be prepended to the specified pathname before
  205. * assigning it to window.location.pathname.
  206. * @return {void}
  207. */
  208. function assignWindowLocationPathname(pathname) {
  209. const windowLocation = window.location;
  210. let newPathname = pathname;
  211. if (!newPathname.startsWith('/')) {
  212. // A pathname equal to ./ specifies the current directory. It will be
  213. // fine but pointless to include it because contextRoot is the current
  214. // directory.
  215. newPathname.startsWith('./')
  216. && (newPathname = newPathname.substring(2));
  217. newPathname = getLocationContextRoot(windowLocation) + newPathname;
  218. }
  219. windowLocation.pathname = newPathname;
  220. }
  221. /**
  222. *
  223. */
  224. class ConferenceConnector {
  225. /**
  226. *
  227. */
  228. constructor(resolve, reject) {
  229. this._resolve = resolve;
  230. this._reject = reject;
  231. this.reconnectTimeout = null;
  232. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  233. this._handleConferenceJoined.bind(this));
  234. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  235. this._onConferenceFailed.bind(this));
  236. room.on(JitsiConferenceEvents.CONFERENCE_ERROR,
  237. this._onConferenceError.bind(this));
  238. }
  239. /**
  240. *
  241. */
  242. _handleConferenceFailed(err) {
  243. this._unsubscribe();
  244. this._reject(err);
  245. }
  246. /**
  247. *
  248. */
  249. _onConferenceFailed(err, ...params) {
  250. APP.store.dispatch(conferenceFailed(room, err, ...params));
  251. logger.error('CONFERENCE FAILED:', err, ...params);
  252. switch (err) {
  253. case JitsiConferenceErrors.CONNECTION_ERROR: {
  254. const [ msg ] = params;
  255. APP.UI.notifyConnectionFailed(msg);
  256. break;
  257. }
  258. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  259. // let's show some auth not allowed page
  260. assignWindowLocationPathname('static/authError.html');
  261. break;
  262. }
  263. // not enough rights to create conference
  264. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  265. // Schedule reconnect to check if someone else created the room.
  266. this.reconnectTimeout = setTimeout(() => room.join(), 5000);
  267. const { password }
  268. = APP.store.getState()['features/base/conference'];
  269. AuthHandler.requireAuth(room, password);
  270. break;
  271. }
  272. case JitsiConferenceErrors.RESERVATION_ERROR: {
  273. const [ code, msg ] = params;
  274. APP.UI.notifyReservationError(code, msg);
  275. break;
  276. }
  277. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  278. APP.UI.notifyGracefulShutdown();
  279. break;
  280. case JitsiConferenceErrors.JINGLE_FATAL_ERROR:
  281. APP.UI.notifyInternalError();
  282. break;
  283. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  284. const [ reason ] = params;
  285. APP.UI.hideStats();
  286. APP.UI.notifyConferenceDestroyed(reason);
  287. break;
  288. }
  289. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  290. // What really happens there is that the library is not ready yet,
  291. // because Jicofo is not available, but it is going to give it another
  292. // try.
  293. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  294. const [ focus, retrySec ] = params;
  295. APP.UI.notifyFocusDisconnected(focus, retrySec);
  296. break;
  297. }
  298. case JitsiConferenceErrors.FOCUS_LEFT:
  299. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  300. // FIXME the conference should be stopped by the library and not by
  301. // the app. Both the errors above are unrecoverable from the library
  302. // perspective.
  303. room.leave().then(() => connection.disconnect());
  304. break;
  305. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  306. connection.disconnect();
  307. APP.UI.notifyMaxUsersLimitReached();
  308. break;
  309. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  310. reload();
  311. break;
  312. default:
  313. this._handleConferenceFailed(err, ...params);
  314. }
  315. }
  316. /**
  317. *
  318. */
  319. _onConferenceError(err, ...params) {
  320. logger.error('CONFERENCE Error:', err, params);
  321. switch (err) {
  322. case JitsiConferenceErrors.CHAT_ERROR:
  323. logger.error('Chat error.', err);
  324. if (isButtonEnabled('chat')) {
  325. const [ code, msg ] = params;
  326. APP.UI.showChatError(code, msg);
  327. }
  328. break;
  329. default:
  330. logger.error('Unknown error.', err);
  331. }
  332. }
  333. /**
  334. *
  335. */
  336. _unsubscribe() {
  337. room.off(
  338. JitsiConferenceEvents.CONFERENCE_JOINED,
  339. this._handleConferenceJoined);
  340. room.off(
  341. JitsiConferenceEvents.CONFERENCE_FAILED,
  342. this._onConferenceFailed);
  343. if (this.reconnectTimeout !== null) {
  344. clearTimeout(this.reconnectTimeout);
  345. }
  346. AuthHandler.closeAuth();
  347. }
  348. /**
  349. *
  350. */
  351. _handleConferenceJoined() {
  352. this._unsubscribe();
  353. this._resolve();
  354. }
  355. /**
  356. *
  357. */
  358. connect() {
  359. room.join();
  360. }
  361. }
  362. /**
  363. * Disconnects the connection.
  364. * @returns resolved Promise. We need this in order to make the Promise.all
  365. * call in hangup() to resolve when all operations are finished.
  366. */
  367. function disconnect() {
  368. connection.disconnect();
  369. APP.API.notifyConferenceLeft(APP.conference.roomName);
  370. return Promise.resolve();
  371. }
  372. /**
  373. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  374. *
  375. * @param {JitsiConnectionError} error - The reported error.
  376. * @returns {void}
  377. * @private
  378. */
  379. function _connectionFailedHandler(error) {
  380. if (isFatalJitsiConnectionError(error)) {
  381. APP.connection.removeEventListener(
  382. JitsiConnectionEvents.CONNECTION_FAILED,
  383. _connectionFailedHandler);
  384. if (room) {
  385. room.leave();
  386. }
  387. }
  388. }
  389. export default {
  390. /**
  391. * Flag used to delay modification of the muted status of local media tracks
  392. * until those are created (or not, but at that point it's certain that
  393. * the tracks won't exist).
  394. */
  395. _localTracksInitialized: false,
  396. isModerator: false,
  397. isSharingScreen: false,
  398. /**
  399. * Indicates if the desktop sharing functionality has been enabled.
  400. * It takes into consideration {@link isDesktopSharingDisabledByConfig}
  401. * as well as the status returned by
  402. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  403. * either if the desktop sharing is not supported by the current browser
  404. * or if it was disabled through lib-jitsi-meet specific options (check
  405. * config.js for listed options).
  406. */
  407. isDesktopSharingEnabled: false,
  408. /**
  409. * Set to <tt>true</tt> if the desktop sharing functionality has been
  410. * explicitly disabled in the config.
  411. */
  412. isDesktopSharingDisabledByConfig: false,
  413. /**
  414. * The text displayed when the desktop sharing button is disabled through
  415. * the config. The value is set through
  416. * {@link interfaceConfig.DESKTOP_SHARING_BUTTON_DISABLED_TOOLTIP}.
  417. */
  418. desktopSharingDisabledTooltip: null,
  419. /*
  420. * Whether the local "raisedHand" flag is on.
  421. */
  422. isHandRaised: false,
  423. /*
  424. * Whether the local participant is the dominant speaker in the conference.
  425. */
  426. isDominantSpeaker: false,
  427. /**
  428. * The local audio track (if any).
  429. * FIXME tracks from redux store should be the single source of truth
  430. * @type {JitsiLocalTrack|null}
  431. */
  432. localAudio: null,
  433. /**
  434. * The local video track (if any).
  435. * FIXME tracks from redux store should be the single source of truth, but
  436. * more refactoring is required around screen sharing ('localVideo' usages).
  437. * @type {JitsiLocalTrack|null}
  438. */
  439. localVideo: null,
  440. /**
  441. * Creates local media tracks and connects to a room. Will show error
  442. * dialogs in case accessing the local microphone and/or camera failed. Will
  443. * show guidance overlay for users on how to give access to camera and/or
  444. * microphone.
  445. * @param {string} roomName
  446. * @param {object} options
  447. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  448. * only audio track will be created and the audio only mode will be turned
  449. * on.
  450. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  451. * should start with screensharing instead of camera video.
  452. * @param {boolean} options.startWithAudioMuted - will start the conference
  453. * without any audio tracks.
  454. * @param {boolean} options.startWithVideoMuted - will start the conference
  455. * without any video tracks.
  456. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  457. */
  458. createInitialLocalTracksAndConnect(roomName, options = {}) {
  459. let audioAndVideoError,
  460. audioOnlyError,
  461. screenSharingError,
  462. videoOnlyError;
  463. const initialDevices = [];
  464. let requestedAudio = false;
  465. let requestedVideo = false;
  466. if (!options.startWithAudioMuted) {
  467. initialDevices.push('audio');
  468. requestedAudio = true;
  469. }
  470. if (!options.startWithVideoMuted
  471. && !options.startAudioOnly
  472. && !options.startScreenSharing) {
  473. initialDevices.push('video');
  474. requestedVideo = true;
  475. }
  476. JitsiMeetJS.mediaDevices.addEventListener(
  477. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  478. browser =>
  479. APP.store.dispatch(
  480. mediaPermissionPromptVisibilityChanged(true, browser))
  481. );
  482. let tryCreateLocalTracks;
  483. // Enable audio only mode
  484. if (config.startAudioOnly) {
  485. APP.store.dispatch(toggleAudioOnly());
  486. }
  487. // FIXME is there any simpler way to rewrite this spaghetti below ?
  488. if (options.startScreenSharing) {
  489. tryCreateLocalTracks = this._createDesktopTrack()
  490. .then(desktopStream => {
  491. if (!requestedAudio) {
  492. return [ desktopStream ];
  493. }
  494. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  495. .then(([ audioStream ]) =>
  496. [ desktopStream, audioStream ])
  497. .catch(error => {
  498. audioOnlyError = error;
  499. return [ desktopStream ];
  500. });
  501. })
  502. .catch(error => {
  503. logger.error('Failed to obtain desktop stream', error);
  504. screenSharingError = error;
  505. return requestedAudio
  506. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  507. : [];
  508. })
  509. .catch(error => {
  510. audioOnlyError = error;
  511. return [];
  512. });
  513. } else if (!requestedAudio && !requestedVideo) {
  514. // Resolve with no tracks
  515. tryCreateLocalTracks = Promise.resolve([]);
  516. } else {
  517. tryCreateLocalTracks = createLocalTracksF(
  518. { devices: initialDevices }, true)
  519. .catch(err => {
  520. if (requestedAudio && requestedVideo) {
  521. // Try audio only...
  522. audioAndVideoError = err;
  523. return (
  524. createLocalTracksF({ devices: [ 'audio' ] }, true));
  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 && this._room.myUserId();
  977. },
  978. /**
  979. * Indicates if recording is supported in this conference.
  980. */
  981. isRecordingSupported() {
  982. return this._room && this._room.isRecordingSupported();
  983. },
  984. /**
  985. * Returns the recording state or undefined if the room is not defined.
  986. */
  987. getRecordingState() {
  988. return this._room ? this._room.getRecordingState() : undefined;
  989. },
  990. /**
  991. * Will be filled with values only when config.debug is enabled.
  992. * Its used by torture to check audio levels.
  993. */
  994. audioLevelsMap: {},
  995. /**
  996. * Returns the stored audio level (stored only if config.debug is enabled)
  997. * @param id the id for the user audio level to return (the id value is
  998. * returned for the participant using getMyUserId() method)
  999. */
  1000. getPeerSSRCAudioLevel(id) {
  1001. return this.audioLevelsMap[id];
  1002. },
  1003. /**
  1004. * @return {number} the number of participants in the conference with at
  1005. * least one track.
  1006. */
  1007. getNumberOfParticipantsWithTracks() {
  1008. return this._room.getParticipants()
  1009. .filter(p => p.getTracks().length > 0)
  1010. .length;
  1011. },
  1012. /**
  1013. * Returns the stats.
  1014. */
  1015. getStats() {
  1016. return room.connectionQuality.getStats();
  1017. },
  1018. // end used by torture
  1019. getLogs() {
  1020. return room.getLogs();
  1021. },
  1022. /**
  1023. * Download logs, a function that can be called from console while
  1024. * debugging.
  1025. * @param filename (optional) specify target filename
  1026. */
  1027. saveLogs(filename = 'meetlog.json') {
  1028. // this can be called from console and will not have reference to this
  1029. // that's why we reference the global var
  1030. const logs = APP.conference.getLogs();
  1031. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1032. const elem = document.createElement('a');
  1033. elem.download = filename;
  1034. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  1035. elem.dataset.downloadurl
  1036. = [ 'text/json', elem.download, elem.href ].join(':');
  1037. elem.dispatchEvent(new MouseEvent('click', {
  1038. view: window,
  1039. bubbles: true,
  1040. cancelable: false
  1041. }));
  1042. },
  1043. /**
  1044. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1045. * desire to keep room private to this instance and (2) the need of other
  1046. * modules to send and receive commands to and from participants.
  1047. * Eventually, this instance remains in control with respect to the
  1048. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1049. * JitsiConference) is to be used in the implementation of the Command(s)
  1050. * API of this instance.
  1051. */
  1052. commands: {
  1053. /**
  1054. * Known custom conference commands.
  1055. */
  1056. defaults: commands,
  1057. /**
  1058. * Receives notifications from other participants about commands aka
  1059. * custom events (sent by sendCommand or sendCommandOnce methods).
  1060. * @param command {String} the name of the command
  1061. * @param handler {Function} handler for the command
  1062. */
  1063. addCommandListener() {
  1064. // eslint-disable-next-line prefer-rest-params
  1065. room.addCommandListener(...arguments);
  1066. },
  1067. /**
  1068. * Removes command.
  1069. * @param name {String} the name of the command.
  1070. */
  1071. removeCommand() {
  1072. // eslint-disable-next-line prefer-rest-params
  1073. room.removeCommand(...arguments);
  1074. },
  1075. /**
  1076. * Sends command.
  1077. * @param name {String} the name of the command.
  1078. * @param values {Object} with keys and values that will be sent.
  1079. */
  1080. sendCommand() {
  1081. // eslint-disable-next-line prefer-rest-params
  1082. room.sendCommand(...arguments);
  1083. },
  1084. /**
  1085. * Sends command one time.
  1086. * @param name {String} the name of the command.
  1087. * @param values {Object} with keys and values that will be sent.
  1088. */
  1089. sendCommandOnce() {
  1090. // eslint-disable-next-line prefer-rest-params
  1091. room.sendCommandOnce(...arguments);
  1092. }
  1093. },
  1094. _createRoom(localTracks) {
  1095. room
  1096. = connection.initJitsiConference(
  1097. APP.conference.roomName,
  1098. this._getConferenceOptions());
  1099. this._setLocalAudioVideoStreams(localTracks);
  1100. this._room = room; // FIXME do not use this
  1101. sendLocalParticipant(APP.store, room);
  1102. this._setupListeners();
  1103. },
  1104. /**
  1105. * Sets local video and audio streams.
  1106. * @param {JitsiLocalTrack[]} tracks=[]
  1107. * @returns {Promise[]}
  1108. * @private
  1109. */
  1110. _setLocalAudioVideoStreams(tracks = []) {
  1111. return tracks.map(track => {
  1112. if (track.isAudioTrack()) {
  1113. return this.useAudioStream(track);
  1114. } else if (track.isVideoTrack()) {
  1115. return this.useVideoStream(track);
  1116. }
  1117. logger.error(
  1118. 'Ignored not an audio nor a video track: ', track);
  1119. return Promise.resolve();
  1120. });
  1121. },
  1122. _getConferenceOptions() {
  1123. const options = config;
  1124. if (config.enableRecording && !config.recordingType) {
  1125. options.recordingType
  1126. = config.hosts && (typeof config.hosts.jirecon !== 'undefined')
  1127. ? 'jirecon'
  1128. : 'colibri';
  1129. }
  1130. const nick = APP.settings.getDisplayName();
  1131. if (nick) {
  1132. options.displayName = nick;
  1133. }
  1134. return options;
  1135. },
  1136. /**
  1137. * Start using provided video stream.
  1138. * Stops previous video stream.
  1139. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1140. * @returns {Promise}
  1141. */
  1142. useVideoStream(newStream) {
  1143. return APP.store.dispatch(
  1144. replaceLocalTrack(this.localVideo, newStream, room))
  1145. .then(() => {
  1146. this.localVideo = newStream;
  1147. if (newStream) {
  1148. this.isSharingScreen = newStream.videoType === 'desktop';
  1149. APP.UI.addLocalStream(newStream);
  1150. } else {
  1151. this.isSharingScreen = false;
  1152. }
  1153. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1154. APP.UI.updateDesktopSharingButtons();
  1155. });
  1156. },
  1157. /**
  1158. * Start using provided audio stream.
  1159. * Stops previous audio stream.
  1160. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1161. * @returns {Promise}
  1162. */
  1163. useAudioStream(newStream) {
  1164. return APP.store.dispatch(
  1165. replaceLocalTrack(this.localAudio, newStream, room))
  1166. .then(() => {
  1167. this.localAudio = newStream;
  1168. if (newStream) {
  1169. APP.UI.addLocalStream(newStream);
  1170. }
  1171. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1172. });
  1173. },
  1174. /**
  1175. * Triggers a tooltip to display when a feature was attempted to be used
  1176. * while in audio only mode.
  1177. *
  1178. * @param {string} featureName - The name of the feature that attempted to
  1179. * toggle.
  1180. * @private
  1181. * @returns {void}
  1182. */
  1183. _displayAudioOnlyTooltip(featureName) {
  1184. let buttonName = null;
  1185. let tooltipElementId = null;
  1186. switch (featureName) {
  1187. case 'screenShare':
  1188. buttonName = 'desktop';
  1189. tooltipElementId = 'screenshareWhileAudioOnly';
  1190. break;
  1191. case 'videoMute':
  1192. buttonName = 'camera';
  1193. tooltipElementId = 'unmuteWhileAudioOnly';
  1194. break;
  1195. }
  1196. if (tooltipElementId) {
  1197. APP.UI.showToolbar(6000);
  1198. APP.UI.showCustomToolbarPopup(
  1199. buttonName, tooltipElementId, true, 5000);
  1200. }
  1201. },
  1202. /**
  1203. * Returns whether or not the conference is currently in audio only mode.
  1204. *
  1205. * @returns {boolean}
  1206. */
  1207. isAudioOnly() {
  1208. return Boolean(
  1209. APP.store.getState()['features/base/conference'].audioOnly);
  1210. },
  1211. videoSwitchInProgress: false,
  1212. /**
  1213. * This fields stores a handler which will create a Promise which turns off
  1214. * the screen sharing and restores the previous video state (was there
  1215. * any video, before switching to screen sharing ? was it muted ?).
  1216. *
  1217. * Once called this fields is cleared to <tt>null</tt>.
  1218. * @type {Function|null}
  1219. */
  1220. _untoggleScreenSharing: null,
  1221. /**
  1222. * Creates a Promise which turns off the screen sharing and restores
  1223. * the previous state described by the arguments.
  1224. *
  1225. * This method is bound to the appropriate values, after switching to screen
  1226. * sharing and stored in {@link _untoggleScreenSharing}.
  1227. *
  1228. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1229. * used, before switching to screen sharing.
  1230. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1231. * switching to screen sharing.
  1232. * @return {Promise} resolved after the screen sharing is turned off, or
  1233. * rejected with some error (no idea what kind of error, possible GUM error)
  1234. * in case it fails.
  1235. * @private
  1236. */
  1237. _turnScreenSharingOff(didHaveVideo, wasVideoMuted) {
  1238. this._untoggleScreenSharing = null;
  1239. this.videoSwitchInProgress = true;
  1240. APP.remoteControl.receiver.stop();
  1241. let promise = null;
  1242. if (didHaveVideo) {
  1243. promise = createLocalTracksF({ devices: [ 'video' ] })
  1244. .then(([ stream ]) => this.useVideoStream(stream))
  1245. .then(() => {
  1246. sendEvent(
  1247. 'conference.sharingDesktop.stop');
  1248. logger.log('switched back to local video');
  1249. if (!this.localVideo && wasVideoMuted) {
  1250. return Promise.reject('No local video to be muted!');
  1251. } else if (wasVideoMuted && this.localVideo) {
  1252. return this.localVideo.mute();
  1253. }
  1254. })
  1255. .catch(error => {
  1256. logger.error('failed to switch back to local video', error);
  1257. return this.useVideoStream(null).then(() =>
  1258. // Still fail with the original err
  1259. Promise.reject(error)
  1260. );
  1261. });
  1262. } else {
  1263. promise = this.useVideoStream(null);
  1264. }
  1265. return promise.then(
  1266. () => {
  1267. this.videoSwitchInProgress = false;
  1268. },
  1269. error => {
  1270. this.videoSwitchInProgress = false;
  1271. throw error;
  1272. });
  1273. },
  1274. /**
  1275. * Toggles between screen sharing and camera video if the toggle parameter
  1276. * is not specified and starts the procedure for obtaining new screen
  1277. * sharing/video track otherwise.
  1278. *
  1279. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1280. * obtained. If false - new video track will be obtain. If not specified -
  1281. * toggles between screen sharing and camera video.
  1282. * @param {Object} [options] - Screen sharing options that will be passed to
  1283. * createLocalTracks.
  1284. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1285. * sources that have to be displayed in the desktop picker window ('screen',
  1286. * 'window', etc.).
  1287. * @return {Promise.<T>}
  1288. */
  1289. toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1290. if (this.videoSwitchInProgress) {
  1291. return Promise.reject('Switch in progress.');
  1292. }
  1293. if (!this.isDesktopSharingEnabled) {
  1294. return Promise.reject(
  1295. 'Cannot toggle screen sharing: not supported.');
  1296. }
  1297. if (this.isAudioOnly()) {
  1298. this._displayAudioOnlyTooltip('screenShare');
  1299. return Promise.reject('No screensharing in audio only mode');
  1300. }
  1301. if (toggle) {
  1302. return this._switchToScreenSharing(options);
  1303. }
  1304. return this._untoggleScreenSharing();
  1305. },
  1306. /**
  1307. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1308. * @param {Object} [options] - Screen sharing options that will be passed to
  1309. * createLocalTracks.
  1310. *
  1311. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1312. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1313. * {@link JitsiTrackError}.
  1314. *
  1315. * @private
  1316. */
  1317. _createDesktopTrack(options = {}) {
  1318. let externalInstallation = false;
  1319. let DSExternalInstallationInProgress = false;
  1320. const didHaveVideo = Boolean(this.localVideo);
  1321. const wasVideoMuted = this.isLocalVideoMuted();
  1322. return createLocalTracksF({
  1323. desktopSharingSources: options.desktopSharingSources,
  1324. devices: [ 'desktop' ],
  1325. desktopSharingExtensionExternalInstallation: {
  1326. interval: 500,
  1327. checkAgain: () => DSExternalInstallationInProgress,
  1328. listener: (status, url) => {
  1329. switch (status) {
  1330. case 'waitingForExtension': {
  1331. DSExternalInstallationInProgress = true;
  1332. externalInstallation = true;
  1333. const listener = () => {
  1334. // Wait a little bit more just to be sure that we
  1335. // won't miss the extension installation
  1336. setTimeout(
  1337. () => {
  1338. DSExternalInstallationInProgress = false;
  1339. },
  1340. 500);
  1341. APP.UI.removeListener(
  1342. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1343. listener);
  1344. };
  1345. APP.UI.addListener(
  1346. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1347. listener);
  1348. APP.UI.showExtensionExternalInstallationDialog(url);
  1349. break;
  1350. }
  1351. case 'extensionFound':
  1352. // Close the dialog.
  1353. externalInstallation && $.prompt.close();
  1354. break;
  1355. default:
  1356. // Unknown status
  1357. }
  1358. }
  1359. }
  1360. }).then(([ desktopStream ]) => {
  1361. // Stores the "untoggle" handler which remembers whether was
  1362. // there any video before and whether was it muted.
  1363. this._untoggleScreenSharing
  1364. = this._turnScreenSharingOff
  1365. .bind(this, didHaveVideo, wasVideoMuted);
  1366. desktopStream.on(
  1367. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1368. () => {
  1369. // If the stream was stopped during screen sharing
  1370. // session then we should switch back to video.
  1371. this.isSharingScreen
  1372. && this._untoggleScreenSharing
  1373. && this._untoggleScreenSharing();
  1374. }
  1375. );
  1376. // close external installation dialog on success.
  1377. externalInstallation && $.prompt.close();
  1378. return desktopStream;
  1379. }, error => {
  1380. DSExternalInstallationInProgress = false;
  1381. // close external installation dialog on success.
  1382. externalInstallation && $.prompt.close();
  1383. throw error;
  1384. });
  1385. },
  1386. /**
  1387. * Tries to switch to the screenshairng mode by disposing camera stream and
  1388. * replacing it with a desktop one.
  1389. *
  1390. * @param {Object} [options] - Screen sharing options that will be passed to
  1391. * createLocalTracks.
  1392. *
  1393. * @return {Promise} - A Promise resolved if the operation succeeds or
  1394. * rejected with some unknown type of error in case it fails. Promise will
  1395. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1396. *
  1397. * @private
  1398. */
  1399. _switchToScreenSharing(options = {}) {
  1400. if (this.videoSwitchInProgress) {
  1401. return Promise.reject('Switch in progress.');
  1402. }
  1403. this.videoSwitchInProgress = true;
  1404. return this._createDesktopTrack(options)
  1405. .then(stream => this.useVideoStream(stream))
  1406. .then(() => {
  1407. this.videoSwitchInProgress = false;
  1408. sendEvent('conference.sharingDesktop.start');
  1409. logger.log('sharing local desktop');
  1410. })
  1411. .catch(error => {
  1412. this.videoSwitchInProgress = false;
  1413. // Pawel: With this call I'm trying to preserve the original
  1414. // behaviour although it is not clear why would we "untoggle"
  1415. // on failure. I suppose it was to restore video in case there
  1416. // was some problem during "this.useVideoStream(desktopStream)".
  1417. // It's important to note that the handler will not be available
  1418. // if we fail early on trying to get desktop media (which makes
  1419. // sense, because the camera video is still being used, so
  1420. // nothing to "untoggle").
  1421. if (this._untoggleScreenSharing) {
  1422. this._untoggleScreenSharing();
  1423. }
  1424. // FIXME the code inside of _handleScreenSharingError is
  1425. // asynchronous, but does not return a Promise and is not part
  1426. // of the current Promise chain.
  1427. this._handleScreenSharingError(error);
  1428. return Promise.reject(error);
  1429. });
  1430. },
  1431. /**
  1432. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1433. * trying to create screensharing track. It will either do nothing if
  1434. * the dialog was canceled on user's request or display inline installation
  1435. * dialog and ask the user to install the extension, once the extension is
  1436. * installed it will switch the conference to screensharing. The last option
  1437. * is that an unrecoverable error dialog will be displayed.
  1438. * @param {JitsiTrackError} error - The error returned by
  1439. * {@link _createDesktopTrack} Promise.
  1440. * @private
  1441. */
  1442. _handleScreenSharingError(error) {
  1443. if (error.name === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1444. return;
  1445. }
  1446. logger.error('failed to share local desktop', error);
  1447. if (error.name
  1448. === JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1449. // If start with screen sharing the extension will fail to install
  1450. // (if not found), because the request has been triggered by the
  1451. // script. Show a dialog which asks user to click "install" and try
  1452. // again switching to the screen sharing.
  1453. APP.UI.showExtensionInlineInstallationDialog(
  1454. () => {
  1455. // eslint-disable-next-line no-empty-function
  1456. this.toggleScreenSharing().catch(() => {});
  1457. }
  1458. );
  1459. return;
  1460. } else if (error.name === JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED) {
  1461. APP.UI.showExtensionRequiredDialog(
  1462. config.desktopSharingFirefoxExtensionURL
  1463. );
  1464. return;
  1465. }
  1466. // Handling:
  1467. // JitsiTrackErrors.PERMISSION_DENIED
  1468. // JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1469. // JitsiTrackErrors.GENERAL
  1470. // and any other
  1471. let dialogTxt;
  1472. let dialogTitleKey;
  1473. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1474. dialogTxt = APP.translation.generateTranslationHTML(
  1475. 'dialog.screenSharingPermissionDeniedError');
  1476. dialogTitleKey = 'dialog.error';
  1477. } else {
  1478. dialogTxt = APP.translation.generateTranslationHTML(
  1479. 'dialog.failtoinstall');
  1480. dialogTitleKey = 'dialog.permissionDenied';
  1481. }
  1482. APP.UI.messageHandler.openDialog(dialogTitleKey, dialogTxt, false);
  1483. },
  1484. /**
  1485. * Setup interaction between conference and UI.
  1486. */
  1487. _setupListeners() {
  1488. // add local streams when joined to the conference
  1489. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1490. APP.store.dispatch(conferenceJoined(room));
  1491. APP.UI.mucJoined();
  1492. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1493. APP.UI.markVideoInterrupted(false);
  1494. });
  1495. room.on(
  1496. JitsiConferenceEvents.CONFERENCE_LEFT,
  1497. (...args) => APP.store.dispatch(conferenceLeft(room, ...args)));
  1498. room.on(
  1499. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1500. (authEnabled, authLogin) =>
  1501. APP.UI.updateAuthInfo(authEnabled, authLogin));
  1502. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1503. user => APP.UI.onUserFeaturesChanged(user));
  1504. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1505. if (user.isHidden()) {
  1506. return;
  1507. }
  1508. APP.store.dispatch(participantJoined({
  1509. id,
  1510. name: user.getDisplayName(),
  1511. role: user.getRole()
  1512. }));
  1513. logger.log('USER %s connnected', id, user);
  1514. APP.API.notifyUserJoined(id);
  1515. APP.UI.addUser(user);
  1516. // check the roles for the new user and reflect them
  1517. APP.UI.updateUserRole(user);
  1518. });
  1519. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1520. APP.store.dispatch(participantLeft(id, user));
  1521. logger.log('USER %s LEFT', id, user);
  1522. APP.API.notifyUserLeft(id);
  1523. APP.UI.removeUser(id, user.getDisplayName());
  1524. APP.UI.onSharedVideoStop(id);
  1525. });
  1526. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1527. APP.store.dispatch(participantPresenceChanged(id, status));
  1528. const user = room.getParticipantById(id);
  1529. if (user) {
  1530. APP.UI.updateUserStatus(user, status);
  1531. }
  1532. });
  1533. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1534. if (this.isLocalId(id)) {
  1535. logger.info(`My role changed, new role: ${role}`);
  1536. APP.store.dispatch(localParticipantRoleChanged(role));
  1537. if (this.isModerator !== room.isModerator()) {
  1538. this.isModerator = room.isModerator();
  1539. APP.UI.updateLocalRole(room.isModerator());
  1540. }
  1541. } else {
  1542. APP.store.dispatch(participantRoleChanged(id, role));
  1543. const user = room.getParticipantById(id);
  1544. if (user) {
  1545. APP.UI.updateUserRole(user);
  1546. }
  1547. }
  1548. });
  1549. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1550. if (!track || track.isLocal()) {
  1551. return;
  1552. }
  1553. APP.store.dispatch(trackAdded(track));
  1554. });
  1555. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1556. if (!track || track.isLocal()) {
  1557. return;
  1558. }
  1559. APP.store.dispatch(trackRemoved(track));
  1560. });
  1561. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1562. let newLvl = lvl;
  1563. if (this.isLocalId(id)
  1564. && this.localAudio && this.localAudio.isMuted()) {
  1565. newLvl = 0;
  1566. }
  1567. if (config.debug) {
  1568. this.audioLevelsMap[id] = newLvl;
  1569. if (config.debugAudioLevels) {
  1570. logger.log(`AudioLevel:${id}/${newLvl}`);
  1571. }
  1572. }
  1573. APP.UI.setAudioLevel(id, newLvl);
  1574. });
  1575. room.on(JitsiConferenceEvents.TALK_WHILE_MUTED, () => {
  1576. APP.UI.showToolbar(6000);
  1577. APP.UI.showCustomToolbarPopup(
  1578. 'microphone', 'talkWhileMutedPopup', true, 5000);
  1579. });
  1580. room.on(
  1581. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1582. (leavingIds, enteringIds) =>
  1583. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1584. room.on(
  1585. JitsiConferenceEvents.P2P_STATUS,
  1586. (jitsiConference, p2p) =>
  1587. APP.store.dispatch(p2pStatusChanged(p2p)));
  1588. room.on(
  1589. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1590. (id, connectionStatus) => {
  1591. APP.store.dispatch(participantConnectionStatusChanged(
  1592. id, connectionStatus));
  1593. APP.UI.participantConnectionStatusChanged(id);
  1594. });
  1595. room.on(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id => {
  1596. APP.store.dispatch(dominantSpeakerChanged(id));
  1597. if (this.isLocalId(id)) {
  1598. this.isDominantSpeaker = true;
  1599. this.setRaisedHand(false);
  1600. } else {
  1601. this.isDominantSpeaker = false;
  1602. const participant = room.getParticipantById(id);
  1603. if (participant) {
  1604. APP.UI.setRaisedHandStatus(participant, false);
  1605. }
  1606. }
  1607. APP.UI.markDominantSpeaker(id);
  1608. });
  1609. if (!interfaceConfig.filmStripOnly) {
  1610. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1611. APP.UI.markVideoInterrupted(true);
  1612. });
  1613. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1614. APP.UI.markVideoInterrupted(false);
  1615. });
  1616. if (isButtonEnabled('chat')) {
  1617. room.on(
  1618. JitsiConferenceEvents.MESSAGE_RECEIVED,
  1619. (id, body, ts) => {
  1620. let nick = getDisplayName(id);
  1621. if (!nick) {
  1622. nick = `${
  1623. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME} (${
  1624. id})`;
  1625. }
  1626. APP.API.notifyReceivedChatMessage({
  1627. id,
  1628. nick,
  1629. body,
  1630. ts
  1631. });
  1632. APP.UI.addMessage(id, nick, body, ts);
  1633. }
  1634. );
  1635. APP.UI.addListener(UIEvents.MESSAGE_CREATED, message => {
  1636. APP.API.notifySendingChatMessage(message);
  1637. room.sendTextMessage(message);
  1638. });
  1639. }
  1640. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, id => {
  1641. try {
  1642. // do not try to select participant if there is none (we
  1643. // are alone in the room), otherwise an error will be
  1644. // thrown cause reporting mechanism is not available
  1645. // (datachannels currently)
  1646. if (room.getParticipants().length === 0) {
  1647. return;
  1648. }
  1649. room.selectParticipant(id);
  1650. } catch (e) {
  1651. sendEvent(
  1652. 'selectParticipant.failed');
  1653. reportError(e);
  1654. }
  1655. });
  1656. APP.UI.addListener(
  1657. UIEvents.VIDEO_UNMUTING_WHILE_AUDIO_ONLY,
  1658. () => this._displayAudioOnlyTooltip('videoMute'));
  1659. }
  1660. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1661. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1662. JitsiParticipantConnectionStatus.INTERRUPTED));
  1663. APP.UI.showLocalConnectionInterrupted(true);
  1664. });
  1665. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1666. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1667. JitsiParticipantConnectionStatus.ACTIVE));
  1668. APP.UI.showLocalConnectionInterrupted(false);
  1669. });
  1670. room.on(
  1671. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1672. (id, displayName) => {
  1673. const formattedDisplayName
  1674. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1675. APP.store.dispatch(participantUpdated({
  1676. id,
  1677. name: formattedDisplayName
  1678. }));
  1679. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1680. APP.UI.changeDisplayName(id, formattedDisplayName);
  1681. }
  1682. );
  1683. room.on(
  1684. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1685. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1686. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1687. room.setLocalParticipantProperty(
  1688. 'remoteControlSessionStatus',
  1689. isActive
  1690. );
  1691. APP.UI.setLocalRemoteControlActiveChanged();
  1692. });
  1693. /* eslint-disable max-params */
  1694. room.on(
  1695. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1696. (participant, name, oldValue, newValue) => {
  1697. switch (name) {
  1698. case 'raisedHand':
  1699. APP.UI.setRaisedHandStatus(participant, newValue);
  1700. break;
  1701. case 'remoteControlSessionStatus':
  1702. APP.UI.setRemoteControlActiveStatus(
  1703. participant.getId(),
  1704. newValue);
  1705. break;
  1706. default:
  1707. // ignore
  1708. }
  1709. });
  1710. /* eslint-enable max-params */
  1711. room.on(
  1712. JitsiConferenceEvents.RECORDER_STATE_CHANGED,
  1713. (status, error) => {
  1714. logger.log('Received recorder status change: ', status, error);
  1715. APP.UI.updateRecordingState(status);
  1716. }
  1717. );
  1718. room.on(JitsiConferenceEvents.KICKED, () => {
  1719. APP.UI.hideStats();
  1720. APP.UI.notifyKicked();
  1721. // FIXME close
  1722. });
  1723. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1724. APP.store.dispatch(suspendDetected());
  1725. // After wake up, we will be in a state where conference is left
  1726. // there will be dialog shown to user.
  1727. // We do not want video/audio as we show an overlay and after it
  1728. // user need to rejoin or close, while waking up we can detect
  1729. // camera wakeup as a problem with device.
  1730. // We also do not care about device change, which happens
  1731. // on resume after suspending PC.
  1732. if (this.deviceChangeListener) {
  1733. JitsiMeetJS.mediaDevices.removeEventListener(
  1734. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  1735. this.deviceChangeListener);
  1736. }
  1737. // stop local video
  1738. if (this.localVideo) {
  1739. this.localVideo.dispose();
  1740. this.localVideo = null;
  1741. }
  1742. // stop local audio
  1743. if (this.localAudio) {
  1744. this.localAudio.dispose();
  1745. this.localAudio = null;
  1746. }
  1747. });
  1748. room.on(
  1749. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1750. isDTMFSupported => {
  1751. APP.UI.updateDTMFSupport(isDTMFSupported);
  1752. }
  1753. );
  1754. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1755. this.muteAudio(muted);
  1756. });
  1757. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1758. if (this.isAudioOnly() && !muted) {
  1759. this._displayAudioOnlyTooltip('videoMute');
  1760. } else {
  1761. this.muteVideo(muted);
  1762. }
  1763. });
  1764. statsEmitter.startListeningForStats(room);
  1765. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1766. ({ value }) => {
  1767. APP.UI.initEtherpad(value);
  1768. }
  1769. );
  1770. APP.UI.addListener(UIEvents.EMAIL_CHANGED, this.changeLocalEmail);
  1771. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1772. APP.store.dispatch(participantUpdated({
  1773. id: from,
  1774. email: data.value
  1775. }));
  1776. APP.UI.setUserEmail(from, data.value);
  1777. });
  1778. room.addCommandListener(
  1779. this.commands.defaults.AVATAR_URL,
  1780. (data, from) => {
  1781. APP.store.dispatch(
  1782. participantUpdated({
  1783. id: from,
  1784. avatarURL: data.value
  1785. }));
  1786. APP.UI.setUserAvatarUrl(from, data.value);
  1787. });
  1788. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1789. (data, from) => {
  1790. APP.store.dispatch(
  1791. participantUpdated({
  1792. id: from,
  1793. avatarID: data.value
  1794. }));
  1795. APP.UI.setUserAvatarID(from, data.value);
  1796. });
  1797. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  1798. this.changeLocalDisplayName.bind(this));
  1799. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1800. (startAudioMuted, startVideoMuted) => {
  1801. room.setStartMutedPolicy({
  1802. audio: startAudioMuted,
  1803. video: startVideoMuted
  1804. });
  1805. }
  1806. );
  1807. room.on(
  1808. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  1809. ({ audio, video }) => {
  1810. APP.UI.onStartMutedChanged(audio, video);
  1811. }
  1812. );
  1813. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  1814. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1815. && APP.UI.notifyInitiallyMuted();
  1816. });
  1817. room.on(
  1818. JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED,
  1819. (id, devices) => {
  1820. APP.UI.updateDevicesAvailability(id, devices);
  1821. }
  1822. );
  1823. room.on(
  1824. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  1825. APP.store.dispatch(dataChannelOpened());
  1826. }
  1827. );
  1828. // call hangup
  1829. APP.UI.addListener(UIEvents.HANGUP, () => {
  1830. this.hangup(true);
  1831. });
  1832. // logout
  1833. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1834. AuthHandler.logout(room).then(url => {
  1835. if (url) {
  1836. UIUtil.redirect(url);
  1837. } else {
  1838. this.hangup(true);
  1839. }
  1840. });
  1841. });
  1842. /* eslint-disable max-params */
  1843. APP.UI.addListener(
  1844. UIEvents.RESOLUTION_CHANGED,
  1845. (id, oldResolution, newResolution, delay) => {
  1846. const logObject = {
  1847. id: 'resolution_change',
  1848. participant: id,
  1849. oldValue: oldResolution,
  1850. newValue: newResolution,
  1851. delay
  1852. };
  1853. room.sendApplicationLog(JSON.stringify(logObject));
  1854. // We only care about the delay between simulcast streams.
  1855. // Longer delays will be caused by something else and will just
  1856. // poison the data.
  1857. if (delay < 2000) {
  1858. sendEvent('stream.switch.delay', { value: delay });
  1859. }
  1860. });
  1861. /* eslint-enable max-params */
  1862. // Starts or stops the recording for the conference.
  1863. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, options => {
  1864. room.toggleRecording(options);
  1865. });
  1866. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, topic => {
  1867. room.setSubject(topic);
  1868. });
  1869. room.on(JitsiConferenceEvents.SUBJECT_CHANGED, subject => {
  1870. APP.UI.setSubject(subject);
  1871. });
  1872. APP.UI.addListener(UIEvents.USER_KICKED, id => {
  1873. room.kickParticipant(id);
  1874. });
  1875. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, id => {
  1876. room.muteParticipant(id);
  1877. });
  1878. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1879. AuthHandler.authenticate(room);
  1880. });
  1881. APP.UI.addListener(
  1882. UIEvents.VIDEO_DEVICE_CHANGED,
  1883. cameraDeviceId => {
  1884. sendEvent('settings.changeDevice.video');
  1885. createLocalTracksF({
  1886. devices: [ 'video' ],
  1887. cameraDeviceId,
  1888. micDeviceId: null
  1889. })
  1890. .then(([ stream ]) => {
  1891. if (this.isAudioOnly()) {
  1892. return stream.mute()
  1893. .then(() => stream);
  1894. }
  1895. return stream;
  1896. })
  1897. .then(stream => {
  1898. this.useVideoStream(stream);
  1899. logger.log('switched local video device');
  1900. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1901. })
  1902. .catch(err => {
  1903. APP.UI.showCameraErrorNotification(err);
  1904. });
  1905. }
  1906. );
  1907. APP.UI.addListener(
  1908. UIEvents.AUDIO_DEVICE_CHANGED,
  1909. micDeviceId => {
  1910. sendEvent(
  1911. 'settings.changeDevice.audioIn');
  1912. createLocalTracksF({
  1913. devices: [ 'audio' ],
  1914. cameraDeviceId: null,
  1915. micDeviceId
  1916. })
  1917. .then(([ stream ]) => {
  1918. this.useAudioStream(stream);
  1919. logger.log('switched local audio device');
  1920. APP.settings.setMicDeviceId(micDeviceId, true);
  1921. })
  1922. .catch(err => {
  1923. APP.UI.showMicErrorNotification(err);
  1924. });
  1925. }
  1926. );
  1927. APP.UI.addListener(
  1928. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1929. audioOutputDeviceId => {
  1930. sendEvent(
  1931. 'settings.changeDevice.audioOut');
  1932. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1933. .then(() => logger.log('changed audio output device'))
  1934. .catch(err => {
  1935. logger.warn('Failed to change audio output device. '
  1936. + 'Default or previously set audio output device '
  1937. + 'will be used instead.', err);
  1938. });
  1939. }
  1940. );
  1941. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  1942. // FIXME On web video track is stored both in redux and in
  1943. // 'localVideo' field, video is attempted to be unmuted twice when
  1944. // turning off the audio only mode. This will crash the app with
  1945. // 'unmute operation is already in progress'.
  1946. // Because there's no logic in redux about creating new track in
  1947. // case unmute when not track exists the things have to go through
  1948. // muteVideo logic in such case.
  1949. const tracks = APP.store.getState()['features/base/tracks'];
  1950. const isTrackInRedux
  1951. = Boolean(
  1952. tracks.find(
  1953. track => track.jitsiTrack
  1954. && track.jitsiTrack.getType() === 'video'));
  1955. if (!isTrackInRedux) {
  1956. this.muteVideo(audioOnly);
  1957. }
  1958. // Immediately update the UI by having remote videos and the large
  1959. // video update themselves instead of waiting for some other event
  1960. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  1961. // There is no guarantee another event will trigger the update
  1962. // immediately and in all situations, for example because a remote
  1963. // participant is having connection trouble so no status changes.
  1964. APP.UI.updateAllVideos();
  1965. });
  1966. APP.UI.addListener(
  1967. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1968. );
  1969. /* eslint-disable max-params */
  1970. APP.UI.addListener(
  1971. UIEvents.UPDATE_SHARED_VIDEO,
  1972. (url, state, time, isMuted, volume) => {
  1973. /* eslint-enable max-params */
  1974. // send start and stop commands once, and remove any updates
  1975. // that had left
  1976. if (state === 'stop'
  1977. || state === 'start'
  1978. || state === 'playing') {
  1979. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1980. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1981. value: url,
  1982. attributes: {
  1983. state,
  1984. time,
  1985. muted: isMuted,
  1986. volume
  1987. }
  1988. });
  1989. } else {
  1990. // in case of paused, in order to allow late users to join
  1991. // paused
  1992. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1993. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1994. value: url,
  1995. attributes: {
  1996. state,
  1997. time,
  1998. muted: isMuted,
  1999. volume
  2000. }
  2001. });
  2002. }
  2003. });
  2004. room.addCommandListener(
  2005. this.commands.defaults.SHARED_VIDEO,
  2006. ({ value, attributes }, id) => {
  2007. if (attributes.state === 'stop') {
  2008. APP.UI.onSharedVideoStop(id, attributes);
  2009. } else if (attributes.state === 'start') {
  2010. APP.UI.onSharedVideoStart(id, value, attributes);
  2011. } else if (attributes.state === 'playing'
  2012. || attributes.state === 'pause') {
  2013. APP.UI.onSharedVideoUpdate(id, value, attributes);
  2014. }
  2015. });
  2016. },
  2017. /**
  2018. * Adds any room listener.
  2019. * @param {string} eventName one of the JitsiConferenceEvents
  2020. * @param {Function} listener the function to be called when the event
  2021. * occurs
  2022. */
  2023. addConferenceListener(eventName, listener) {
  2024. room.on(eventName, listener);
  2025. },
  2026. /**
  2027. * Removes any room listener.
  2028. * @param {string} eventName one of the JitsiConferenceEvents
  2029. * @param {Function} listener the listener to be removed.
  2030. */
  2031. removeConferenceListener(eventName, listener) {
  2032. room.off(eventName, listener);
  2033. },
  2034. /**
  2035. * Inits list of current devices and event listener for device change.
  2036. * @private
  2037. */
  2038. _initDeviceList() {
  2039. JitsiMeetJS.mediaDevices.isDeviceListAvailable()
  2040. .then(isDeviceListAvailable => {
  2041. if (isDeviceListAvailable
  2042. && JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  2043. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  2044. // Ugly way to synchronize real device IDs with local
  2045. // storage and settings menu. This is a workaround until
  2046. // getConstraints() method will be implemented
  2047. // in browsers.
  2048. if (this.localAudio) {
  2049. APP.settings.setMicDeviceId(
  2050. this.localAudio.getDeviceId(), false);
  2051. }
  2052. if (this.localVideo) {
  2053. APP.settings.setCameraDeviceId(
  2054. this.localVideo.getDeviceId(), false);
  2055. }
  2056. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2057. APP.UI.onAvailableDevicesChanged(devices);
  2058. APP.store.dispatch(updateDeviceList(devices));
  2059. });
  2060. this.deviceChangeListener = devices =>
  2061. window.setTimeout(
  2062. () => this._onDeviceListChanged(devices), 0);
  2063. JitsiMeetJS.mediaDevices.addEventListener(
  2064. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2065. this.deviceChangeListener);
  2066. }
  2067. })
  2068. .catch(error => {
  2069. logger.warn(`Error getting device list: ${error}`);
  2070. });
  2071. },
  2072. /**
  2073. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2074. * handle change of available media devices.
  2075. * @private
  2076. * @param {MediaDeviceInfo[]} devices
  2077. * @returns {Promise}
  2078. */
  2079. _onDeviceListChanged(devices) {
  2080. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2081. // Event handler can be fired before direct
  2082. // enumerateDevices() call, so handle this situation here.
  2083. if (!currentDevices.audioinput
  2084. && !currentDevices.videoinput
  2085. && !currentDevices.audiooutput) {
  2086. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2087. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  2088. }
  2089. const newDevices
  2090. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2091. devices,
  2092. this.isSharingScreen,
  2093. this.localVideo,
  2094. this.localAudio);
  2095. const promises = [];
  2096. const audioWasMuted = this.isLocalAudioMuted();
  2097. const videoWasMuted = this.isLocalVideoMuted();
  2098. const availableAudioInputDevices
  2099. = mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  2100. const availableVideoInputDevices
  2101. = mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  2102. if (typeof newDevices.audiooutput !== 'undefined') {
  2103. // Just ignore any errors in catch block.
  2104. promises.push(APP.settings
  2105. .setAudioOutputDeviceId(newDevices.audiooutput)
  2106. .catch());
  2107. }
  2108. promises.push(
  2109. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2110. createLocalTracksF,
  2111. newDevices.videoinput,
  2112. newDevices.audioinput)
  2113. .then(tracks =>
  2114. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  2115. .then(() => {
  2116. // If audio was muted before, or we unplugged current device
  2117. // and selected new one, then mute new audio track.
  2118. if (audioWasMuted
  2119. || currentDevices.audioinput.length
  2120. > availableAudioInputDevices.length) {
  2121. sendEvent('deviceListChanged.audio.muted');
  2122. logger.log('Audio mute: device list changed');
  2123. muteLocalAudio(true);
  2124. }
  2125. // If video was muted before, or we unplugged current device
  2126. // and selected new one, then mute new video track.
  2127. if (!this.isSharingScreen
  2128. && (videoWasMuted
  2129. || currentDevices.videoinput.length
  2130. > availableVideoInputDevices.length)) {
  2131. sendEvent('deviceListChanged.video.muted');
  2132. logger.log('Video mute: device list changed');
  2133. muteLocalVideo(true);
  2134. }
  2135. }));
  2136. return Promise.all(promises)
  2137. .then(() => {
  2138. mediaDeviceHelper.setCurrentMediaDevices(devices);
  2139. APP.UI.onAvailableDevicesChanged(devices);
  2140. });
  2141. },
  2142. /**
  2143. * Determines whether or not the audio button should be enabled.
  2144. */
  2145. updateAudioIconEnabled() {
  2146. const audioMediaDevices
  2147. = mediaDeviceHelper.getCurrentMediaDevices().audioinput;
  2148. const audioDeviceCount
  2149. = audioMediaDevices ? audioMediaDevices.length : 0;
  2150. // The audio functionality is considered available if there are any
  2151. // audio devices detected or if the local audio stream already exists.
  2152. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2153. logger.debug(
  2154. `Microphone button enabled: ${available}`,
  2155. `local audio: ${this.localAudio}`,
  2156. `audio devices: ${audioMediaDevices}`,
  2157. `device count: ${audioDeviceCount}`);
  2158. APP.store.dispatch(setAudioAvailable(available));
  2159. APP.API.notifyAudioAvailabilityChanged(available);
  2160. },
  2161. /**
  2162. * Determines whether or not the video button should be enabled.
  2163. */
  2164. updateVideoIconEnabled() {
  2165. const videoMediaDevices
  2166. = mediaDeviceHelper.getCurrentMediaDevices().videoinput;
  2167. const videoDeviceCount
  2168. = videoMediaDevices ? videoMediaDevices.length : 0;
  2169. // The video functionality is considered available if there are any
  2170. // video devices detected or if there is local video stream already
  2171. // active which could be either screensharing stream or a video track
  2172. // created before the permissions were rejected (through browser
  2173. // config).
  2174. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2175. logger.debug(
  2176. `Camera button enabled: ${available}`,
  2177. `local video: ${this.localVideo}`,
  2178. `video devices: ${videoMediaDevices}`,
  2179. `device count: ${videoDeviceCount}`);
  2180. APP.store.dispatch(setVideoAvailable(available));
  2181. APP.API.notifyVideoAvailabilityChanged(available);
  2182. },
  2183. /**
  2184. * Toggles the local "raised hand" status.
  2185. */
  2186. maybeToggleRaisedHand() {
  2187. this.setRaisedHand(!this.isHandRaised);
  2188. },
  2189. /**
  2190. * Sets the local "raised hand" status to a particular value.
  2191. */
  2192. setRaisedHand(raisedHand) {
  2193. if (raisedHand !== this.isHandRaised) {
  2194. APP.UI.onLocalRaiseHandChanged(raisedHand);
  2195. this.isHandRaised = raisedHand;
  2196. // Advertise the updated status
  2197. room.setLocalParticipantProperty('raisedHand', raisedHand);
  2198. // Update the view
  2199. APP.UI.setLocalRaisedHandStatus(raisedHand);
  2200. }
  2201. },
  2202. /**
  2203. * Log event to callstats and analytics.
  2204. * @param {string} name the event name
  2205. * @param {int} value the value (it's int because google analytics supports
  2206. * only int).
  2207. * @param {string} label short text which provides more info about the event
  2208. * which allows to distinguish between few event cases of the same name
  2209. * NOTE: Should be used after conference.init
  2210. */
  2211. logEvent(name, value, label) {
  2212. sendEvent(name, {
  2213. value,
  2214. label
  2215. });
  2216. if (room) {
  2217. room.sendApplicationLog(JSON.stringify({ name,
  2218. value,
  2219. label }));
  2220. }
  2221. },
  2222. /**
  2223. * Methods logs an application event given in the JSON format.
  2224. * @param {string} logJSON an event to be logged in JSON format
  2225. */
  2226. logJSON(logJSON) {
  2227. if (room) {
  2228. room.sendApplicationLog(logJSON);
  2229. }
  2230. },
  2231. /**
  2232. * Disconnect from the conference and optionally request user feedback.
  2233. * @param {boolean} [requestFeedback=false] if user feedback should be
  2234. * requested
  2235. */
  2236. hangup(requestFeedback = false) {
  2237. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2238. let requestFeedbackPromise;
  2239. if (requestFeedback) {
  2240. requestFeedbackPromise
  2241. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2242. // false because the thank you dialog shouldn't be displayed
  2243. .catch(() => Promise.resolve(false));
  2244. } else {
  2245. requestFeedbackPromise = Promise.resolve(true);
  2246. }
  2247. // All promises are returning Promise.resolve to make Promise.all to
  2248. // be resolved when both Promises are finished. Otherwise Promise.all
  2249. // will reject on first rejected Promise and we can redirect the page
  2250. // before all operations are done.
  2251. Promise.all([
  2252. requestFeedbackPromise,
  2253. room.leave().then(disconnect, disconnect)
  2254. ]).then(values => {
  2255. APP.API.notifyReadyToClose();
  2256. maybeRedirectToWelcomePage(values[0]);
  2257. });
  2258. },
  2259. /**
  2260. * Changes the email for the local user
  2261. * @param email {string} the new email
  2262. */
  2263. changeLocalEmail(email = '') {
  2264. const localParticipant = getLocalParticipant(APP.store.getState());
  2265. const formattedEmail = String(email).trim();
  2266. if (formattedEmail === localParticipant.email) {
  2267. return;
  2268. }
  2269. const localId = localParticipant.id;
  2270. APP.store.dispatch(participantUpdated({
  2271. id: localId,
  2272. local: true,
  2273. formattedEmail
  2274. }));
  2275. APP.settings.setEmail(formattedEmail);
  2276. APP.UI.setUserEmail(localId, formattedEmail);
  2277. sendData(commands.EMAIL, formattedEmail);
  2278. },
  2279. /**
  2280. * Changes the avatar url for the local user
  2281. * @param url {string} the new url
  2282. */
  2283. changeLocalAvatarUrl(url = '') {
  2284. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2285. const formattedUrl = String(url).trim();
  2286. if (formattedUrl === avatarURL) {
  2287. return;
  2288. }
  2289. APP.store.dispatch(participantUpdated({
  2290. id,
  2291. local: true,
  2292. avatarURL: formattedUrl
  2293. }));
  2294. APP.settings.setAvatarUrl(url);
  2295. APP.UI.setUserAvatarUrl(id, url);
  2296. sendData(commands.AVATAR_URL, url);
  2297. },
  2298. /**
  2299. * Sends a message via the data channel.
  2300. * @param {string} to the id of the endpoint that should receive the
  2301. * message. If "" - the message will be sent to all participants.
  2302. * @param {object} payload the payload of the message.
  2303. * @throws NetworkError or InvalidStateError or Error if the operation
  2304. * fails.
  2305. */
  2306. sendEndpointMessage(to, payload) {
  2307. room.sendEndpointMessage(to, payload);
  2308. },
  2309. /**
  2310. * Adds new listener.
  2311. * @param {String} eventName the name of the event
  2312. * @param {Function} listener the listener.
  2313. */
  2314. addListener(eventName, listener) {
  2315. eventEmitter.addListener(eventName, listener);
  2316. },
  2317. /**
  2318. * Removes listener.
  2319. * @param {String} eventName the name of the event that triggers the
  2320. * listener
  2321. * @param {Function} listener the listener.
  2322. */
  2323. removeListener(eventName, listener) {
  2324. eventEmitter.removeListener(eventName, listener);
  2325. },
  2326. /**
  2327. * Changes the display name for the local user
  2328. * @param nickname {string} the new display name
  2329. */
  2330. changeLocalDisplayName(nickname = '') {
  2331. const formattedNickname
  2332. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  2333. const { id, name } = getLocalParticipant(APP.store.getState());
  2334. if (formattedNickname === name) {
  2335. return;
  2336. }
  2337. APP.store.dispatch(participantUpdated({
  2338. id,
  2339. local: true,
  2340. name: formattedNickname
  2341. }));
  2342. APP.settings.setDisplayName(formattedNickname);
  2343. if (room) {
  2344. room.setDisplayName(formattedNickname);
  2345. APP.UI.changeDisplayName(id, formattedNickname);
  2346. }
  2347. },
  2348. /**
  2349. * Returns the desktop sharing source id or undefined if the desktop sharing
  2350. * is not active at the moment.
  2351. *
  2352. * @returns {string|undefined} - The source id. If the track is not desktop
  2353. * track or the source id is not available, undefined will be returned.
  2354. */
  2355. getDesktopSharingSourceId() {
  2356. return this.localVideo.sourceId;
  2357. },
  2358. /**
  2359. * Returns the desktop sharing source type or undefined if the desktop
  2360. * sharing is not active at the moment.
  2361. *
  2362. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2363. * not desktop track or the source type is not available, undefined will be
  2364. * returned.
  2365. */
  2366. getDesktopSharingSourceType() {
  2367. return this.localVideo.sourceType;
  2368. },
  2369. /**
  2370. * Sets the video muted status.
  2371. *
  2372. * @param {boolean} muted - New muted status.
  2373. */
  2374. setVideoMuteStatus(muted) {
  2375. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2376. APP.API.notifyVideoMutedStatusChanged(muted);
  2377. },
  2378. /**
  2379. * Sets the audio muted status.
  2380. *
  2381. * @param {boolean} muted - New muted status.
  2382. */
  2383. setAudioMuteStatus(muted) {
  2384. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2385. APP.API.notifyAudioMutedStatusChanged(muted);
  2386. }
  2387. };