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

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