You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 60KB

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