Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 95KB

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