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

conference.js 94KB

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