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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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 CQEvents from './service/connectionquality/CQEvents';
  9. import UIEvents from './service/UI/UIEvents';
  10. const ConnectionEvents = JitsiMeetJS.events.connection;
  11. const ConnectionErrors = JitsiMeetJS.errors.connection;
  12. const ConferenceEvents = JitsiMeetJS.events.conference;
  13. const ConferenceErrors = JitsiMeetJS.errors.conference;
  14. const TrackEvents = JitsiMeetJS.events.track;
  15. const TrackErrors = JitsiMeetJS.errors.track;
  16. let room, connection, localAudio, localVideo, roomLocker;
  17. /**
  18. * Known custom conference commands.
  19. */
  20. const Commands = {
  21. CONNECTION_QUALITY: "stats",
  22. EMAIL: "email",
  23. ETHERPAD: "etherpad"
  24. };
  25. /**
  26. * Open Connection. When authentication failed it shows auth dialog.
  27. * @param roomName the room name to use
  28. * @returns Promise<JitsiConnection>
  29. */
  30. function connect(roomName) {
  31. return openConnection({retry: true, roomName: roomName})
  32. .catch(function (err) {
  33. if (err === ConnectionErrors.PASSWORD_REQUIRED) {
  34. APP.UI.notifyTokenAuthFailed();
  35. } else {
  36. APP.UI.notifyConnectionFailed(err);
  37. }
  38. throw err;
  39. });
  40. }
  41. /**
  42. * Share email with other users.
  43. * @param {string} email new email
  44. */
  45. function sendEmail (email) {
  46. room.sendCommand(Commands.EMAIL, {
  47. value: email,
  48. attributes: {
  49. id: room.myUserId()
  50. }
  51. });
  52. }
  53. /**
  54. * Get user nickname by user id.
  55. * @param {string} id user id
  56. * @returns {string?} user nickname or undefined if user is unknown.
  57. */
  58. function getDisplayName (id) {
  59. if (APP.conference.isLocalId(id)) {
  60. return APP.settings.getDisplayName();
  61. }
  62. let participant = room.getParticipantById(id);
  63. if (participant && participant.getDisplayName()) {
  64. return participant.getDisplayName();
  65. }
  66. }
  67. /**
  68. * Mute or unmute local audio stream if it exists.
  69. * @param {boolean} muted if audio stream should be muted or unmuted.
  70. */
  71. function muteLocalAudio (muted) {
  72. if (!localAudio) {
  73. return;
  74. }
  75. if (muted) {
  76. localAudio.mute().then(function(value) {},
  77. function(value) {
  78. console.warn('Audio Mute was rejected:', value);
  79. }
  80. );
  81. } else {
  82. localAudio.unmute().then(function(value) {},
  83. function(value) {
  84. console.warn('Audio unmute was rejected:', value);
  85. }
  86. );
  87. }
  88. }
  89. /**
  90. * Mute or unmute local video stream if it exists.
  91. * @param {boolean} muted if video stream should be muted or unmuted.
  92. */
  93. function muteLocalVideo (muted) {
  94. if (!localVideo) {
  95. return;
  96. }
  97. if (muted) {
  98. localVideo.mute().then(function(value) {},
  99. function(value) {
  100. console.warn('Video mute was rejected:', value);
  101. }
  102. );
  103. } else {
  104. localVideo.unmute().then(function(value) {},
  105. function(value) {
  106. console.warn('Video unmute was rejected:', value);
  107. }
  108. );
  109. }
  110. }
  111. /**
  112. * Disconnect from the conference and optionally request user feedback.
  113. * @param {boolean} [requestFeedback=false] if user feedback should be requested
  114. */
  115. function hangup (requestFeedback = false) {
  116. let promise = Promise.resolve();
  117. if (requestFeedback) {
  118. promise = APP.UI.requestFeedback();
  119. }
  120. promise.then(function () {
  121. connection.disconnect();
  122. if (!config.enableWelcomePage) {
  123. return;
  124. }
  125. // redirect to welcome page
  126. setTimeout(() => {
  127. APP.settings.setWelcomePageEnabled(true);
  128. window.location.pathname = "/";
  129. }, 3000);
  130. }, function (err) {
  131. console.error('Failed to hangup the call:', err);
  132. });
  133. }
  134. /**
  135. * Create local tracks of specified types.
  136. * @param {string[]} devices required track types ('audio', 'video' etc.)
  137. * @returns {Promise<JitsiLocalTrack[]>}
  138. */
  139. function createLocalTracks (...devices) {
  140. return JitsiMeetJS.createLocalTracks({
  141. // copy array to avoid mutations inside library
  142. devices: devices.slice(0),
  143. resolution: config.resolution,
  144. cameraDeviceId: APP.settings.getCameraDeviceId(),
  145. micDeviceId: APP.settings.getMicDeviceId(),
  146. // adds any ff fake device settings if any
  147. firefox_fake_device: config.firefox_fake_device
  148. }).catch(function (err) {
  149. console.error('failed to create local tracks', ...devices, err);
  150. return Promise.reject(err);
  151. });
  152. }
  153. class ConferenceConnector {
  154. constructor(resolve, reject) {
  155. this._resolve = resolve;
  156. this._reject = reject;
  157. this.reconnectTimeout = null;
  158. room.on(ConferenceEvents.CONFERENCE_JOINED,
  159. this._handleConferenceJoined.bind(this));
  160. room.on(ConferenceEvents.CONFERENCE_FAILED,
  161. this._onConferenceFailed.bind(this));
  162. room.on(ConferenceEvents.CONFERENCE_ERROR,
  163. this._onConferenceError.bind(this));
  164. }
  165. _handleConferenceFailed(err, msg) {
  166. this._unsubscribe();
  167. this._reject(err);
  168. }
  169. _onConferenceFailed(err, ...params) {
  170. console.error('CONFERENCE FAILED:', err, ...params);
  171. switch (err) {
  172. // room is locked by the password
  173. case ConferenceErrors.PASSWORD_REQUIRED:
  174. APP.UI.markRoomLocked(true);
  175. roomLocker.requirePassword().then(function () {
  176. room.join(roomLocker.password);
  177. });
  178. break;
  179. case ConferenceErrors.CONNECTION_ERROR:
  180. {
  181. let [msg] = params;
  182. APP.UI.notifyConnectionFailed(msg);
  183. }
  184. break;
  185. case ConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  186. APP.UI.notifyBridgeDown();
  187. break;
  188. // not enough rights to create conference
  189. case ConferenceErrors.AUTHENTICATION_REQUIRED:
  190. // schedule reconnect to check if someone else created the room
  191. this.reconnectTimeout = setTimeout(function () {
  192. room.join();
  193. }, 5000);
  194. // notify user that auth is required
  195. AuthHandler.requireAuth(room, roomLocker.password);
  196. break;
  197. case ConferenceErrors.RESERVATION_ERROR:
  198. {
  199. let [code, msg] = params;
  200. APP.UI.notifyReservationError(code, msg);
  201. }
  202. break;
  203. case ConferenceErrors.GRACEFUL_SHUTDOWN:
  204. APP.UI.notifyGracefulShutdown();
  205. break;
  206. case ConferenceErrors.JINGLE_FATAL_ERROR:
  207. APP.UI.notifyInternalError();
  208. break;
  209. case ConferenceErrors.CONFERENCE_DESTROYED:
  210. {
  211. let [reason] = params;
  212. APP.UI.hideStats();
  213. APP.UI.notifyConferenceDestroyed(reason);
  214. }
  215. break;
  216. case ConferenceErrors.FOCUS_DISCONNECTED:
  217. {
  218. let [focus, retrySec] = params;
  219. APP.UI.notifyFocusDisconnected(focus, retrySec);
  220. }
  221. break;
  222. case ConferenceErrors.FOCUS_LEFT:
  223. room.leave().then(() => connection.disconnect());
  224. APP.UI.notifyFocusLeft();
  225. break;
  226. default:
  227. this._handleConferenceFailed(err, ...params);
  228. }
  229. }
  230. _onConferenceError(err, ...params) {
  231. console.error('CONFERENCE Error:', err, params);
  232. switch (err) {
  233. case ConferenceErrors.CHAT_ERROR:
  234. {
  235. let [code, msg] = params;
  236. APP.UI.showChatError(code, msg);
  237. }
  238. break;
  239. default:
  240. console.error("Unknown error.");
  241. }
  242. }
  243. _unsubscribe() {
  244. room.off(
  245. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  246. room.off(
  247. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  248. if (this.reconnectTimeout !== null) {
  249. clearTimeout(this.reconnectTimeout);
  250. }
  251. AuthHandler.closeAuth();
  252. }
  253. _handleConferenceJoined() {
  254. this._unsubscribe();
  255. this._resolve();
  256. }
  257. connect() {
  258. room.join();
  259. }
  260. }
  261. export default {
  262. localId: undefined,
  263. isModerator: false,
  264. audioMuted: false,
  265. videoMuted: false,
  266. isSharingScreen: false,
  267. isDesktopSharingEnabled: false,
  268. /**
  269. * Open new connection and join to the conference.
  270. * @param {object} options
  271. * @param {string} roomName name of the conference
  272. * @returns {Promise}
  273. */
  274. init(options) {
  275. this.roomName = options.roomName;
  276. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  277. return JitsiMeetJS.init(config).then(() => {
  278. return Promise.all([
  279. // try to retrieve audio and video
  280. createLocalTracks('audio', 'video')
  281. // if failed then try to retrieve only audio
  282. .catch(() => createLocalTracks('audio'))
  283. // if audio also failed then just return empty array
  284. .catch(() => []),
  285. connect(options.roomName)
  286. ]);
  287. }).then(([tracks, con]) => {
  288. console.log('initialized with %s local tracks', tracks.length);
  289. connection = con;
  290. this._createRoom(tracks);
  291. this.isDesktopSharingEnabled =
  292. JitsiMeetJS.isDesktopSharingEnabled();
  293. // update list of available devices
  294. if (JitsiMeetJS.isDeviceListAvailable() &&
  295. JitsiMeetJS.isDeviceChangeAvailable()) {
  296. JitsiMeetJS.enumerateDevices(
  297. devices => APP.UI.onAvailableDevicesChanged(devices)
  298. );
  299. }
  300. // XXX The API will take care of disconnecting from the XMPP server
  301. // (and, thus, leaving the room) on unload.
  302. return new Promise((resolve, reject) => {
  303. (new ConferenceConnector(resolve, reject)).connect();
  304. });
  305. });
  306. },
  307. /**
  308. * Check if id is id of the local user.
  309. * @param {string} id id to check
  310. * @returns {boolean}
  311. */
  312. isLocalId (id) {
  313. return this.localId === id;
  314. },
  315. /**
  316. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  317. * @param mute true for mute and false for unmute.
  318. */
  319. muteAudio (mute) {
  320. muteLocalAudio(mute);
  321. },
  322. /**
  323. * Returns whether local audio is muted or not.
  324. * @returns {boolean}
  325. */
  326. isLocalAudioMuted() {
  327. return this.audioMuted;
  328. },
  329. /**
  330. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  331. */
  332. toggleAudioMuted () {
  333. this.muteAudio(!this.audioMuted);
  334. },
  335. /**
  336. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  337. * @param mute true for mute and false for unmute.
  338. */
  339. muteVideo (mute) {
  340. muteLocalVideo(mute);
  341. },
  342. /**
  343. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  344. */
  345. toggleVideoMuted () {
  346. this.muteVideo(!this.videoMuted);
  347. },
  348. /**
  349. * Retrieve list of conference participants (without local user).
  350. * @returns {JitsiParticipant[]}
  351. */
  352. listMembers () {
  353. return room.getParticipants();
  354. },
  355. /**
  356. * Retrieve list of ids of conference participants (without local user).
  357. * @returns {string[]}
  358. */
  359. listMembersIds () {
  360. return room.getParticipants().map(p => p.getId());
  361. },
  362. /**
  363. * Check if SIP is supported.
  364. * @returns {boolean}
  365. */
  366. sipGatewayEnabled () {
  367. return room.isSIPCallingSupported();
  368. },
  369. get membersCount () {
  370. return room.getParticipants().length + 1;
  371. },
  372. /**
  373. * Returns true if the callstats integration is enabled, otherwise returns
  374. * false.
  375. *
  376. * @returns true if the callstats integration is enabled, otherwise returns
  377. * false.
  378. */
  379. isCallstatsEnabled () {
  380. return room.isCallstatsEnabled();
  381. },
  382. /**
  383. * Sends the given feedback through CallStats if enabled.
  384. *
  385. * @param overallFeedback an integer between 1 and 5 indicating the
  386. * user feedback
  387. * @param detailedFeedback detailed feedback from the user. Not yet used
  388. */
  389. sendFeedback (overallFeedback, detailedFeedback) {
  390. return room.sendFeedback (overallFeedback, detailedFeedback);
  391. },
  392. // used by torture currently
  393. isJoined () {
  394. return this._room
  395. && this._room.isJoined();
  396. },
  397. getConnectionState () {
  398. return this._room
  399. && this._room.getConnectionState();
  400. },
  401. getMyUserId () {
  402. return this._room
  403. && this._room.myUserId();
  404. },
  405. /**
  406. * Will be filled with values only when config.debug is enabled.
  407. * Its used by torture to check audio levels.
  408. */
  409. audioLevelsMap: {},
  410. /**
  411. * Returns the stored audio level (stored only if config.debug is enabled)
  412. * @param id the id for the user audio level to return (the id value is
  413. * returned for the participant using getMyUserId() method)
  414. */
  415. getPeerSSRCAudioLevel (id) {
  416. return this.audioLevelsMap[id];
  417. },
  418. /**
  419. * Will check for number of remote particiapnts that have at least one
  420. * remote track.
  421. * @return {boolean} whether we have enough participants with remote streams
  422. */
  423. checkEnoughParticipants (number) {
  424. var participants = this._room.getParticipants();
  425. var foundParticipants = 0;
  426. for (var i = 0; i < participants.length; i += 1) {
  427. if (participants[i].getTracks().length > 0) {
  428. foundParticipants++;
  429. }
  430. }
  431. return foundParticipants >= number;
  432. },
  433. /**
  434. * Returns the stats.
  435. */
  436. getStats() {
  437. return ConnectionQuality.getStats();
  438. },
  439. // end used by torture
  440. getLogs () {
  441. return room.getLogs();
  442. },
  443. _createRoom (localTracks) {
  444. room = connection.initJitsiConference(APP.conference.roomName,
  445. this._getConferenceOptions());
  446. this.localId = room.myUserId();
  447. localTracks.forEach((track) => {
  448. if (track.isAudioTrack()) {
  449. this.useAudioStream(track);
  450. } else if (track.isVideoTrack()) {
  451. this.useVideoStream(track);
  452. }
  453. });
  454. roomLocker = createRoomLocker(room);
  455. this._room = room; // FIXME do not use this
  456. let email = APP.settings.getEmail();
  457. email && sendEmail(email);
  458. let nick = APP.settings.getDisplayName();
  459. if (config.useNicks && !nick) {
  460. nick = APP.UI.askForNickname();
  461. APP.settings.setDisplayName(nick);
  462. }
  463. nick && room.setDisplayName(nick);
  464. this._setupListeners();
  465. },
  466. _getConferenceOptions() {
  467. let options = config;
  468. if(config.enableRecording) {
  469. options.recordingType = (config.hosts &&
  470. (typeof config.hosts.jirecon != "undefined"))?
  471. "jirecon" : "colibri";
  472. }
  473. return options;
  474. },
  475. /**
  476. * Start using provided video stream.
  477. * Stops previous video stream.
  478. * @param {JitsiLocalTrack} [stream] new stream to use or null
  479. * @returns {Promise}
  480. */
  481. useVideoStream (stream) {
  482. let promise = Promise.resolve();
  483. if (localVideo) {
  484. // this calls room.removeTrack internally
  485. // so we don't need to remove it manually
  486. promise = localVideo.dispose();
  487. }
  488. localVideo = stream;
  489. return promise.then(function () {
  490. if (stream) {
  491. return room.addTrack(stream);
  492. }
  493. }).then(() => {
  494. if (stream) {
  495. this.videoMuted = stream.isMuted();
  496. this.isSharingScreen = stream.videoType === 'desktop';
  497. APP.UI.addLocalStream(stream);
  498. } else {
  499. this.videoMuted = false;
  500. this.isSharingScreen = false;
  501. }
  502. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  503. APP.UI.updateDesktopSharingButtons();
  504. });
  505. },
  506. /**
  507. * Start using provided audio stream.
  508. * Stops previous audio stream.
  509. * @param {JitsiLocalTrack} [stream] new stream to use or null
  510. * @returns {Promise}
  511. */
  512. useAudioStream (stream) {
  513. let promise = Promise.resolve();
  514. if (localAudio) {
  515. // this calls room.removeTrack internally
  516. // so we don't need to remove it manually
  517. promise = localAudio.dispose();
  518. }
  519. localAudio = stream;
  520. return promise.then(function () {
  521. if (stream) {
  522. return room.addTrack(stream);
  523. }
  524. }).then(() => {
  525. if (stream) {
  526. this.audioMuted = stream.isMuted();
  527. APP.UI.addLocalStream(stream);
  528. } else {
  529. this.audioMuted = false;
  530. }
  531. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  532. });
  533. },
  534. videoSwitchInProgress: false,
  535. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  536. if (this.videoSwitchInProgress) {
  537. console.warn("Switch in progress.");
  538. return;
  539. }
  540. if (!this.isDesktopSharingEnabled) {
  541. console.warn("Cannot toggle screen sharing: not supported.");
  542. return;
  543. }
  544. this.videoSwitchInProgress = true;
  545. if (shareScreen) {
  546. createLocalTracks('desktop').then(([stream]) => {
  547. stream.on(
  548. TrackEvents.LOCAL_TRACK_STOPPED,
  549. () => {
  550. // if stream was stopped during screensharing session
  551. // then we should switch to video
  552. // otherwise we stopped it because we already switched
  553. // to video, so nothing to do here
  554. if (this.isSharingScreen) {
  555. this.toggleScreenSharing(false);
  556. }
  557. }
  558. );
  559. return this.useVideoStream(stream);
  560. }).then(() => {
  561. this.videoSwitchInProgress = false;
  562. console.log('sharing local desktop');
  563. }).catch((err) => {
  564. this.videoSwitchInProgress = false;
  565. this.toggleScreenSharing(false);
  566. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  567. return;
  568. console.error('failed to share local desktop', err);
  569. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  570. APP.UI.showExtensionRequiredDialog(
  571. config.desktopSharingFirefoxExtensionURL
  572. );
  573. return;
  574. }
  575. // Handling:
  576. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  577. // TrackErrors.GENERAL
  578. // and any other
  579. let dialogTxt = APP.translation
  580. .generateTranslationHTML("dialog.failtoinstall");
  581. let dialogTitle = APP.translation
  582. .generateTranslationHTML("dialog.error");
  583. APP.UI.messageHandler.openDialog(
  584. dialogTitle,
  585. dialogTxt,
  586. false
  587. );
  588. });
  589. } else {
  590. createLocalTracks('video').then(
  591. ([stream]) => this.useVideoStream(stream)
  592. ).then(() => {
  593. this.videoSwitchInProgress = false;
  594. console.log('sharing local video');
  595. }).catch((err) => {
  596. this.useVideoStream(null);
  597. this.videoSwitchInProgress = false;
  598. console.error('failed to share local video', err);
  599. });
  600. }
  601. },
  602. /**
  603. * Setup interaction between conference and UI.
  604. */
  605. _setupListeners () {
  606. // add local streams when joined to the conference
  607. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  608. APP.UI.mucJoined();
  609. });
  610. room.on(
  611. ConferenceEvents.AUTH_STATUS_CHANGED,
  612. function (authEnabled, authLogin) {
  613. APP.UI.updateAuthInfo(authEnabled, authLogin);
  614. }
  615. );
  616. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  617. console.log('USER %s connnected', id, user);
  618. APP.API.notifyUserJoined(id);
  619. APP.UI.addUser(id, user.getDisplayName());
  620. // chek the roles for the new user and reflect them
  621. APP.UI.updateUserRole(user);
  622. });
  623. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  624. console.log('USER %s LEFT', id, user);
  625. APP.API.notifyUserLeft(id);
  626. APP.UI.removeUser(id, user.getDisplayName());
  627. });
  628. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  629. if (this.isLocalId(id)) {
  630. console.info(`My role changed, new role: ${role}`);
  631. this.isModerator = room.isModerator();
  632. APP.UI.updateLocalRole(room.isModerator());
  633. } else {
  634. let user = room.getParticipantById(id);
  635. if (user) {
  636. APP.UI.updateUserRole(user);
  637. }
  638. }
  639. });
  640. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  641. if(!track || track.isLocal())
  642. return;
  643. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  644. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  645. });
  646. APP.UI.addRemoteStream(track);
  647. });
  648. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  649. if(!track || track.isLocal())
  650. return;
  651. APP.UI.removeRemoteStream(track);
  652. });
  653. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  654. if(!track)
  655. return;
  656. const handler = (track.getType() === "audio")?
  657. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  658. let id;
  659. const mute = track.isMuted();
  660. if(track.isLocal()){
  661. id = this.localId;
  662. if(track.getType() === "audio") {
  663. this.audioMuted = mute;
  664. } else {
  665. this.videoMuted = mute;
  666. }
  667. } else {
  668. id = track.getParticipantId();
  669. }
  670. handler(id , mute);
  671. });
  672. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  673. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  674. lvl = 0;
  675. }
  676. if(config.debug)
  677. {
  678. this.audioLevelsMap[id] = lvl;
  679. console.log("AudioLevel:" + id + "/" + lvl);
  680. }
  681. APP.UI.setAudioLevel(id, lvl);
  682. });
  683. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  684. //FIXME
  685. if (config.muteLocalVideoIfNotInLastN) {
  686. // TODO mute or unmute if required
  687. // mark video on UI
  688. // APP.UI.markVideoMuted(true/false);
  689. }
  690. });
  691. room.on(
  692. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  693. APP.UI.handleLastNEndpoints(ids, enteringIds);
  694. });
  695. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  696. APP.UI.markDominantSpeaker(id);
  697. });
  698. if (!interfaceConfig.filmStripOnly) {
  699. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  700. APP.UI.markVideoInterrupted(true);
  701. });
  702. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  703. APP.UI.markVideoInterrupted(false);
  704. });
  705. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  706. let nick = getDisplayName(id);
  707. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  708. APP.UI.addMessage(id, nick, text, ts);
  709. });
  710. }
  711. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  712. APP.API.notifyDisplayNameChanged(id, displayName);
  713. APP.UI.changeDisplayName(id, displayName);
  714. });
  715. room.on(ConferenceEvents.RECORDING_STATE_CHANGED, (status, error) => {
  716. if(status == "error") {
  717. console.error(error);
  718. return;
  719. }
  720. APP.UI.updateRecordingState(status);
  721. });
  722. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  723. APP.UI.updateUserStatus(id, status);
  724. });
  725. room.on(ConferenceEvents.KICKED, () => {
  726. APP.UI.hideStats();
  727. APP.UI.notifyKicked();
  728. // FIXME close
  729. });
  730. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  731. APP.UI.updateDTMFSupport(isDTMFSupported);
  732. });
  733. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  734. if (room.isModerator()) {
  735. let promise = roomLocker.isLocked
  736. ? roomLocker.askToUnlock()
  737. : roomLocker.askToLock();
  738. promise.then(() => {
  739. APP.UI.markRoomLocked(roomLocker.isLocked);
  740. });
  741. } else {
  742. roomLocker.notifyModeratorRequired();
  743. }
  744. });
  745. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  746. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  747. if (!interfaceConfig.filmStripOnly) {
  748. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  749. APP.API.notifySendingChatMessage(message);
  750. room.sendTextMessage(message);
  751. });
  752. }
  753. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  754. ConnectionQuality.updateLocalStats(stats);
  755. });
  756. ConnectionQuality.addListener(
  757. CQEvents.LOCALSTATS_UPDATED,
  758. (percent, stats) => {
  759. APP.UI.updateLocalStats(percent, stats);
  760. // send local stats to other users
  761. room.sendCommandOnce(Commands.CONNECTION_QUALITY, {
  762. children: ConnectionQuality.convertToMUCStats(stats),
  763. attributes: {
  764. xmlns: 'http://jitsi.org/jitmeet/stats'
  765. }
  766. });
  767. }
  768. );
  769. // listen to remote stats
  770. room.addCommandListener(Commands.CONNECTION_QUALITY,(values, from) => {
  771. ConnectionQuality.updateRemoteStats(from, values);
  772. });
  773. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  774. (id, percent, stats) => {
  775. APP.UI.updateRemoteStats(id, percent, stats);
  776. });
  777. room.addCommandListener(Commands.ETHERPAD, ({value}) => {
  778. APP.UI.initEtherpad(value);
  779. });
  780. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  781. email = email.trim();
  782. if (email === APP.settings.getEmail()) {
  783. return;
  784. }
  785. APP.settings.setEmail(email);
  786. APP.UI.setUserAvatar(room.myUserId(), email);
  787. sendEmail(email);
  788. });
  789. room.addCommandListener(Commands.EMAIL, (data) => {
  790. APP.UI.setUserAvatar(data.attributes.id, data.value);
  791. });
  792. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  793. nickname = nickname.trim();
  794. if (nickname === APP.settings.getDisplayName()) {
  795. return;
  796. }
  797. APP.settings.setDisplayName(nickname);
  798. room.setDisplayName(nickname);
  799. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  800. });
  801. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  802. (startAudioMuted, startVideoMuted) => {
  803. room.setStartMutedPolicy({
  804. audio: startAudioMuted,
  805. video: startVideoMuted
  806. });
  807. }
  808. );
  809. room.on(
  810. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  811. ({ audio, video }) => {
  812. APP.UI.onStartMutedChanged(audio, video);
  813. }
  814. );
  815. room.on(ConferenceEvents.STARTED_MUTED, () => {
  816. (room.isStartAudioMuted() || room.isStartVideoMuted())
  817. && APP.UI.notifyInitiallyMuted();
  818. });
  819. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  820. APP.UI.inviteParticipants(
  821. roomUrl,
  822. APP.conference.roomName,
  823. roomLocker.password,
  824. APP.settings.getDisplayName()
  825. );
  826. });
  827. room.on(
  828. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  829. APP.UI.updateDevicesAvailability(id, devices);
  830. }
  831. );
  832. // call hangup
  833. APP.UI.addListener(UIEvents.HANGUP, () => {
  834. hangup(true);
  835. });
  836. // logout
  837. APP.UI.addListener(UIEvents.LOGOUT, () => {
  838. AuthHandler.logout(room).then(function (url) {
  839. if (url) {
  840. window.location.href = url;
  841. } else {
  842. hangup(true);
  843. }
  844. });
  845. });
  846. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  847. room.dial(sipNumber);
  848. });
  849. // Starts or stops the recording for the conference.
  850. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, (predefinedToken) => {
  851. if (predefinedToken) {
  852. room.toggleRecording({token: predefinedToken});
  853. return;
  854. }
  855. APP.UI.requestRecordingToken().then((token) => {
  856. room.toggleRecording({token: token});
  857. });
  858. });
  859. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  860. room.setSubject(topic);
  861. });
  862. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  863. APP.UI.setSubject(subject);
  864. });
  865. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  866. room.kickParticipant(id);
  867. });
  868. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  869. room.muteParticipant(id);
  870. });
  871. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  872. AuthHandler.authenticate(room);
  873. });
  874. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  875. room.selectParticipant(id);
  876. });
  877. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (id) => {
  878. room.pinParticipant(id);
  879. });
  880. APP.UI.addListener(
  881. UIEvents.VIDEO_DEVICE_CHANGED,
  882. (cameraDeviceId) => {
  883. APP.settings.setCameraDeviceId(cameraDeviceId);
  884. createLocalTracks('video').then(([stream]) => {
  885. this.useVideoStream(stream);
  886. console.log('switched local video device');
  887. });
  888. }
  889. );
  890. APP.UI.addListener(
  891. UIEvents.AUDIO_DEVICE_CHANGED,
  892. (micDeviceId) => {
  893. APP.settings.setMicDeviceId(micDeviceId);
  894. createLocalTracks('audio').then(([stream]) => {
  895. this.useAudioStream(stream);
  896. console.log('switched local audio device');
  897. });
  898. }
  899. );
  900. APP.UI.addListener(
  901. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  902. );
  903. }
  904. };