Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

conference.js 62KB

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