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 57KB

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