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

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