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

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