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

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