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

conference.js 95KB

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