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

conference.js 98KB

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