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

conference.js 99KB

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