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

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