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

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