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

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