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

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