Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 63KB

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