Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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