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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  648. * desire to keep room private to this instance and (2) the need of other
  649. * modules to send and receive commands to and from participants.
  650. * Eventually, this instance remains in control with respect to the
  651. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  652. * JitsiConference) is to be used in the implementation of the Command(s)
  653. * API of this instance.
  654. */
  655. commands: {
  656. /**
  657. * Known custom conference commands.
  658. */
  659. defaults: commands,
  660. /**
  661. * Receives notifications from other participants about commands aka
  662. * custom events (sent by sendCommand or sendCommandOnce methods).
  663. * @param command {String} the name of the command
  664. * @param handler {Function} handler for the command
  665. */
  666. addCommandListener () {
  667. room.addCommandListener.apply(room, arguments);
  668. },
  669. /**
  670. * Removes command.
  671. * @param name {String} the name of the command.
  672. */
  673. removeCommand () {
  674. room.removeCommand.apply(room, arguments);
  675. },
  676. /**
  677. * Sends command.
  678. * @param name {String} the name of the command.
  679. * @param values {Object} with keys and values that will be sent.
  680. */
  681. sendCommand () {
  682. room.sendCommand.apply(room, arguments);
  683. },
  684. /**
  685. * Sends command one time.
  686. * @param name {String} the name of the command.
  687. * @param values {Object} with keys and values that will be sent.
  688. */
  689. sendCommandOnce () {
  690. room.sendCommandOnce.apply(room, arguments);
  691. }
  692. },
  693. _createRoom (localTracks) {
  694. room = connection.initJitsiConference(APP.conference.roomName,
  695. this._getConferenceOptions());
  696. this._setLocalAudioVideoStreams(localTracks);
  697. roomLocker = createRoomLocker(room);
  698. this._room = room; // FIXME do not use this
  699. let email = APP.settings.getEmail();
  700. email && sendData(this.commands.defaults.EMAIL, email);
  701. let avatarUrl = APP.settings.getAvatarUrl();
  702. avatarUrl && sendData(this.commands.defaults.AVATAR_URL,
  703. avatarUrl);
  704. !email && sendData(
  705. this.commands.defaults.AVATAR_ID, APP.settings.getAvatarId());
  706. let nick = APP.settings.getDisplayName();
  707. if (config.useNicks && !nick) {
  708. nick = APP.UI.askForNickname();
  709. APP.settings.setDisplayName(nick);
  710. }
  711. nick && room.setDisplayName(nick);
  712. this._setupListeners();
  713. },
  714. /**
  715. * Sets local video and audio streams.
  716. * @param {JitsiLocalTrack[]} tracks=[]
  717. * @returns {Promise[]}
  718. * @private
  719. */
  720. _setLocalAudioVideoStreams(tracks = []) {
  721. return tracks.map(track => {
  722. if (track.isAudioTrack()) {
  723. return this.useAudioStream(track);
  724. } else if (track.isVideoTrack()) {
  725. return this.useVideoStream(track);
  726. } else {
  727. console.error(
  728. "Ignored not an audio nor a video track: ", track);
  729. return Promise.resolve();
  730. }
  731. });
  732. },
  733. _getConferenceOptions() {
  734. let options = config;
  735. if(config.enableRecording && !config.recordingType) {
  736. options.recordingType = (config.hosts &&
  737. (typeof config.hosts.jirecon != "undefined"))?
  738. "jirecon" : "colibri";
  739. }
  740. return options;
  741. },
  742. /**
  743. * Start using provided video stream.
  744. * Stops previous video stream.
  745. * @param {JitsiLocalTrack} [stream] new stream to use or null
  746. * @returns {Promise}
  747. */
  748. useVideoStream (stream) {
  749. let promise = Promise.resolve();
  750. if (localVideo) {
  751. // this calls room.removeTrack internally
  752. // so we don't need to remove it manually
  753. promise = localVideo.dispose();
  754. }
  755. localVideo = stream;
  756. return promise.then(function () {
  757. if (stream) {
  758. return room.addTrack(stream);
  759. }
  760. }).then(() => {
  761. if (stream) {
  762. this.videoMuted = stream.isMuted();
  763. this.isSharingScreen = stream.videoType === 'desktop';
  764. APP.UI.addLocalStream(stream);
  765. stream.videoType === 'camera' && APP.UI.enableCameraButton();
  766. } else {
  767. this.videoMuted = false;
  768. this.isSharingScreen = false;
  769. }
  770. APP.UI.setVideoMuted(this.getMyUserId(), this.videoMuted);
  771. APP.UI.updateDesktopSharingButtons();
  772. });
  773. },
  774. /**
  775. * Start using provided audio stream.
  776. * Stops previous audio stream.
  777. * @param {JitsiLocalTrack} [stream] new stream to use or null
  778. * @returns {Promise}
  779. */
  780. useAudioStream (stream) {
  781. let promise = Promise.resolve();
  782. if (localAudio) {
  783. // this calls room.removeTrack internally
  784. // so we don't need to remove it manually
  785. promise = localAudio.dispose();
  786. }
  787. localAudio = stream;
  788. return promise.then(function () {
  789. if (stream) {
  790. return room.addTrack(stream);
  791. }
  792. }).then(() => {
  793. if (stream) {
  794. this.audioMuted = stream.isMuted();
  795. APP.UI.addLocalStream(stream);
  796. } else {
  797. this.audioMuted = false;
  798. }
  799. APP.UI.enableMicrophoneButton();
  800. APP.UI.setAudioMuted(this.getMyUserId(), this.audioMuted);
  801. });
  802. },
  803. videoSwitchInProgress: false,
  804. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  805. if (this.videoSwitchInProgress) {
  806. console.warn("Switch in progress.");
  807. return;
  808. }
  809. if (!this.isDesktopSharingEnabled) {
  810. console.warn("Cannot toggle screen sharing: not supported.");
  811. return;
  812. }
  813. this.videoSwitchInProgress = true;
  814. let externalInstallation = false;
  815. if (shareScreen) {
  816. createLocalTracks({
  817. devices: ['desktop'],
  818. desktopSharingExtensionExternalInstallation: {
  819. interval: 500,
  820. checkAgain: () => {
  821. return DSExternalInstallationInProgress;
  822. },
  823. listener: (status, url) => {
  824. switch(status) {
  825. case "waitingForExtension":
  826. DSExternalInstallationInProgress = true;
  827. externalInstallation = true;
  828. APP.UI.showExtensionExternalInstallationDialog(
  829. url);
  830. break;
  831. case "extensionFound":
  832. if(externalInstallation) //close the dialog
  833. $.prompt.close();
  834. break;
  835. default:
  836. //Unknown status
  837. }
  838. }
  839. }
  840. }).then(([stream]) => {
  841. DSExternalInstallationInProgress = false;
  842. // close external installation dialog on success.
  843. if(externalInstallation)
  844. $.prompt.close();
  845. stream.on(
  846. TrackEvents.LOCAL_TRACK_STOPPED,
  847. () => {
  848. // if stream was stopped during screensharing session
  849. // then we should switch to video
  850. // otherwise we stopped it because we already switched
  851. // to video, so nothing to do here
  852. if (this.isSharingScreen) {
  853. this.toggleScreenSharing(false);
  854. }
  855. }
  856. );
  857. return this.useVideoStream(stream);
  858. }).then(() => {
  859. this.videoSwitchInProgress = false;
  860. JitsiMeetJS.analytics.sendEvent(
  861. 'conference.sharingDesktop.start');
  862. console.log('sharing local desktop');
  863. }).catch((err) => {
  864. // close external installation dialog to show the error.
  865. if(externalInstallation)
  866. $.prompt.close();
  867. this.videoSwitchInProgress = false;
  868. this.toggleScreenSharing(false);
  869. if (err.name === TrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  870. return;
  871. }
  872. console.error('failed to share local desktop', err);
  873. if (err.name === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  874. APP.UI.showExtensionRequiredDialog(
  875. config.desktopSharingFirefoxExtensionURL
  876. );
  877. return;
  878. }
  879. // Handling:
  880. // TrackErrors.PERMISSION_DENIED
  881. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  882. // TrackErrors.GENERAL
  883. // and any other
  884. let dialogTxt;
  885. let dialogTitle;
  886. if (err.name === TrackErrors.PERMISSION_DENIED) {
  887. dialogTxt = APP.translation.generateTranslationHTML(
  888. "dialog.screenSharingPermissionDeniedError");
  889. dialogTitle = APP.translation.generateTranslationHTML(
  890. "dialog.error");
  891. } else {
  892. dialogTxt = APP.translation.generateTranslationHTML(
  893. "dialog.failtoinstall");
  894. dialogTitle = APP.translation.generateTranslationHTML(
  895. "dialog.permissionDenied");
  896. }
  897. APP.UI.messageHandler.openDialog(dialogTitle, dialogTxt, false);
  898. });
  899. } else {
  900. createLocalTracks({ devices: ['video'] }).then(
  901. ([stream]) => this.useVideoStream(stream)
  902. ).then(() => {
  903. this.videoSwitchInProgress = false;
  904. JitsiMeetJS.analytics.sendEvent(
  905. 'conference.sharingDesktop.stop');
  906. console.log('sharing local video');
  907. }).catch((err) => {
  908. this.useVideoStream(null);
  909. this.videoSwitchInProgress = false;
  910. console.error('failed to share local video', err);
  911. });
  912. }
  913. },
  914. /**
  915. * Setup interaction between conference and UI.
  916. */
  917. _setupListeners () {
  918. // add local streams when joined to the conference
  919. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  920. APP.UI.mucJoined();
  921. APP.API.notifyConferenceJoined(APP.conference.roomName);
  922. connectionIsInterrupted = false;
  923. APP.UI.markVideoInterrupted(false);
  924. });
  925. room.on(
  926. ConferenceEvents.AUTH_STATUS_CHANGED,
  927. function (authEnabled, authLogin) {
  928. APP.UI.updateAuthInfo(authEnabled, authLogin);
  929. }
  930. );
  931. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  932. if (user.isHidden())
  933. return;
  934. console.log('USER %s connnected', id, user);
  935. APP.API.notifyUserJoined(id);
  936. APP.UI.addUser(id, user.getDisplayName());
  937. // check the roles for the new user and reflect them
  938. APP.UI.updateUserRole(user);
  939. });
  940. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  941. console.log('USER %s LEFT', id, user);
  942. APP.API.notifyUserLeft(id);
  943. APP.UI.removeUser(id, user.getDisplayName());
  944. APP.UI.onSharedVideoStop(id);
  945. });
  946. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  947. if (this.isLocalId(id)) {
  948. console.info(`My role changed, new role: ${role}`);
  949. this.isModerator = room.isModerator();
  950. APP.UI.updateLocalRole(room.isModerator());
  951. } else {
  952. let user = room.getParticipantById(id);
  953. if (user) {
  954. APP.UI.updateUserRole(user);
  955. }
  956. }
  957. });
  958. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  959. if(!track || track.isLocal())
  960. return;
  961. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  962. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  963. });
  964. APP.UI.addRemoteStream(track);
  965. });
  966. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  967. if(!track || track.isLocal())
  968. return;
  969. APP.UI.removeRemoteStream(track);
  970. });
  971. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  972. if(!track)
  973. return;
  974. const handler = (track.getType() === "audio")?
  975. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  976. let id;
  977. const mute = track.isMuted();
  978. if(track.isLocal()){
  979. id = APP.conference.getMyUserId();
  980. if(track.getType() === "audio") {
  981. this.audioMuted = mute;
  982. } else {
  983. this.videoMuted = mute;
  984. }
  985. } else {
  986. id = track.getParticipantId();
  987. }
  988. handler(id , mute);
  989. });
  990. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  991. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  992. lvl = 0;
  993. }
  994. if(config.debug)
  995. {
  996. this.audioLevelsMap[id] = lvl;
  997. if(config.debugAudioLevels)
  998. console.log("AudioLevel:" + id + "/" + lvl);
  999. }
  1000. APP.UI.setAudioLevel(id, lvl);
  1001. });
  1002. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  1003. //FIXME
  1004. if (config.muteLocalVideoIfNotInLastN) {
  1005. // TODO mute or unmute if required
  1006. // mark video on UI
  1007. // APP.UI.markVideoMuted(true/false);
  1008. }
  1009. });
  1010. room.on(
  1011. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  1012. APP.UI.handleLastNEndpoints(ids, enteringIds);
  1013. });
  1014. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  1015. if (this.isLocalId(id)) {
  1016. this.isDominantSpeaker = true;
  1017. this.setRaisedHand(false);
  1018. } else {
  1019. this.isDominantSpeaker = false;
  1020. var participant = room.getParticipantById(id);
  1021. if (participant) {
  1022. APP.UI.setRaisedHandStatus(participant, false);
  1023. }
  1024. }
  1025. APP.UI.markDominantSpeaker(id);
  1026. });
  1027. if (!interfaceConfig.filmStripOnly) {
  1028. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1029. APP.UI.markVideoInterrupted(true);
  1030. });
  1031. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1032. APP.UI.markVideoInterrupted(false);
  1033. });
  1034. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  1035. let nick = getDisplayName(id);
  1036. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  1037. APP.UI.addMessage(id, nick, text, ts);
  1038. });
  1039. }
  1040. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1041. connectionIsInterrupted = true;
  1042. ConnectionQuality.updateLocalConnectionQuality(0);
  1043. });
  1044. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  1045. connectionIsInterrupted = false;
  1046. });
  1047. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  1048. APP.API.notifyDisplayNameChanged(id, displayName);
  1049. APP.UI.changeDisplayName(id, displayName);
  1050. });
  1051. room.on(ConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1052. (participant, name, oldValue, newValue) => {
  1053. if (name === "raisedHand") {
  1054. APP.UI.setRaisedHandStatus(participant, newValue);
  1055. }
  1056. });
  1057. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  1058. console.log("Received recorder status change: ", status, error);
  1059. APP.UI.updateRecordingState(status);
  1060. });
  1061. room.on(ConferenceEvents.LOCK_STATE_CHANGED, (state, error) => {
  1062. console.log("Received channel password lock change: ", state,
  1063. error);
  1064. APP.UI.markRoomLocked(state);
  1065. });
  1066. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  1067. APP.UI.updateUserStatus(id, status);
  1068. });
  1069. room.on(ConferenceEvents.KICKED, () => {
  1070. APP.UI.hideStats();
  1071. APP.UI.notifyKicked();
  1072. // FIXME close
  1073. });
  1074. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  1075. APP.UI.updateDTMFSupport(isDTMFSupported);
  1076. });
  1077. APP.UI.addListener(UIEvents.EXTERNAL_INSTALLATION_CANCELED, () => {
  1078. // Wait a little bit more just to be sure that we won't miss the
  1079. // extension installation
  1080. setTimeout(() => DSExternalInstallationInProgress = false, 500);
  1081. });
  1082. APP.UI.addListener(UIEvents.OPEN_EXTENSION_STORE, (url) => {
  1083. window.open(
  1084. url, "extension_store_window",
  1085. "resizable,scrollbars=yes,status=1");
  1086. });
  1087. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  1088. if (room.isModerator()) {
  1089. let promise = roomLocker.isLocked
  1090. ? roomLocker.askToUnlock()
  1091. : roomLocker.askToLock();
  1092. promise.then(() => {
  1093. APP.UI.markRoomLocked(roomLocker.isLocked);
  1094. });
  1095. } else {
  1096. roomLocker.notifyModeratorRequired();
  1097. }
  1098. });
  1099. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  1100. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  1101. if (!interfaceConfig.filmStripOnly) {
  1102. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  1103. APP.API.notifySendingChatMessage(message);
  1104. room.sendTextMessage(message);
  1105. });
  1106. }
  1107. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  1108. ConnectionQuality.updateLocalStats(stats, connectionIsInterrupted);
  1109. });
  1110. ConnectionQuality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1111. (percent, stats) => {
  1112. APP.UI.updateLocalStats(percent, stats);
  1113. // Send only the data that remote participants care about.
  1114. let data = {
  1115. bitrate: stats.bitrate,
  1116. packetLoss: stats.packetLoss};
  1117. try {
  1118. room.broadcastEndpointMessage({
  1119. type: this.commands.defaults.CONNECTION_QUALITY,
  1120. values: data });
  1121. } catch (e) {
  1122. reportError(e);
  1123. }
  1124. });
  1125. room.on(ConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1126. (participant, payload) => {
  1127. switch(payload.type) {
  1128. case this.commands.defaults.CONNECTION_QUALITY:
  1129. ConnectionQuality.updateRemoteStats(participant.getId(),
  1130. payload.values);
  1131. break;
  1132. default:
  1133. console.warn("Unknown datachannel message", payload);
  1134. }
  1135. });
  1136. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1137. (id, percent, stats) => {
  1138. APP.UI.updateRemoteStats(id, percent, stats);
  1139. });
  1140. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  1141. APP.UI.initEtherpad(value);
  1142. });
  1143. APP.UI.addListener(UIEvents.EMAIL_CHANGED, changeLocalEmail);
  1144. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1145. APP.UI.setUserEmail(from, data.value);
  1146. });
  1147. room.addCommandListener(this.commands.defaults.AVATAR_URL,
  1148. (data, from) => {
  1149. APP.UI.setUserAvatarUrl(from, data.value);
  1150. });
  1151. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  1152. (data, from) => {
  1153. APP.UI.setUserAvatarID(from, data.value);
  1154. });
  1155. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, changeLocalDisplayName);
  1156. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  1157. (startAudioMuted, startVideoMuted) => {
  1158. room.setStartMutedPolicy({
  1159. audio: startAudioMuted,
  1160. video: startVideoMuted
  1161. });
  1162. }
  1163. );
  1164. room.on(
  1165. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  1166. ({ audio, video }) => {
  1167. APP.UI.onStartMutedChanged(audio, video);
  1168. }
  1169. );
  1170. room.on(ConferenceEvents.STARTED_MUTED, () => {
  1171. (room.isStartAudioMuted() || room.isStartVideoMuted())
  1172. && APP.UI.notifyInitiallyMuted();
  1173. });
  1174. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  1175. APP.UI.inviteParticipants(
  1176. roomUrl,
  1177. APP.conference.roomName,
  1178. roomLocker.password,
  1179. APP.settings.getDisplayName()
  1180. );
  1181. });
  1182. room.on(
  1183. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  1184. APP.UI.updateDevicesAvailability(id, devices);
  1185. }
  1186. );
  1187. // call hangup
  1188. APP.UI.addListener(UIEvents.HANGUP, () => {
  1189. hangup(true);
  1190. });
  1191. // logout
  1192. APP.UI.addListener(UIEvents.LOGOUT, () => {
  1193. AuthHandler.logout(room).then(function (url) {
  1194. if (url) {
  1195. window.location.href = url;
  1196. } else {
  1197. hangup(true);
  1198. }
  1199. });
  1200. });
  1201. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  1202. room.dial(sipNumber);
  1203. });
  1204. APP.UI.addListener(UIEvents.RESOLUTION_CHANGED,
  1205. (id, oldResolution, newResolution, delay) => {
  1206. var logObject = {
  1207. id: "resolution_change",
  1208. participant: id,
  1209. oldValue: oldResolution,
  1210. newValue: newResolution,
  1211. delay: delay
  1212. };
  1213. room.sendApplicationLog(JSON.stringify(logObject));
  1214. // We only care about the delay between simulcast streams.
  1215. // Longer delays will be caused by something else and will just
  1216. // poison the data.
  1217. if (delay < 2000) {
  1218. JitsiMeetJS.analytics.sendEvent('stream.switch.delay', delay);
  1219. }
  1220. });
  1221. // Starts or stops the recording for the conference.
  1222. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  1223. room.toggleRecording(options);
  1224. });
  1225. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  1226. room.setSubject(topic);
  1227. });
  1228. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  1229. APP.UI.setSubject(subject);
  1230. });
  1231. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  1232. room.kickParticipant(id);
  1233. });
  1234. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  1235. room.muteParticipant(id);
  1236. });
  1237. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  1238. AuthHandler.authenticate(room);
  1239. });
  1240. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  1241. try {
  1242. // do not try to select participant if there is none (we are
  1243. // alone in the room), otherwise an error will be thrown cause
  1244. // reporting mechanism is not available (datachannels currently)
  1245. if (room.getParticipants().length === 0)
  1246. return;
  1247. room.selectParticipant(id);
  1248. } catch (e) {
  1249. JitsiMeetJS.analytics.sendEvent('selectParticipant.failed');
  1250. reportError(e);
  1251. }
  1252. });
  1253. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  1254. var smallVideoId = smallVideo.getId();
  1255. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  1256. && !APP.conference.isLocalId(smallVideoId)) {
  1257. // When the library starts supporting multiple pins we would
  1258. // pass the isPinned parameter together with the identifier,
  1259. // but currently we send null to indicate that we unpin the
  1260. // last pinned.
  1261. try {
  1262. room.pinParticipant(isPinned ? smallVideoId : null);
  1263. } catch (e) {
  1264. reportError(e);
  1265. }
  1266. }
  1267. });
  1268. APP.UI.addListener(
  1269. UIEvents.VIDEO_DEVICE_CHANGED,
  1270. (cameraDeviceId) => {
  1271. JitsiMeetJS.analytics.sendEvent('settings.changeDevice.video');
  1272. createLocalTracks({
  1273. devices: ['video'],
  1274. cameraDeviceId: cameraDeviceId,
  1275. micDeviceId: null
  1276. })
  1277. .then(([stream]) => {
  1278. this.useVideoStream(stream);
  1279. console.log('switched local video device');
  1280. APP.settings.setCameraDeviceId(cameraDeviceId, true);
  1281. })
  1282. .catch((err) => {
  1283. APP.UI.showDeviceErrorDialog(null, err);
  1284. APP.UI.setSelectedCameraFromSettings();
  1285. });
  1286. }
  1287. );
  1288. APP.UI.addListener(
  1289. UIEvents.AUDIO_DEVICE_CHANGED,
  1290. (micDeviceId) => {
  1291. JitsiMeetJS.analytics.sendEvent(
  1292. 'settings.changeDevice.audioIn');
  1293. createLocalTracks({
  1294. devices: ['audio'],
  1295. cameraDeviceId: null,
  1296. micDeviceId: micDeviceId
  1297. })
  1298. .then(([stream]) => {
  1299. this.useAudioStream(stream);
  1300. console.log('switched local audio device');
  1301. APP.settings.setMicDeviceId(micDeviceId, true);
  1302. })
  1303. .catch((err) => {
  1304. APP.UI.showDeviceErrorDialog(err, null);
  1305. APP.UI.setSelectedMicFromSettings();
  1306. });
  1307. }
  1308. );
  1309. APP.UI.addListener(
  1310. UIEvents.AUDIO_OUTPUT_DEVICE_CHANGED,
  1311. (audioOutputDeviceId) => {
  1312. JitsiMeetJS.analytics.sendEvent(
  1313. 'settings.changeDevice.audioOut');
  1314. APP.settings.setAudioOutputDeviceId(audioOutputDeviceId)
  1315. .then(() => console.log('changed audio output device'))
  1316. .catch((err) => {
  1317. console.warn('Failed to change audio output device. ' +
  1318. 'Default or previously set audio output device ' +
  1319. 'will be used instead.', err);
  1320. APP.UI.setSelectedAudioOutputFromSettings();
  1321. });
  1322. }
  1323. );
  1324. APP.UI.addListener(
  1325. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  1326. );
  1327. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  1328. (url, state, time, isMuted, volume) => {
  1329. // send start and stop commands once, and remove any updates
  1330. // that had left
  1331. if (state === 'stop' || state === 'start' || state === 'playing') {
  1332. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1333. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  1334. value: url,
  1335. attributes: {
  1336. state: state,
  1337. time: time,
  1338. muted: isMuted,
  1339. volume: volume
  1340. }
  1341. });
  1342. }
  1343. else {
  1344. // in case of paused, in order to allow late users to join
  1345. // paused
  1346. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  1347. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  1348. value: url,
  1349. attributes: {
  1350. state: state,
  1351. time: time,
  1352. muted: isMuted,
  1353. volume: volume
  1354. }
  1355. });
  1356. }
  1357. });
  1358. room.addCommandListener(
  1359. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1360. if (attributes.state === 'stop') {
  1361. APP.UI.onSharedVideoStop(id, attributes);
  1362. }
  1363. else if (attributes.state === 'start') {
  1364. APP.UI.onSharedVideoStart(id, value, attributes);
  1365. }
  1366. else if (attributes.state === 'playing'
  1367. || attributes.state === 'pause') {
  1368. APP.UI.onSharedVideoUpdate(id, value, attributes);
  1369. }
  1370. });
  1371. },
  1372. /**
  1373. * Adds any room listener.
  1374. * @param eventName one of the ConferenceEvents
  1375. * @param callBack the function to be called when the event occurs
  1376. */
  1377. addConferenceListener(eventName, callBack) {
  1378. room.on(eventName, callBack);
  1379. },
  1380. /**
  1381. * Inits list of current devices and event listener for device change.
  1382. * @private
  1383. */
  1384. _initDeviceList() {
  1385. if (JitsiMeetJS.mediaDevices.isDeviceListAvailable() &&
  1386. JitsiMeetJS.mediaDevices.isDeviceChangeAvailable()) {
  1387. JitsiMeetJS.mediaDevices.enumerateDevices(devices => {
  1388. // Ugly way to synchronize real device IDs with local
  1389. // storage and settings menu. This is a workaround until
  1390. // getConstraints() method will be implemented in browsers.
  1391. if (localAudio) {
  1392. APP.settings.setMicDeviceId(
  1393. localAudio.getDeviceId(), false);
  1394. }
  1395. if (localVideo) {
  1396. APP.settings.setCameraDeviceId(
  1397. localVideo.getDeviceId(), false);
  1398. }
  1399. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1400. APP.UI.onAvailableDevicesChanged(devices);
  1401. });
  1402. JitsiMeetJS.mediaDevices.addEventListener(
  1403. JitsiMeetJS.events.mediaDevices.DEVICE_LIST_CHANGED,
  1404. (devices) =>
  1405. window.setTimeout(
  1406. () => this._onDeviceListChanged(devices), 0));
  1407. }
  1408. },
  1409. /**
  1410. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  1411. * handle change of available media devices.
  1412. * @private
  1413. * @param {MediaDeviceInfo[]} devices
  1414. * @returns {Promise}
  1415. */
  1416. _onDeviceListChanged(devices) {
  1417. let currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1418. // Event handler can be fired before direct
  1419. // enumerateDevices() call, so handle this situation here.
  1420. if (!currentDevices.audioinput &&
  1421. !currentDevices.videoinput &&
  1422. !currentDevices.audiooutput) {
  1423. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1424. currentDevices = mediaDeviceHelper.getCurrentMediaDevices();
  1425. }
  1426. let newDevices =
  1427. mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  1428. devices, this.isSharingScreen, localVideo, localAudio);
  1429. let promises = [];
  1430. let audioWasMuted = this.audioMuted;
  1431. let videoWasMuted = this.videoMuted;
  1432. let availableAudioInputDevices =
  1433. mediaDeviceHelper.getDevicesFromListByKind(devices, 'audioinput');
  1434. let availableVideoInputDevices =
  1435. mediaDeviceHelper.getDevicesFromListByKind(devices, 'videoinput');
  1436. if (typeof newDevices.audiooutput !== 'undefined') {
  1437. // Just ignore any errors in catch block.
  1438. promises.push(APP.settings
  1439. .setAudioOutputDeviceId(newDevices.audiooutput)
  1440. .catch());
  1441. }
  1442. promises.push(
  1443. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  1444. createLocalTracks,
  1445. newDevices.videoinput,
  1446. newDevices.audioinput)
  1447. .then(tracks =>
  1448. Promise.all(this._setLocalAudioVideoStreams(tracks)))
  1449. .then(() => {
  1450. // If audio was muted before, or we unplugged current device
  1451. // and selected new one, then mute new audio track.
  1452. if (audioWasMuted ||
  1453. currentDevices.audioinput.length >
  1454. availableAudioInputDevices.length) {
  1455. muteLocalAudio(true);
  1456. }
  1457. // If video was muted before, or we unplugged current device
  1458. // and selected new one, then mute new video track.
  1459. if (videoWasMuted ||
  1460. currentDevices.videoinput.length >
  1461. availableVideoInputDevices.length) {
  1462. muteLocalVideo(true);
  1463. }
  1464. }));
  1465. return Promise.all(promises)
  1466. .then(() => {
  1467. mediaDeviceHelper.setCurrentMediaDevices(devices);
  1468. APP.UI.onAvailableDevicesChanged(devices);
  1469. });
  1470. },
  1471. /**
  1472. * Toggles the local "raised hand" status, if the current state allows
  1473. * toggling.
  1474. */
  1475. maybeToggleRaisedHand() {
  1476. // If we are the dominant speaker, we don't enable "raise hand".
  1477. if (this.isHandRaised || !this.isDominantSpeaker) {
  1478. this.setRaisedHand(!this.isHandRaised);
  1479. }
  1480. },
  1481. /**
  1482. * Sets the local "raised hand" status to a particular value.
  1483. */
  1484. setRaisedHand(raisedHand) {
  1485. if (raisedHand !== this.isHandRaised)
  1486. {
  1487. APP.UI.onLocalRaiseHandChanged(raisedHand);
  1488. this.isHandRaised = raisedHand;
  1489. // Advertise the updated status
  1490. room.setLocalParticipantProperty("raisedHand", raisedHand);
  1491. // Update the view
  1492. APP.UI.setLocalRaisedHandStatus(raisedHand);
  1493. }
  1494. }
  1495. };