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.

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