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

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