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.

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