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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. /**
  469. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  470. * desire to keep room private to this instance and (2) the need of other
  471. * modules to send and receive commands to and from participants.
  472. * Eventually, this instance remains in control with respect to the
  473. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  474. * JitsiConference) is to be used in the implementation of the Command(s)
  475. * API of this instance.
  476. */
  477. commands: {
  478. /**
  479. * Receives notifications from other participants about commands aka
  480. * custom events (sent by sendCommand or sendCommandOnce methods).
  481. * @param command {String} the name of the command
  482. * @param handler {Function} handler for the command
  483. */
  484. addCommandListener () {
  485. room.addCommandListener.apply(room, arguments);
  486. },
  487. /**
  488. * Removes command.
  489. * @param name {String} the name of the command.
  490. */
  491. removeCommand () {
  492. room.removeCommand.apply(room, arguments);
  493. },
  494. /**
  495. * Sends command.
  496. * @param name {String} the name of the command.
  497. * @param values {Object} with keys and values that will be sent.
  498. */
  499. sendCommand () {
  500. room.sendCommand.apply(room, arguments);
  501. },
  502. /**
  503. * Sends command one time.
  504. * @param name {String} the name of the command.
  505. * @param values {Object} with keys and values that will be sent.
  506. */
  507. sendCommandOnce () {
  508. room.sendCommandOnce.apply(room, arguments);
  509. },
  510. },
  511. _getConferenceOptions() {
  512. let options = config;
  513. if(config.enableRecording) {
  514. options.recordingType = (config.hosts &&
  515. (typeof config.hosts.jirecon != "undefined"))?
  516. "jirecon" : "colibri";
  517. }
  518. return options;
  519. },
  520. /**
  521. * Start using provided video stream.
  522. * Stops previous video stream.
  523. * @param {JitsiLocalTrack} [stream] new stream to use or null
  524. * @returns {Promise}
  525. */
  526. useVideoStream (stream) {
  527. let promise = Promise.resolve();
  528. if (localVideo) {
  529. // this calls room.removeTrack internally
  530. // so we don't need to remove it manually
  531. promise = localVideo.dispose();
  532. }
  533. localVideo = stream;
  534. return promise.then(function () {
  535. if (stream) {
  536. return room.addTrack(stream);
  537. }
  538. }).then(() => {
  539. if (stream) {
  540. this.videoMuted = stream.isMuted();
  541. this.isSharingScreen = stream.videoType === 'desktop';
  542. APP.UI.addLocalStream(stream);
  543. } else {
  544. this.videoMuted = false;
  545. this.isSharingScreen = false;
  546. }
  547. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  548. APP.UI.updateDesktopSharingButtons();
  549. });
  550. },
  551. /**
  552. * Start using provided audio stream.
  553. * Stops previous audio stream.
  554. * @param {JitsiLocalTrack} [stream] new stream to use or null
  555. * @returns {Promise}
  556. */
  557. useAudioStream (stream) {
  558. let promise = Promise.resolve();
  559. if (localAudio) {
  560. // this calls room.removeTrack internally
  561. // so we don't need to remove it manually
  562. promise = localAudio.dispose();
  563. }
  564. localAudio = stream;
  565. return promise.then(function () {
  566. if (stream) {
  567. return room.addTrack(stream);
  568. }
  569. }).then(() => {
  570. if (stream) {
  571. this.audioMuted = stream.isMuted();
  572. APP.UI.addLocalStream(stream);
  573. } else {
  574. this.audioMuted = false;
  575. }
  576. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  577. });
  578. },
  579. videoSwitchInProgress: false,
  580. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  581. if (this.videoSwitchInProgress) {
  582. console.warn("Switch in progress.");
  583. return;
  584. }
  585. if (!this.isDesktopSharingEnabled) {
  586. console.warn("Cannot toggle screen sharing: not supported.");
  587. return;
  588. }
  589. this.videoSwitchInProgress = true;
  590. if (shareScreen) {
  591. createLocalTracks('desktop').then(([stream]) => {
  592. stream.on(
  593. TrackEvents.LOCAL_TRACK_STOPPED,
  594. () => {
  595. // if stream was stopped during screensharing session
  596. // then we should switch to video
  597. // otherwise we stopped it because we already switched
  598. // to video, so nothing to do here
  599. if (this.isSharingScreen) {
  600. this.toggleScreenSharing(false);
  601. }
  602. }
  603. );
  604. return this.useVideoStream(stream);
  605. }).then(() => {
  606. this.videoSwitchInProgress = false;
  607. console.log('sharing local desktop');
  608. }).catch((err) => {
  609. this.videoSwitchInProgress = false;
  610. this.toggleScreenSharing(false);
  611. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  612. return;
  613. console.error('failed to share local desktop', err);
  614. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  615. APP.UI.showExtensionRequiredDialog(
  616. config.desktopSharingFirefoxExtensionURL
  617. );
  618. return;
  619. }
  620. // Handling:
  621. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  622. // TrackErrors.GENERAL
  623. // and any other
  624. let dialogTxt = APP.translation
  625. .generateTranslationHTML("dialog.failtoinstall");
  626. let dialogTitle = APP.translation
  627. .generateTranslationHTML("dialog.error");
  628. APP.UI.messageHandler.openDialog(
  629. dialogTitle,
  630. dialogTxt,
  631. false
  632. );
  633. });
  634. } else {
  635. createLocalTracks('video').then(
  636. ([stream]) => this.useVideoStream(stream)
  637. ).then(() => {
  638. this.videoSwitchInProgress = false;
  639. console.log('sharing local video');
  640. }).catch((err) => {
  641. this.useVideoStream(null);
  642. this.videoSwitchInProgress = false;
  643. console.error('failed to share local video', err);
  644. });
  645. }
  646. },
  647. /**
  648. * Setup interaction between conference and UI.
  649. */
  650. _setupListeners () {
  651. // add local streams when joined to the conference
  652. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  653. APP.UI.mucJoined();
  654. });
  655. room.on(
  656. ConferenceEvents.AUTH_STATUS_CHANGED,
  657. function (authEnabled, authLogin) {
  658. APP.UI.updateAuthInfo(authEnabled, authLogin);
  659. }
  660. );
  661. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  662. console.log('USER %s connnected', id, user);
  663. APP.API.notifyUserJoined(id);
  664. APP.UI.addUser(id, user.getDisplayName());
  665. // chek the roles for the new user and reflect them
  666. APP.UI.updateUserRole(user);
  667. });
  668. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  669. console.log('USER %s LEFT', id, user);
  670. APP.API.notifyUserLeft(id);
  671. APP.UI.removeUser(id, user.getDisplayName());
  672. APP.UI.stopPrezi(id);
  673. });
  674. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  675. if (this.isLocalId(id)) {
  676. console.info(`My role changed, new role: ${role}`);
  677. this.isModerator = room.isModerator();
  678. APP.UI.updateLocalRole(room.isModerator());
  679. } else {
  680. let user = room.getParticipantById(id);
  681. if (user) {
  682. APP.UI.updateUserRole(user);
  683. }
  684. }
  685. });
  686. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  687. if(!track || track.isLocal())
  688. return;
  689. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  690. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  691. });
  692. APP.UI.addRemoteStream(track);
  693. });
  694. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  695. if(!track || track.isLocal())
  696. return;
  697. APP.UI.removeRemoteStream(track);
  698. });
  699. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  700. if(!track)
  701. return;
  702. const handler = (track.getType() === "audio")?
  703. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  704. let id;
  705. const mute = track.isMuted();
  706. if(track.isLocal()){
  707. id = this.localId;
  708. if(track.getType() === "audio") {
  709. this.audioMuted = mute;
  710. } else {
  711. this.videoMuted = mute;
  712. }
  713. } else {
  714. id = track.getParticipantId();
  715. }
  716. handler(id , mute);
  717. });
  718. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  719. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  720. lvl = 0;
  721. }
  722. if(config.debug)
  723. {
  724. this.audioLevelsMap[id] = lvl;
  725. console.log("AudioLevel:" + id + "/" + lvl);
  726. }
  727. APP.UI.setAudioLevel(id, lvl);
  728. });
  729. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  730. //FIXME
  731. if (config.muteLocalVideoIfNotInLastN) {
  732. // TODO mute or unmute if required
  733. // mark video on UI
  734. // APP.UI.markVideoMuted(true/false);
  735. }
  736. });
  737. room.on(
  738. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  739. APP.UI.handleLastNEndpoints(ids, enteringIds);
  740. });
  741. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  742. APP.UI.markDominantSpeaker(id);
  743. });
  744. if (!interfaceConfig.filmStripOnly) {
  745. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  746. APP.UI.markVideoInterrupted(true);
  747. });
  748. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  749. APP.UI.markVideoInterrupted(false);
  750. });
  751. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  752. let nick = getDisplayName(id);
  753. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  754. APP.UI.addMessage(id, nick, text, ts);
  755. });
  756. }
  757. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  758. APP.API.notifyDisplayNameChanged(id, displayName);
  759. APP.UI.changeDisplayName(id, displayName);
  760. });
  761. room.on(ConferenceEvents.RECORDING_STATE_CHANGED, (status, error) => {
  762. if(status == "error") {
  763. console.error(error);
  764. return;
  765. }
  766. APP.UI.updateRecordingState(status);
  767. });
  768. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  769. APP.UI.updateUserStatus(id, status);
  770. });
  771. room.on(ConferenceEvents.KICKED, () => {
  772. APP.UI.hideStats();
  773. APP.UI.notifyKicked();
  774. // FIXME close
  775. });
  776. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  777. APP.UI.updateDTMFSupport(isDTMFSupported);
  778. });
  779. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  780. if (room.isModerator()) {
  781. let promise = roomLocker.isLocked
  782. ? roomLocker.askToUnlock()
  783. : roomLocker.askToLock();
  784. promise.then(() => {
  785. APP.UI.markRoomLocked(roomLocker.isLocked);
  786. });
  787. } else {
  788. roomLocker.notifyModeratorRequired();
  789. }
  790. });
  791. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  792. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  793. if (!interfaceConfig.filmStripOnly) {
  794. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  795. APP.API.notifySendingChatMessage(message);
  796. room.sendTextMessage(message);
  797. });
  798. }
  799. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  800. ConnectionQuality.updateLocalStats(stats);
  801. });
  802. ConnectionQuality.addListener(
  803. CQEvents.LOCALSTATS_UPDATED,
  804. (percent, stats) => {
  805. APP.UI.updateLocalStats(percent, stats);
  806. // send local stats to other users
  807. room.sendCommandOnce(Commands.CONNECTION_QUALITY, {
  808. children: ConnectionQuality.convertToMUCStats(stats),
  809. attributes: {
  810. xmlns: 'http://jitsi.org/jitmeet/stats'
  811. }
  812. });
  813. }
  814. );
  815. // listen to remote stats
  816. room.addCommandListener(Commands.CONNECTION_QUALITY,(values, from) => {
  817. ConnectionQuality.updateRemoteStats(from, values);
  818. });
  819. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  820. (id, percent, stats) => {
  821. APP.UI.updateRemoteStats(id, percent, stats);
  822. });
  823. room.addCommandListener(Commands.ETHERPAD, ({value}) => {
  824. APP.UI.initEtherpad(value);
  825. });
  826. room.addCommandListener(Commands.PREZI, ({value, attributes}) => {
  827. APP.UI.showPrezi(attributes.id, value, attributes.slide);
  828. });
  829. room.addCommandListener(Commands.STOP_PREZI, ({attributes}) => {
  830. APP.UI.stopPrezi(attributes.id);
  831. });
  832. APP.UI.addListener(UIEvents.SHARE_PREZI, (url, slide) => {
  833. console.log('Sharing Prezi %s slide %s', url, slide);
  834. room.removeCommand(Commands.PREZI);
  835. room.sendCommand(Commands.PREZI, {
  836. value: url,
  837. attributes: {
  838. id: room.myUserId(),
  839. slide
  840. }
  841. });
  842. });
  843. APP.UI.addListener(UIEvents.STOP_SHARING_PREZI, () => {
  844. room.removeCommand(Commands.PREZI);
  845. room.sendCommandOnce(Commands.STOP_PREZI, {
  846. attributes: {
  847. id: room.myUserId()
  848. }
  849. });
  850. });
  851. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  852. email = email.trim();
  853. if (email === APP.settings.getEmail()) {
  854. return;
  855. }
  856. APP.settings.setEmail(email);
  857. APP.UI.setUserAvatar(room.myUserId(), email);
  858. sendEmail(email);
  859. });
  860. room.addCommandListener(Commands.EMAIL, (data) => {
  861. APP.UI.setUserAvatar(data.attributes.id, data.value);
  862. });
  863. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  864. nickname = nickname.trim();
  865. if (nickname === APP.settings.getDisplayName()) {
  866. return;
  867. }
  868. APP.settings.setDisplayName(nickname);
  869. room.setDisplayName(nickname);
  870. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  871. });
  872. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  873. (startAudioMuted, startVideoMuted) => {
  874. room.setStartMutedPolicy({
  875. audio: startAudioMuted,
  876. video: startVideoMuted
  877. });
  878. }
  879. );
  880. room.on(
  881. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  882. ({ audio, video }) => {
  883. APP.UI.onStartMutedChanged(audio, video);
  884. }
  885. );
  886. room.on(ConferenceEvents.STARTED_MUTED, () => {
  887. (room.isStartAudioMuted() || room.isStartVideoMuted())
  888. && APP.UI.notifyInitiallyMuted();
  889. });
  890. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  891. APP.UI.inviteParticipants(
  892. roomUrl,
  893. APP.conference.roomName,
  894. roomLocker.password,
  895. APP.settings.getDisplayName()
  896. );
  897. });
  898. room.on(
  899. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  900. APP.UI.updateDevicesAvailability(id, devices);
  901. }
  902. );
  903. // call hangup
  904. APP.UI.addListener(UIEvents.HANGUP, () => {
  905. hangup(true);
  906. });
  907. // logout
  908. APP.UI.addListener(UIEvents.LOGOUT, () => {
  909. AuthHandler.logout(room).then(function (url) {
  910. if (url) {
  911. window.location.href = url;
  912. } else {
  913. hangup(true);
  914. }
  915. });
  916. });
  917. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  918. room.dial(sipNumber);
  919. });
  920. // Starts or stops the recording for the conference.
  921. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, (predefinedToken) => {
  922. if (predefinedToken) {
  923. room.toggleRecording({token: predefinedToken});
  924. return;
  925. }
  926. APP.UI.requestRecordingToken().then((token) => {
  927. room.toggleRecording({token: token});
  928. });
  929. });
  930. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  931. room.setSubject(topic);
  932. });
  933. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  934. APP.UI.setSubject(subject);
  935. });
  936. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  937. room.kickParticipant(id);
  938. });
  939. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  940. room.muteParticipant(id);
  941. });
  942. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  943. AuthHandler.authenticate(room);
  944. });
  945. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  946. room.selectParticipant(id);
  947. });
  948. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (id) => {
  949. room.pinParticipant(id);
  950. });
  951. APP.UI.addListener(
  952. UIEvents.VIDEO_DEVICE_CHANGED,
  953. (cameraDeviceId) => {
  954. APP.settings.setCameraDeviceId(cameraDeviceId);
  955. createLocalTracks('video').then(([stream]) => {
  956. this.useVideoStream(stream);
  957. console.log('switched local video device');
  958. });
  959. }
  960. );
  961. APP.UI.addListener(
  962. UIEvents.AUDIO_DEVICE_CHANGED,
  963. (micDeviceId) => {
  964. APP.settings.setMicDeviceId(micDeviceId);
  965. createLocalTracks('audio').then(([stream]) => {
  966. this.useAudioStream(stream);
  967. console.log('switched local audio device');
  968. });
  969. }
  970. );
  971. APP.UI.addListener(
  972. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  973. );
  974. }
  975. };