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

conference.js 95KB

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