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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. const logger = require("jitsi-meet-logger").getLogger(__filename);
  3. import {openConnection} from './connection';
  4. import Invite from './modules/UI/invite/Invite';
  5. import ContactList from './modules/UI/side_pannels/contactlist/ContactList';
  6. import AuthHandler from './modules/UI/authentication/AuthHandler';
  7. import Recorder from './modules/recorder/Recorder';
  8. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  9. import {reportError} from './modules/util/helpers';
  10. import UIEvents from './service/UI/UIEvents';
  11. import UIUtil from './modules/UI/util/UIUtil';
  12. import analytics from './modules/analytics/analytics';
  13. const ConnectionEvents = JitsiMeetJS.events.connection;
  14. const ConnectionErrors = JitsiMeetJS.errors.connection;
  15. const ConferenceEvents = JitsiMeetJS.events.conference;
  16. const ConferenceErrors = JitsiMeetJS.errors.conference;
  17. const TrackEvents = JitsiMeetJS.events.track;
  18. const TrackErrors = JitsiMeetJS.errors.track;
  19. const ConnectionQualityEvents = JitsiMeetJS.events.connectionQuality;
  20. let room, connection, localAudio, localVideo;
  21. /**
  22. * Indicates whether extension external installation is in progress or not.
  23. */
  24. let DSExternalInstallationInProgress = false;
  25. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/VideoContainer";
  26. /**
  27. * Known custom conference commands.
  28. */
  29. const commands = {
  30. EMAIL: "email",
  31. AVATAR_URL: "avatar-url",
  32. AVATAR_ID: "avatar-id",
  33. ETHERPAD: "etherpad",
  34. SHARED_VIDEO: "shared-video",
  35. CUSTOM_ROLE: "custom-role"
  36. };
  37. /**
  38. * Max length of the display names. If we receive longer display name the
  39. * additional chars are going to be cut.
  40. */
  41. const MAX_DISPLAY_NAME_LENGTH = 50;
  42. /**
  43. * Open Connection. When authentication failed it shows auth dialog.
  44. * @param roomName the room name to use
  45. * @returns Promise<JitsiConnection>
  46. */
  47. function connect(roomName) {
  48. return openConnection({retry: true, roomName: roomName})
  49. .catch(function (err) {
  50. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  51. APP.UI.notifyTokenAuthFailed();
  52. } else {
  53. APP.UI.notifyConnectionFailed(err);
  54. }
  55. throw err;
  56. });
  57. }
  58. /**
  59. * Creates local media tracks and connects to room. Will show error
  60. * dialogs in case if accessing local microphone and/or camera failed. Will
  61. * show guidance overlay for users on how to give access to camera and/or
  62. * microphone,
  63. * @param {string} roomName
  64. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  65. */
  66. function createInitialLocalTracksAndConnect(roomName) {
  67. let audioAndVideoError,
  68. audioOnlyError;
  69. JitsiMeetJS.mediaDevices.addEventListener(
  70. JitsiMeetJS.events.mediaDevices.PERMISSION_PROMPT_IS_SHOWN,
  71. browser => APP.UI.showUserMediaPermissionsGuidanceOverlay(browser));
  72. // First try to retrieve both audio and video.
  73. let tryCreateLocalTracks = createLocalTracks(
  74. { devices: ['audio', 'video'] }, true)
  75. .catch(err => {
  76. // If failed then try to retrieve only audio.
  77. audioAndVideoError = err;
  78. return createLocalTracks({ devices: ['audio'] }, true);
  79. })
  80. .catch(err => {
  81. // If audio failed too then just return empty array for tracks.
  82. audioOnlyError = err;
  83. return [];
  84. });
  85. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  86. .then(([tracks, con]) => {
  87. APP.UI.hideUserMediaPermissionsGuidanceOverlay();
  88. if (audioAndVideoError) {
  89. if (audioOnlyError) {
  90. // If both requests for 'audio' + 'video' and 'audio' only
  91. // failed, we assume that there is some problems with user's
  92. // microphone and show corresponding dialog.
  93. APP.UI.showDeviceErrorDialog(audioOnlyError, null);
  94. } else {
  95. // If request for 'audio' + 'video' failed, but request for
  96. // 'audio' only was OK, we assume that we had problems with
  97. // camera and show corresponding dialog.
  98. APP.UI.showDeviceErrorDialog(null, audioAndVideoError);
  99. }
  100. }
  101. return [tracks, con];
  102. });
  103. }
  104. /**
  105. * Share data to other users.
  106. * @param command the command
  107. * @param {string} value new value
  108. */
  109. function sendData (command, value) {
  110. room.removeCommand(command);
  111. room.sendCommand(command, {value: value});
  112. }
  113. /**
  114. * Get user nickname by user id.
  115. * @param {string} id user id
  116. * @returns {string?} user nickname or undefined if user is unknown.
  117. */
  118. function getDisplayName (id) {
  119. if (APP.conference.isLocalId(id)) {
  120. return APP.settings.getDisplayName();
  121. }
  122. let participant = room.getParticipantById(id);
  123. if (participant && participant.getDisplayName()) {
  124. return participant.getDisplayName();
  125. }
  126. }
  127. /**
  128. * Mute or unmute local audio stream if it exists.
  129. * @param {boolean} muted - if audio stream should be muted or unmuted.
  130. * @param {boolean} userInteraction - indicates if this local audio mute was a
  131. * result of user interaction
  132. */
  133. function muteLocalAudio (muted) {
  134. muteLocalMedia(localAudio, muted, 'Audio');
  135. }
  136. function muteLocalMedia(localMedia, muted, localMediaTypeString) {
  137. if (!localMedia) {
  138. return;
  139. }
  140. const method = muted ? 'mute' : 'unmute';
  141. localMedia[method]().catch(reason => {
  142. logger.warn(`${localMediaTypeString} ${method} was rejected:`, reason);
  143. });
  144. }
  145. /**
  146. * Mute or unmute local video stream if it exists.
  147. * @param {boolean} muted if video stream should be muted or unmuted.
  148. */
  149. function muteLocalVideo (muted) {
  150. muteLocalMedia(localVideo, muted, 'Video');
  151. }
  152. /**
  153. * Check if the welcome page is enabled and redirects to it.
  154. * If requested show a thank you dialog before that.
  155. * If we have a close page enabled, redirect to it without
  156. * showing any other dialog.
  157. *
  158. * @param {object} options used to decide which particular close page to show
  159. * or if close page is disabled, whether we should show the thankyou dialog
  160. * @param {boolean} options.thankYouDialogVisible - whether we should
  161. * show thank you dialog
  162. * @param {boolean} options.feedbackSubmitted - whether feedback was submitted
  163. */
  164. function maybeRedirectToWelcomePage(options) {
  165. // if close page is enabled redirect to it, without further action
  166. if (config.enableClosePage) {
  167. if (options.feedbackSubmitted)
  168. window.location.pathname = "close.html";
  169. else
  170. window.location.pathname = "close2.html";
  171. return;
  172. }
  173. // else: show thankYou dialog only if there is no feedback
  174. if (options.thankYouDialogVisible)
  175. APP.UI.messageHandler.openMessageDialog(
  176. null, "dialog.thankYou", {appName:interfaceConfig.APP_NAME});
  177. // if Welcome page is enabled redirect to welcome page after 3 sec.
  178. if (config.enableWelcomePage) {
  179. setTimeout(() => {
  180. APP.settings.setWelcomePageEnabled(true);
  181. window.location.pathname = "/";
  182. }, 3000);
  183. }
  184. }
  185. /**
  186. * Create local tracks of specified types.
  187. * @param {Object} options
  188. * @param {string[]} options.devices - required track types
  189. * ('audio', 'video' etc.)
  190. * @param {string|null} (options.cameraDeviceId) - camera device id, if
  191. * undefined - one from settings will be used
  192. * @param {string|null} (options.micDeviceId) - microphone device id, if
  193. * undefined - one from settings will be used
  194. * @param {boolean} (checkForPermissionPrompt) - if lib-jitsi-meet should check
  195. * for gUM permission prompt
  196. * @returns {Promise<JitsiLocalTrack[]>}
  197. */
  198. function createLocalTracks (options, checkForPermissionPrompt) {
  199. options || (options = {});
  200. return JitsiMeetJS
  201. .createLocalTracks({
  202. // copy array to avoid mutations inside library
  203. devices: options.devices.slice(0),
  204. resolution: config.resolution,
  205. cameraDeviceId: typeof options.cameraDeviceId === 'undefined' ||
  206. options.cameraDeviceId === null
  207. ? APP.settings.getCameraDeviceId()
  208. : options.cameraDeviceId,
  209. micDeviceId: typeof options.micDeviceId === 'undefined' ||
  210. options.micDeviceId === null
  211. ? APP.settings.getMicDeviceId()
  212. : options.micDeviceId,
  213. // adds any ff fake device settings if any
  214. firefox_fake_device: config.firefox_fake_device,
  215. desktopSharingExtensionExternalInstallation:
  216. options.desktopSharingExtensionExternalInstallation
  217. }, checkForPermissionPrompt).then( (tracks) => {
  218. tracks.forEach((track) => {
  219. track.on(TrackEvents.NO_DATA_FROM_SOURCE,
  220. APP.UI.showTrackNotWorkingDialog.bind(null, track));
  221. });
  222. return tracks;
  223. }).catch(function (err) {
  224. logger.error(
  225. 'failed to create local tracks', options.devices, err);
  226. return Promise.reject(err);
  227. });
  228. }
  229. /**
  230. * Changes the email for the local user
  231. * @param email {string} the new email
  232. */
  233. function changeLocalEmail(email = '') {
  234. email = email.trim();
  235. if (email === APP.settings.getEmail()) {
  236. return;
  237. }
  238. APP.settings.setEmail(email);
  239. APP.UI.setUserEmail(room.myUserId(), email);
  240. sendData(commands.EMAIL, email);
  241. }
  242. /**
  243. * Changes the display name for the local user
  244. * @param nickname {string} the new display name
  245. */
  246. function changeLocalDisplayName(nickname = '') {
  247. const formattedNickname
  248. = nickname.trim().substr(0, MAX_DISPLAY_NAME_LENGTH);
  249. if (formattedNickname === APP.settings.getDisplayName()) {
  250. return;
  251. }
  252. APP.settings.setDisplayName(formattedNickname);
  253. room.setDisplayName(formattedNickname);
  254. APP.UI.changeDisplayName(APP.conference.getMyUserId(), formattedNickname);
  255. }
  256. class ConferenceConnector {
  257. constructor(resolve, reject, invite) {
  258. this._resolve = resolve;
  259. this._reject = reject;
  260. this._invite = invite;
  261. this.reconnectTimeout = null;
  262. room.on(ConferenceEvents.CONFERENCE_JOINED,
  263. this._handleConferenceJoined.bind(this));
  264. room.on(ConferenceEvents.CONFERENCE_FAILED,
  265. this._onConferenceFailed.bind(this));
  266. room.on(ConferenceEvents.CONFERENCE_ERROR,
  267. this._onConferenceError.bind(this));
  268. }
  269. _handleConferenceFailed(err) {
  270. this._unsubscribe();
  271. this._reject(err);
  272. }
  273. _onConferenceFailed(err, ...params) {
  274. logger.error('CONFERENCE FAILED:', err, ...params);
  275. APP.UI.hideRingOverLay();
  276. switch (err) {
  277. // room is locked by the password
  278. case ConferenceErrors.PASSWORD_REQUIRED:
  279. APP.UI.emitEvent(UIEvents.PASSWORD_REQUIRED);
  280. break;
  281. case ConferenceErrors.CONNECTION_ERROR:
  282. {
  283. let [msg] = params;
  284. APP.UI.notifyConnectionFailed(msg);
  285. }
  286. break;
  287. case ConferenceErrors.NOT_ALLOWED_ERROR:
  288. {
  289. // let's show some auth not allowed page
  290. window.location.pathname = "authError.html";
  291. }
  292. break;
  293. // not enough rights to create conference
  294. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  295. // schedule reconnect to check if someone else created the room
  296. this.reconnectTimeout = setTimeout(function () {
  297. room.join();
  298. }, 5000);
  299. // notify user that auth is required
  300. AuthHandler.requireAuth(
  301. room, this._invite.getRoomLocker().password);
  302. break;
  303. case ConferenceErrors.RESERVATION_ERROR:
  304. {
  305. let [code, msg] = params;
  306. APP.UI.notifyReservationError(code, msg);
  307. }
  308. break;
  309. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  310. APP.UI.notifyGracefulShutdown();
  311. break;
  312. case ConferenceErrors.JINGLE_FATAL_ERROR:
  313. APP.UI.notifyInternalError();
  314. break;
  315. case ConferenceErrors.CONFERENCE_DESTROYED:
  316. {
  317. let [reason] = params;
  318. APP.UI.hideStats();
  319. APP.UI.notifyConferenceDestroyed(reason);
  320. }
  321. break;
  322. // FIXME FOCUS_DISCONNECTED is confusing event name.
  323. // What really happens there is that the library is not ready yet,
  324. // because Jicofo is not available, but it is going to give
  325. // it another try.
  326. case ConferenceErrors.FOCUS_DISCONNECTED:
  327. {
  328. let [focus, retrySec] = params;
  329. APP.UI.notifyFocusDisconnected(focus, retrySec);
  330. }
  331. break;
  332. case ConferenceErrors.FOCUS_LEFT:
  333. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  334. // FIXME the conference should be stopped by the library and not by
  335. // the app. Both the errors above are unrecoverable from the library
  336. // perspective.
  337. room.leave().then(() => connection.disconnect());
  338. APP.UI.showPageReloadOverlay(
  339. false /* not a network type of failure */, err);
  340. break;
  341. case ConferenceErrors.CONFERENCE_MAX_USERS:
  342. connection.disconnect();
  343. APP.UI.notifyMaxUsersLimitReached();
  344. break;
  345. case ConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  346. window.location.reload();
  347. break;
  348. default:
  349. this._handleConferenceFailed(err, ...params);
  350. }
  351. }
  352. _onConferenceError(err, ...params) {
  353. logger.error('CONFERENCE Error:', err, params);
  354. switch (err) {
  355. case ConferenceErrors.CHAT_ERROR:
  356. {
  357. let [code, msg] = params;
  358. APP.UI.showChatError(code, msg);
  359. }
  360. break;
  361. default:
  362. logger.error("Unknown error.", err);
  363. }
  364. }
  365. _unsubscribe() {
  366. room.off(
  367. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  368. room.off(
  369. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  370. if (this.reconnectTimeout !== null) {
  371. clearTimeout(this.reconnectTimeout);
  372. }
  373. AuthHandler.closeAuth();
  374. }
  375. _handleConferenceJoined() {
  376. this._unsubscribe();
  377. this._resolve();
  378. }
  379. connect() {
  380. room.join();
  381. }
  382. }
  383. /**
  384. * Disconnects the connection.
  385. * @returns resolved Promise. We need this in order to make the Promise.all
  386. * call in hangup() to resolve when all operations are finished.
  387. */
  388. function disconnect() {
  389. connection.disconnect();
  390. APP.API.notifyConferenceLeft(APP.conference.roomName);
  391. return Promise.resolve();
  392. }
  393. export default {
  394. isModerator: false,
  395. audioMuted: false,
  396. videoMuted: false,
  397. isSharingScreen: false,
  398. isDesktopSharingEnabled: false,
  399. /*
  400. * Whether the local "raisedHand" flag is on.
  401. */
  402. isHandRaised: false,
  403. /*
  404. * Whether the local participant is the dominant speaker in the conference.
  405. */
  406. isDominantSpeaker: false,
  407. /**
  408. * Open new connection and join to the conference.
  409. * @param {object} options
  410. * @param {string} roomName name of the conference
  411. * @returns {Promise}
  412. */
  413. init(options) {
  414. this.roomName = options.roomName;
  415. // attaches global error handler, if there is already one, respect it
  416. if(JitsiMeetJS.getGlobalOnErrorHandler){
  417. var oldOnErrorHandler = window.onerror;
  418. window.onerror = function (message, source, lineno, colno, error) {
  419. JitsiMeetJS.getGlobalOnErrorHandler(
  420. message, source, lineno, colno, error);
  421. if(oldOnErrorHandler)
  422. oldOnErrorHandler(message, source, lineno, colno, error);
  423. };
  424. var oldOnUnhandledRejection = window.onunhandledrejection;
  425. window.onunhandledrejection = function(event) {
  426. JitsiMeetJS.getGlobalOnErrorHandler(
  427. null, null, null, null, event.reason);
  428. if(oldOnUnhandledRejection)
  429. oldOnUnhandledRejection(event);
  430. };
  431. }
  432. return JitsiMeetJS.init(
  433. Object.assign(
  434. {enableAnalyticsLogging: analytics.isEnabled()}, config)
  435. ).then(() => {
  436. analytics.init();
  437. return createInitialLocalTracksAndConnect(options.roomName);
  438. }).then(([tracks, con]) => {
  439. logger.log('initialized with %s local tracks', tracks.length);
  440. APP.connection = connection = con;
  441. this._bindConnectionFailedHandler(con);
  442. this._createRoom(tracks);
  443. this.isDesktopSharingEnabled =
  444. JitsiMeetJS.isDesktopSharingEnabled();
  445. if (UIUtil.isButtonEnabled('contacts'))
  446. APP.UI.ContactList = new ContactList(room);
  447. // if user didn't give access to mic or camera or doesn't have
  448. // them at all, we disable corresponding toolbar buttons
  449. if (!tracks.find((t) => t.isAudioTrack())) {
  450. APP.UI.setMicrophoneButtonEnabled(false);
  451. }
  452. if (!tracks.find((t) => t.isVideoTrack())) {
  453. APP.UI.setCameraButtonEnabled(false);
  454. }
  455. this._initDeviceList();
  456. if (config.iAmRecorder)
  457. this.recorder = new Recorder();
  458. // XXX The API will take care of disconnecting from the XMPP
  459. // server (and, thus, leaving the room) on unload.
  460. return new Promise((resolve, reject) => {
  461. (new ConferenceConnector(
  462. resolve, reject, this.invite)).connect();
  463. });
  464. });
  465. },
  466. /**
  467. * Check if id is id of the local user.
  468. * @param {string} id id to check
  469. * @returns {boolean}
  470. */
  471. isLocalId (id) {
  472. return this.getMyUserId() === id;
  473. },
  474. /**
  475. * Binds a handler that will handle the case when the connection is dropped
  476. * in the middle of the conference.
  477. * @param {JitsiConnection} connection the connection to which the handler
  478. * will be bound to.
  479. * @private
  480. */
  481. _bindConnectionFailedHandler (connection) {
  482. const handler = function (error, errMsg) {
  483. if (ConnectionErrors.OTHER_ERROR === error ||
  484. ConnectionErrors.SERVER_ERROR === error) {
  485. // - item-not-found
  486. // - connection dropped(closed by Strophe unexpectedly
  487. // possible due too many transport errors)
  488. const isNetworkFailure
  489. = error !== ConnectionErrors.SERVER_ERROR;
  490. logger.error("XMPP connection error: " + errMsg);
  491. APP.UI.showPageReloadOverlay(
  492. isNetworkFailure,
  493. "xmpp-conn-dropped:" + errMsg);
  494. connection.removeEventListener(
  495. ConnectionEvents.CONNECTION_FAILED, handler);
  496. // FIXME it feels like the conference should be stopped
  497. // by lib-jitsi-meet
  498. if (room)
  499. room.leave();
  500. }
  501. };
  502. connection.addEventListener(
  503. ConnectionEvents.CONNECTION_FAILED, handler);
  504. },
  505. /**
  506. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  507. * @param mute true for mute and false for unmute.
  508. */
  509. muteAudio (mute) {
  510. muteLocalAudio(mute);
  511. },
  512. /**
  513. * Returns whether local audio is muted or not.
  514. * @returns {boolean}
  515. */
  516. isLocalAudioMuted() {
  517. return this.audioMuted;
  518. },
  519. /**
  520. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  521. */
  522. toggleAudioMuted () {
  523. this.muteAudio(!this.audioMuted);
  524. },
  525. /**
  526. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  527. * @param mute true for mute and false for unmute.
  528. */
  529. muteVideo (mute) {
  530. muteLocalVideo(mute);
  531. },
  532. /**
  533. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  534. */
  535. toggleVideoMuted () {
  536. this.muteVideo(!this.videoMuted);
  537. },
  538. /**
  539. * Retrieve list of conference participants (without local user).
  540. * @returns {JitsiParticipant[]}
  541. */
  542. listMembers () {
  543. return room.getParticipants();
  544. },
  545. /**
  546. * Retrieve list of ids of conference participants (without local user).
  547. * @returns {string[]}
  548. */
  549. listMembersIds () {
  550. return room.getParticipants().map(p => p.getId());
  551. },
  552. /**
  553. * Checks whether the participant identified by id is a moderator.
  554. * @id id to search for participant
  555. * @return {boolean} whether the participant is moderator
  556. */
  557. isParticipantModerator (id) {
  558. let user = room.getParticipantById(id);
  559. return user && user.isModerator();
  560. },
  561. /**
  562. * Check if SIP is supported.
  563. * @returns {boolean}
  564. */
  565. sipGatewayEnabled () {
  566. return room.isSIPCallingSupported();
  567. },
  568. get membersCount () {
  569. return room.getParticipants().length + 1;
  570. },
  571. /**
  572. * Returns true if the callstats integration is enabled, otherwise returns
  573. * false.
  574. *
  575. * @returns true if the callstats integration is enabled, otherwise returns
  576. * false.
  577. */
  578. isCallstatsEnabled () {
  579. return room.isCallstatsEnabled();
  580. },
  581. /**
  582. * Sends the given feedback through CallStats if enabled.
  583. *
  584. * @param overallFeedback an integer between 1 and 5 indicating the
  585. * user feedback
  586. * @param detailedFeedback detailed feedback from the user. Not yet used
  587. */
  588. sendFeedback (overallFeedback, detailedFeedback) {
  589. return room.sendFeedback (overallFeedback, detailedFeedback);
  590. },
  591. /**
  592. * Returns the connection times stored in the library.
  593. */
  594. getConnectionTimes () {
  595. return this._room.getConnectionTimes();
  596. },
  597. // used by torture currently
  598. isJoined () {
  599. return this._room
  600. && this._room.isJoined();
  601. },
  602. getConnectionState () {
  603. return this._room
  604. && this._room.getConnectionState();
  605. },
  606. /**
  607. * Checks whether or not our connection is currently in interrupted and
  608. * reconnect attempts are in progress.
  609. *
  610. * @returns {boolean} true if the connection is in interrupted state or
  611. * false otherwise.
  612. */
  613. isConnectionInterrupted () {
  614. return this._room.isConnectionInterrupted();
  615. },
  616. /**
  617. * Finds JitsiParticipant for given id.
  618. *
  619. * @param {string} id participant's identifier(MUC nickname).
  620. *
  621. * @returns {JitsiParticipant|null} participant instance for given id or
  622. * null if not found.
  623. */
  624. getParticipantById (id) {
  625. return room ? room.getParticipantById(id) : null;
  626. },
  627. /**
  628. * Checks whether the user identified by given id is currently connected.
  629. *
  630. * @param {string} id participant's identifier(MUC nickname)
  631. *
  632. * @returns {boolean|null} true if participant's connection is ok or false
  633. * if the user is having connectivity issues.
  634. */
  635. isParticipantConnectionActive (id) {
  636. let participant = this.getParticipantById(id);
  637. return participant ? participant.isConnectionActive() : null;
  638. },
  639. /**
  640. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  641. * the given <tt>id</tt>.
  642. *
  643. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  644. *
  645. * @return {string} the participant's display name or the default string if
  646. * absent.
  647. */
  648. getParticipantDisplayName (id) {
  649. let displayName = getDisplayName(id);
  650. if (displayName) {
  651. return displayName;
  652. } else {
  653. if (APP.conference.isLocalId(id)) {
  654. return APP.translation.generateTranslationHTML(
  655. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  656. } else {
  657. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  658. }
  659. }
  660. },
  661. getMyUserId () {
  662. return this._room
  663. && this._room.myUserId();
  664. },
  665. /**
  666. * Indicates if recording is supported in this conference.
  667. */
  668. isRecordingSupported() {
  669. return this._room && this._room.isRecordingSupported();
  670. },
  671. /**
  672. * Returns the recording state or undefined if the room is not defined.
  673. */
  674. getRecordingState() {
  675. return (this._room) ? this._room.getRecordingState() : undefined;
  676. },
  677. /**
  678. * Will be filled with values only when config.debug is enabled.
  679. * Its used by torture to check audio levels.
  680. */
  681. audioLevelsMap: {},
  682. /**
  683. * Returns the stored audio level (stored only if config.debug is enabled)
  684. * @param id the id for the user audio level to return (the id value is
  685. * returned for the participant using getMyUserId() method)
  686. */
  687. getPeerSSRCAudioLevel (id) {
  688. return this.audioLevelsMap[id];
  689. },
  690. /**
  691. * @return {number} the number of participants in the conference with at
  692. * least one track.
  693. */
  694. getNumberOfParticipantsWithTracks() {
  695. return this._room.getParticipants()
  696. .filter((p) => p.getTracks().length > 0)
  697. .length;
  698. },
  699. /**
  700. * Returns the stats.
  701. */
  702. getStats() {
  703. return room.connectionQuality.getStats();
  704. },
  705. // end used by torture
  706. getLogs () {
  707. return room.getLogs();
  708. },
  709. /**
  710. * Download logs, a function that can be called from console while
  711. * debugging.
  712. * @param filename (optional) specify target filename
  713. */
  714. saveLogs (filename = 'meetlog.json') {
  715. // this can be called from console and will not have reference to this
  716. // that's why we reference the global var
  717. let logs = APP.conference.getLogs();
  718. let data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  719. let elem = document.createElement('a');
  720. elem.download = filename;
  721. elem.href = 'data:application/json;charset=utf-8,\n' + data;
  722. elem.dataset.downloadurl
  723. = ['text/json', elem.download, elem.href].join(':');
  724. elem.dispatchEvent(new MouseEvent('click', {
  725. view: window,
  726. bubbles: true,
  727. cancelable: false
  728. }));
  729. },
  730. /**
  731. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  732. * desire to keep room private to this instance and (2) the need of other
  733. * modules to send and receive commands to and from participants.
  734. * Eventually, this instance remains in control with respect to the
  735. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  736. * JitsiConference) is to be used in the implementation of the Command(s)
  737. * API of this instance.
  738. */
  739. commands: {
  740. /**
  741. * Known custom conference commands.
  742. */
  743. defaults: commands,
  744. /**
  745. * Receives notifications from other participants about commands aka
  746. * custom events (sent by sendCommand or sendCommandOnce methods).
  747. * @param command {String} the name of the command
  748. * @param handler {Function} handler for the command
  749. */
  750. addCommandListener () {
  751. room.addCommandListener.apply(room, arguments);
  752. },
  753. /**
  754. * Removes command.
  755. * @param name {String} the name of the command.
  756. */
  757. removeCommand () {
  758. room.removeCommand.apply(room, arguments);
  759. },
  760. /**
  761. * Sends command.
  762. * @param name {String} the name of the command.
  763. * @param values {Object} with keys and values that will be sent.
  764. */
  765. sendCommand () {
  766. room.sendCommand.apply(room, arguments);
  767. },
  768. /**
  769. * Sends command one time.
  770. * @param name {String} the name of the command.
  771. * @param values {Object} with keys and values that will be sent.
  772. */
  773. sendCommandOnce () {
  774. room.sendCommandOnce.apply(room, arguments);
  775. }
  776. },
  777. _createRoom (localTracks) {
  778. room = connection.initJitsiConference(APP.conference.roomName,
  779. this._getConferenceOptions());
  780. this._setLocalAudioVideoStreams(localTracks);
  781. this.invite = new Invite(room);
  782. this._room = room; // FIXME do not use this
  783. let email = APP.settings.getEmail();
  784. email && sendData(this.commands.defaults.EMAIL, email);
  785. let avatarUrl = APP.settings.getAvatarUrl();
  786. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  787. avatarUrl);
  788. !email && sendData(
  789. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  790. let nick = APP.settings.getDisplayName();
  791. if (config.useNicks && !nick) {
  792. nick = APP.UI.askForNickname();
  793. APP.settings.setDisplayName(nick);
  794. }
  795. nick && room.setDisplayName(nick);
  796. this._setupListeners();
  797. },
  798. /**
  799. * Sets local video and audio streams.
  800. * @param {JitsiLocalTrack[]} tracks=[]
  801. * @returns {Promise[]}
  802. * @private
  803. */
  804. _setLocalAudioVideoStreams(tracks = []) {
  805. return tracks.map(track => {
  806. if (track.isAudioTrack()) {
  807. return this.useAudioStream(track);
  808. } else if (track.isVideoTrack()) {
  809. return this.useVideoStream(track);
  810. } else {
  811. logger.error(
  812. "Ignored not an audio nor a video track: ", track);
  813. return Promise.resolve();
  814. }
  815. });
  816. },
  817. _getConferenceOptions() {
  818. let options = config;
  819. if(config.enableRecording && !config.recordingType) {
  820. options.recordingType = (config.hosts &&
  821. (typeof config.hosts.jirecon != "undefined"))?
  822. "jirecon" : "colibri";
  823. }
  824. return options;
  825. },
  826. /**
  827. * Start using provided video stream.
  828. * Stops previous video stream.
  829. * @param {JitsiLocalTrack} [stream] new stream to use or null
  830. * @returns {Promise}
  831. */
  832. useVideoStream (stream) {
  833. let promise = Promise.resolve();
  834. if (localVideo) {
  835. // this calls room.removeTrack internally
  836. // so we don't need to remove it manually
  837. promise = localVideo.dispose();
  838. }
  839. localVideo = stream;
  840. return promise.then(function () {
  841. if (stream) {
  842. return room.addTrack(stream);
  843. }
  844. }).then(() => {
  845. if (stream) {
  846. this.videoMuted = stream.isMuted();
  847. this.isSharingScreen = stream.videoType === 'desktop';
  848. APP.UI.addLocalStream(stream);
  849. stream.videoType === 'camera'
  850. && APP.UI.setCameraButtonEnabled(true);
  851. } else {
  852. this.videoMuted = false;
  853. this.isSharingScreen = false;
  854. }
  855. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  856. APP.UI.updateDesktopSharingButtons();
  857. });
  858. },
  859. /**
  860. * Start using provided audio stream.
  861. * Stops previous audio stream.
  862. * @param {JitsiLocalTrack} [stream] new stream to use or null
  863. * @returns {Promise}
  864. */
  865. useAudioStream (stream) {
  866. let promise = Promise.resolve();
  867. if (localAudio) {
  868. // this calls room.removeTrack internally
  869. // so we don't need to remove it manually
  870. promise = localAudio.dispose();
  871. }
  872. localAudio = stream;
  873. return promise.then(function () {
  874. if (stream) {
  875. return room.addTrack(stream);
  876. }
  877. }).then(() => {
  878. if (stream) {
  879. this.audioMuted = stream.isMuted();
  880. APP.UI.addLocalStream(stream);
  881. } else {
  882. this.audioMuted = false;
  883. }
  884. APP.UI.setMicrophoneButtonEnabled(true);
  885. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  886. });
  887. },
  888. videoSwitchInProgress: false,
  889. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  890. if (this.videoSwitchInProgress) {
  891. logger.warn("Switch in progress.");
  892. return;
  893. }
  894. if (!this.isDesktopSharingEnabled) {
  895. logger.warn("Cannot toggle screen sharing: not supported.");
  896. return;
  897. }
  898. this.videoSwitchInProgress = true;
  899. let externalInstallation = false;
  900. if (shareScreen) {
  901. createLocalTracks({
  902. devices: ['desktop'],
  903. desktopSharingExtensionExternalInstallation: {
  904. interval: 500,
  905. checkAgain: () => {
  906. return DSExternalInstallationInProgress;
  907. },
  908. listener: (status, url) => {
  909. switch(status) {
  910. case "waitingForExtension":
  911. DSExternalInstallationInProgress = true;
  912. externalInstallation = true;
  913. APP.UI.showExtensionExternalInstallationDialog(
  914. url);
  915. break;
  916. case "extensionFound":
  917. if(externalInstallation) //close the dialog
  918. $.prompt.close();
  919. break;
  920. default:
  921. //Unknown status
  922. }
  923. }
  924. }
  925. }).then(([stream]) => {
  926. DSExternalInstallationInProgress = false;
  927. // close external installation dialog on success.
  928. if(externalInstallation)
  929. $.prompt.close();
  930. stream.on(
  931. TrackEvents.LOCAL_TRACK_STOPPED,
  932. () => {
  933. // if stream was stopped during screensharing session
  934. // then we should switch to video
  935. // otherwise we stopped it because we already switched
  936. // to video, so nothing to do here
  937. if (this.isSharingScreen) {
  938. this.toggleScreenSharing(false);
  939. }
  940. }
  941. );
  942. return this.useVideoStream(stream);
  943. }).then(() => {
  944. this.videoSwitchInProgress = false;
  945. JitsiMeetJS.analytics.sendEvent(
  946. 'conference.sharingDesktop.start');
  947. logger.log('sharing local desktop');
  948. }).catch((err) => {
  949. // close external installation dialog to show the error.
  950. if(externalInstallation)
  951. $.prompt.close();
  952. this.videoSwitchInProgress = false;
  953. this.toggleScreenSharing(false);
  954. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  955. return;
  956. }
  957. logger.error('failed to share local desktop', err);
  958. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  959. APP.UI.showExtensionRequiredDialog(
  960. config.desktopSharingFirefoxExtensionURL
  961. );
  962. return;
  963. }
  964. // Handling:
  965. // TrackErrors.PERMISSION_DENIED
  966. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  967. // TrackErrors.GENERAL
  968. // and any other
  969. let dialogTxt;
  970. let dialogTitleKey;
  971. if (err.name === TrackErrors.PERMISSION_DENIED) {
  972. dialogTxt = APP.translation.generateTranslationHTML(
  973. "dialog.screenSharingPermissionDeniedError");
  974. dialogTitleKey = "dialog.error";
  975. } else {
  976. dialogTxt = APP.translation.generateTranslationHTML(
  977. "dialog.failtoinstall");
  978. dialogTitleKey = "dialog.permissionDenied";
  979. }
  980. APP.UI.messageHandler.openDialog(
  981. dialogTitleKey, dialogTxt, false);
  982. });
  983. } else {
  984. createLocalTracks({ devices: ['video'] }).then(
  985. ([stream]) => this.useVideoStream(stream)
  986. ).then(() => {
  987. this.videoSwitchInProgress = false;
  988. JitsiMeetJS.analytics.sendEvent(
  989. 'conference.sharingDesktop.stop');
  990. logger.log('sharing local video');
  991. }).catch((err) => {
  992. this.useVideoStream(null);
  993. this.videoSwitchInProgress = false;
  994. logger.error('failed to share local video', err);
  995. });
  996. }
  997. },
  998. /**
  999. * Setup interaction between conference and UI.
  1000. */
  1001. _setupListeners () {
  1002. // add local streams when joined to the conference
  1003. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  1004. APP.UI.mucJoined();
  1005. APP.API.notifyConferenceJoined(APP.conference.roomName);
  1006. APP.UI.markVideoInterrupted(false);
  1007. });
  1008. room.on(
  1009. ConferenceEvents.AUTH_STATUS_CHANGED,
  1010. function (authEnabled, authLogin) {
  1011. APP.UI.updateAuthInfo(authEnabled, authLogin);
  1012. }
  1013. );
  1014. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  1015. if (user.isHidden())
  1016. return;
  1017. logger.log('USER %s connnected', id, user);
  1018. APP.API.notifyUserJoined(id);
  1019. APP.UI.addUser(user);
  1020. // check the roles for the new user and reflect them
  1021. APP.UI.updateUserRole(user);
  1022. });
  1023. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  1024. logger.log('USER %s LEFT', id, user);
  1025. APP.API.notifyUserLeft(id);
  1026. APP.UI.removeUser(id, user.getDisplayName());
  1027. APP.UI.onSharedVideoStop(id);
  1028. });
  1029. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1030. if (this.isLocalId(id)) {
  1031. logger.info(`My role changed, new role: ${role}`);
  1032. if (this.isModerator !== room.isModerator()) {
  1033. this.isModerator = room.isModerator();
  1034. APP.UI.updateLocalRole(room.isModerator());
  1035. }
  1036. } else {
  1037. let user = room.getParticipantById(id);
  1038. if (user) {
  1039. APP.UI.updateUserRole(user);
  1040. }
  1041. }
  1042. });
  1043. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  1044. if(!track || track.isLocal())
  1045. return;
  1046. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  1047. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  1048. });
  1049. APP.UI.addRemoteStream(track);
  1050. });
  1051. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  1052. if(!track || track.isLocal())
  1053. return;
  1054. APP.UI.removeRemoteStream(track);
  1055. });
  1056. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  1057. if(!track)
  1058. return;
  1059. const handler = (track.getType() === "audio")?
  1060. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  1061. let id;
  1062. const mute = track.isMuted();
  1063. if(track.isLocal()){
  1064. id = APP.conference.getMyUserId();
  1065. if(track.getType() === "audio") {
  1066. this.audioMuted = mute;
  1067. } else {
  1068. this.videoMuted = mute;
  1069. }
  1070. } else {
  1071. id = track.getParticipantId();
  1072. }
  1073. handler(id , mute);
  1074. });
  1075. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1076. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  1077. lvl = 0;
  1078. }
  1079. if(config.debug)
  1080. {
  1081. this.audioLevelsMap[id] = lvl;
  1082. if(config.debugAudioLevels)
  1083. logger.log("AudioLevel:" + id + "/" + lvl);
  1084. }
  1085. APP.UI.setAudioLevel(id, lvl);
  1086. });
  1087. room.on(ConferenceEvents.TALK_WHILE_MUTED, () => {
  1088. APP.UI.showToolbar(6000);
  1089. UIUtil.animateShowElement($("#talkWhileMutedPopup"), true, 5000);
  1090. });
  1091. /*
  1092. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1093. //FIXME
  1094. if (config.muteLocalVideoIfNotInLastN) {
  1095. // TODO mute or unmute if required
  1096. // mark video on UI
  1097. // APP.UI.markVideoMuted(true/false);
  1098. }
  1099. });
  1100. */
  1101. room.on(
  1102. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1103. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1104. });
  1105. room.on(
  1106. ConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1107. (id, isActive) => {
  1108. APP.UI.participantConnectionStatusChanged(id, isActive);
  1109. });
  1110. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1111. if (this.isLocalId(id)) {
  1112. this.isDominantSpeaker = true;
  1113. this.setRaisedHand(false);
  1114. } else {
  1115. this.isDominantSpeaker = false;
  1116. var participant = room.getParticipantById(id);
  1117. if (participant) {
  1118. APP.UI.setRaisedHandStatus(participant, false);
  1119. }
  1120. }
  1121. APP.UI.markDominantSpeaker(id);
  1122. });
  1123. if (!interfaceConfig.filmStripOnly) {
  1124. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1125. APP.UI.markVideoInterrupted(true);
  1126. });
  1127. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1128. APP.UI.markVideoInterrupted(false);
  1129. });
  1130. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1131. let nick = getDisplayName(id);
  1132. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1133. APP.UI.addMessage(id, nick, text, ts);
  1134. });
  1135. }
  1136. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1137. APP.UI.showLocalConnectionInterrupted(true);
  1138. });
  1139. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1140. APP.UI.showLocalConnectionInterrupted(false);
  1141. });
  1142. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1143. const formattedDisplayName
  1144. = displayName.substr(0, MAX_DISPLAY_NAME_LENGTH);
  1145. APP.API.notifyDisplayNameChanged(id, formattedDisplayName);
  1146. APP.UI.changeDisplayName(id, formattedDisplayName);
  1147. });
  1148. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1149. (participant, name, oldValue, newValue) => {
  1150. if (name === "raisedHand") {
  1151. APP.UI.setRaisedHandStatus(participant, newValue);
  1152. }
  1153. });
  1154. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1155. logger.log("Received recorder status change: ", status, error);
  1156. APP.UI.updateRecordingState(status);
  1157. });
  1158. room.on(ConferenceEvents.KICKED, () => {
  1159. APP.UI.hideStats();
  1160. APP.UI.notifyKicked();
  1161. // FIXME close
  1162. });
  1163. room.on(ConferenceEvents.SUSPEND_DETECTED, () => {
  1164. // After wake up, we will be in a state where conference is left
  1165. // there will be dialog shown to user.
  1166. // We do not want video/audio as we show an overlay and after it
  1167. // user need to rejoin or close, while waking up we can detect
  1168. // camera wakeup as a problem with device.
  1169. // We also do not care about device change, which happens
  1170. // on resume after suspending PC.
  1171. if (this.deviceChangeListener)
  1172. JitsiMeetJS.mediaDevices.removeEventListener(
  1173. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1174. this.deviceChangeListener);
  1175. // stop local video
  1176. if (localVideo)
  1177. localVideo.dispose();
  1178. // stop local audio
  1179. if (localAudio)
  1180. localAudio.dispose();
  1181. // show overlay
  1182. APP.UI.showSuspendedOverlay();
  1183. });
  1184. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1185. APP.UI.updateDTMFSupport(isDTMFSupported);
  1186. });
  1187. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1188. // Wait a little bit more just to be sure that we won't miss the
  1189. // extension installation
  1190. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1191. });
  1192. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1193. window.open(
  1194. url, "extension_store_window",
  1195. "resizable,scrollbars=yes,status=1");
  1196. });
  1197. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1198. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1199. if (!interfaceConfig.filmStripOnly) {
  1200. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1201. APP.API.notifySendingChatMessage(message);
  1202. room.sendTextMessage(message);
  1203. });
  1204. }
  1205. room.on(ConnectionQualityEvents.LOCAL_STATS_UPDATED,
  1206. (stats) => {
  1207. APP.UI.updateLocalStats(stats.connectionQuality, stats);
  1208. });
  1209. room.on(ConnectionQualityEvents.REMOTE_STATS_UPDATED,
  1210. (id, stats) => {
  1211. APP.UI.updateRemoteStats(id, stats.connectionQuality, stats);
  1212. });
  1213. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1214. APP.UI.initEtherpad(value);
  1215. });
  1216. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1217. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1218. APP.UI.setUserEmail(from, data.value);
  1219. });
  1220. room.addCommandListener(
  1221. this.commands.defaults.AVATAR_URL,
  1222. (data, from) => {
  1223. APP.UI.setUserAvatarUrl(from, data.value);
  1224. });
  1225. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1226. (data, from) => {
  1227. APP.UI.setUserAvatarID(from, data.value);
  1228. });
  1229. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1230. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1231. (startAudioMuted, startVideoMuted) => {
  1232. room.setStartMutedPolicy({
  1233. audio: startAudioMuted,
  1234. video: startVideoMuted
  1235. });
  1236. }
  1237. );
  1238. room.on(
  1239. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1240. ({ audio, video }) => {
  1241. APP.UI.onStartMutedChanged(audio, video);
  1242. }
  1243. );
  1244. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1245. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1246. && APP.UI.notifyInitiallyMuted();
  1247. });
  1248. room.on(
  1249. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1250. APP.UI.updateDevicesAvailability(id, devices);
  1251. }
  1252. );
  1253. // call hangup
  1254. APP.UI.addListener(UIEvents.HANGUP, () => {
  1255. this.hangup(true);
  1256. });
  1257. // logout
  1258. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1259. AuthHandler.logout(room).then(url => {
  1260. if (url) {
  1261. window.location.href = url;
  1262. } else {
  1263. this.hangup(true);
  1264. }
  1265. });
  1266. });
  1267. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1268. room.dial(sipNumber);
  1269. });
  1270. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1271. (id, oldResolution, newResolution, delay) => {
  1272. var logObject = {
  1273. id: "resolution_change",
  1274. participant: id,
  1275. oldValue: oldResolution,
  1276. newValue: newResolution,
  1277. delay: delay
  1278. };
  1279. room.sendApplicationLog(JSON.stringify(logObject));
  1280. // We only care about the delay between simulcast streams.
  1281. // Longer delays will be caused by something else and will just
  1282. // poison the data.
  1283. if (delay < 2000) {
  1284. JitsiMeetJS.analytics.sendEvent('stream.switch.delay',
  1285. {value: delay});
  1286. }
  1287. });
  1288. // Starts or stops the recording for the conference.
  1289. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1290. room.toggleRecording(options);
  1291. });
  1292. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1293. room.setSubject(topic);
  1294. });
  1295. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1296. APP.UI.setSubject(subject);
  1297. });
  1298. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1299. room.kickParticipant(id);
  1300. });
  1301. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1302. room.muteParticipant(id);
  1303. });
  1304. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1305. AuthHandler.authenticate(room);
  1306. });
  1307. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1308. try {
  1309. // do not try to select participant if there is none (we are
  1310. // alone in the room), otherwise an error will be thrown cause
  1311. // reporting mechanism is not available (datachannels currently)
  1312. if (room.getParticipants().length === 0)
  1313. return;
  1314. room.selectParticipant(id);
  1315. } catch (e) {
  1316. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1317. reportError(e);
  1318. }
  1319. });
  1320. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1321. let smallVideoId = smallVideo.getId();
  1322. let isLocal = APP.conference.isLocalId(smallVideoId);
  1323. let eventName
  1324. = (isPinned ? "pinned" : "unpinned") + "." +
  1325. (isLocal ? "local" : "remote");
  1326. let participantCount = room.getParticipantCount();
  1327. JitsiMeetJS.analytics.sendEvent(
  1328. eventName,
  1329. { value: participantCount });
  1330. // FIXME why VIDEO_CONTAINER_TYPE instead of checking if
  1331. // the participant is on the large video ?
  1332. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1333. && !isLocal) {
  1334. // When the library starts supporting multiple pins we would
  1335. // pass the isPinned parameter together with the identifier,
  1336. // but currently we send null to indicate that we unpin the
  1337. // last pinned.
  1338. try {
  1339. room.pinParticipant(isPinned ? smallVideoId : null);
  1340. } catch (e) {
  1341. reportError(e);
  1342. }
  1343. }
  1344. });
  1345. APP.UI.addListener(
  1346. UIEvents.VIDEO_DEVICE_CHANGED,
  1347. (cameraDeviceId) => {
  1348. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1349. createLocalTracks({
  1350. devices: ['video'],
  1351. cameraDeviceId: cameraDeviceId,
  1352. micDeviceId: null
  1353. })
  1354. .then(([stream]) => {
  1355. this.useVideoStream(stream);
  1356. logger.log('switched local video device');
  1357. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1358. })
  1359. .catch((err) => {
  1360. APP.UI.showDeviceErrorDialog(null, err);
  1361. APP.UI.setSelectedCameraFromSettings();
  1362. });
  1363. }
  1364. );
  1365. APP.UI.addListener(
  1366. UIEvents.AUDIO_DEVICE_CHANGED,
  1367. (micDeviceId) => {
  1368. JitsiMeetJS.analytics.sendEvent(
  1369. 'settings.changeDevice.audioIn');
  1370. createLocalTracks({
  1371. devices: ['audio'],
  1372. cameraDeviceId: null,
  1373. micDeviceId: micDeviceId
  1374. })
  1375. .then(([stream]) => {
  1376. this.useAudioStream(stream);
  1377. logger.log('switched local audio device');
  1378. APP.settings.setMicDeviceId(micDeviceId, true);
  1379. })
  1380. .catch((err) => {
  1381. APP.UI.showDeviceErrorDialog(err, null);
  1382. APP.UI.setSelectedMicFromSettings();
  1383. });
  1384. }
  1385. );
  1386. APP.UI.addListener(
  1387. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1388. (audioOutputDeviceId) => {
  1389. JitsiMeetJS.analytics.sendEvent(
  1390. 'settings.changeDevice.audioOut');
  1391. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1392. .then(() => logger.log('changed audio output device'))
  1393. .catch((err) => {
  1394. logger.warn('Failed to change audio output device. ' +
  1395. 'Default or previously set audio output device ' +
  1396. 'will be used instead.', err);
  1397. APP.UI.setSelectedAudioOutputFromSettings();
  1398. });
  1399. }
  1400. );
  1401. APP.UI.addListener(
  1402. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1403. );
  1404. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1405. (url, state, time, isMuted, volume) => {
  1406. // send start and stop commands once, and remove any updates
  1407. // that had left
  1408. if (state === 'stop' || state === 'start' || state === 'playing') {
  1409. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1410. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1411. value: url,
  1412. attributes: {
  1413. state: state,
  1414. time: time,
  1415. muted: isMuted,
  1416. volume: volume
  1417. }
  1418. });
  1419. }
  1420. else {
  1421. // in case of paused, in order to allow late users to join
  1422. // paused
  1423. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1424. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1425. value: url,
  1426. attributes: {
  1427. state: state,
  1428. time: time,
  1429. muted: isMuted,
  1430. volume: volume
  1431. }
  1432. });
  1433. }
  1434. });
  1435. room.addCommandListener(
  1436. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1437. if (attributes.state === 'stop') {
  1438. APP.UI.onSharedVideoStop(id, attributes);
  1439. }
  1440. else if (attributes.state === 'start') {
  1441. APP.UI.onSharedVideoStart(id, value, attributes);
  1442. }
  1443. else if (attributes.state === 'playing'
  1444. || attributes.state === 'pause') {
  1445. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1446. }
  1447. });
  1448. },
  1449. /**
  1450. * Adds any room listener.
  1451. * @param eventName one of the ConferenceEvents
  1452. * @param callBack the function to be called when the event occurs
  1453. */
  1454. addConferenceListener(eventName, callBack) {
  1455. room.on(eventName, callBack);
  1456. },
  1457. /**
  1458. * Inits list of current devices and event listener for device change.
  1459. * @private
  1460. */
  1461. _initDeviceList() {
  1462. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1463. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1464. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1465. // Ugly way to synchronize real device IDs with local
  1466. // storage and settings menu. This is a workaround until
  1467. // getConstraints() method will be implemented in browsers.
  1468. if (localAudio) {
  1469. APP.settings.setMicDeviceId(
  1470. localAudio.getDeviceId(), false);
  1471. }
  1472. if (localVideo) {
  1473. APP.settings.setCameraDeviceId(
  1474. localVideo.getDeviceId(), false);
  1475. }
  1476. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1477. APP.UI.onAvailableDevicesChanged(devices);
  1478. });
  1479. this.deviceChangeListener = (devices) =>
  1480. window.setTimeout(
  1481. () => this._onDeviceListChanged(devices), 0);
  1482. JitsiMeetJS.mediaDevices.addEventListener(
  1483. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1484. this.deviceChangeListener);
  1485. }
  1486. },
  1487. /**
  1488. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1489. * handle change of available media devices.
  1490. * @private
  1491. * @param {MediaDeviceInfo[]} devices
  1492. * @returns {Promise}
  1493. */
  1494. _onDeviceListChanged(devices) {
  1495. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1496. // Event handler can be fired before direct
  1497. // enumerateDevices() call, so handle this situation here.
  1498. if (!currentDevices.audioinput &&
  1499. !currentDevices.videoinput &&
  1500. !currentDevices.audiooutput) {
  1501. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1502. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1503. }
  1504. let newDevices =
  1505. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1506. devices, this.isSharingScreen, localVideo, localAudio);
  1507. let promises = [];
  1508. let audioWasMuted = this.audioMuted;
  1509. let videoWasMuted = this.videoMuted;
  1510. let availableAudioInputDevices =
  1511. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1512. let availableVideoInputDevices =
  1513. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1514. if (typeof newDevices.audiooutput !== 'undefined') {
  1515. // Just ignore any errors in catch block.
  1516. promises.push(APP.settings
  1517. .setAudioOutputDeviceId(newDevices.audiooutput)
  1518. .catch());
  1519. }
  1520. promises.push(
  1521. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1522. createLocalTracks,
  1523. newDevices.videoinput,
  1524. newDevices.audioinput)
  1525. .then(tracks =>
  1526. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1527. .then(() => {
  1528. // If audio was muted before, or we unplugged current device
  1529. // and selected new one, then mute new audio track.
  1530. if (audioWasMuted ||
  1531. currentDevices.audioinput.length >
  1532. availableAudioInputDevices.length) {
  1533. muteLocalAudio(true);
  1534. }
  1535. // If video was muted before, or we unplugged current device
  1536. // and selected new one, then mute new video track.
  1537. if (videoWasMuted ||
  1538. currentDevices.videoinput.length >
  1539. availableVideoInputDevices.length) {
  1540. muteLocalVideo(true);
  1541. }
  1542. }));
  1543. return Promise.all(promises)
  1544. .then(() => {
  1545. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1546. APP.UI.onAvailableDevicesChanged(devices);
  1547. });
  1548. },
  1549. /**
  1550. * Toggles the local "raised hand" status.
  1551. */
  1552. maybeToggleRaisedHand() {
  1553. this.setRaisedHand(!this.isHandRaised);
  1554. },
  1555. /**
  1556. * Sets the local "raised hand" status to a particular value.
  1557. */
  1558. setRaisedHand(raisedHand) {
  1559. if (raisedHand !== this.isHandRaised)
  1560. {
  1561. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1562. this.isHandRaised = raisedHand;
  1563. // Advertise the updated status
  1564. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1565. // Update the view
  1566. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1567. }
  1568. },
  1569. /**
  1570. * Log event to callstats and analytics.
  1571. * @param {string} name the event name
  1572. * @param {int} value the value (it's int because google analytics supports
  1573. * only int).
  1574. * @param {string} label short text which provides more info about the event
  1575. * which allows to distinguish between few event cases of the same name
  1576. * NOTE: Should be used after conference.init
  1577. */
  1578. logEvent(name, value, label) {
  1579. if(JitsiMeetJS.analytics) {
  1580. JitsiMeetJS.analytics.sendEvent(name, {value, label});
  1581. }
  1582. if(room) {
  1583. room.sendApplicationLog(JSON.stringify({name, value, label}));
  1584. }
  1585. },
  1586. /**
  1587. * Methods logs an application event given in the JSON format.
  1588. * @param {string} logJSON an event to be logged in JSON format
  1589. */
  1590. logJSON(logJSON) {
  1591. if (room) {
  1592. room.sendApplicationLog(logJSON);
  1593. }
  1594. },
  1595. /**
  1596. * Disconnect from the conference and optionally request user feedback.
  1597. * @param {boolean} [requestFeedback=false] if user feedback should be
  1598. * requested
  1599. */
  1600. hangup (requestFeedback = false) {
  1601. APP.UI.hideRingOverLay();
  1602. let requestFeedbackPromise = requestFeedback
  1603. ? APP.UI.requestFeedbackOnHangup()
  1604. // false - because the thank you dialog shouldn't be displayed
  1605. .catch(() => Promise.resolve(false))
  1606. : Promise.resolve(true);// true - because the thank you dialog
  1607. //should be displayed
  1608. // All promises are returning Promise.resolve to make Promise.all to
  1609. // be resolved when both Promises are finished. Otherwise Promise.all
  1610. // will reject on first rejected Promise and we can redirect the page
  1611. // before all operations are done.
  1612. Promise.all([
  1613. requestFeedbackPromise,
  1614. room.leave().then(disconnect, disconnect)
  1615. ]).then(values => {
  1616. APP.API.notifyReadyToClose();
  1617. maybeRedirectToWelcomePage(values[0]);
  1618. });
  1619. }
  1620. };