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 91KB

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