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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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. import {VIDEO_CONTAINER_TYPE} from "./modules/UI/videolayout/LargeVideo";
  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. case ConferenceErrors.CONFERENCE_MAX_USERS:
  229. connection.disconnect();
  230. APP.UI.notifyMaxUsersLimitReached();
  231. break;
  232. default:
  233. this._handleConferenceFailed(err, ...params);
  234. }
  235. }
  236. _onConferenceError(err, ...params) {
  237. console.error('CONFERENCE Error:', err, params);
  238. switch (err) {
  239. case ConferenceErrors.CHAT_ERROR:
  240. {
  241. let [code, msg] = params;
  242. APP.UI.showChatError(code, msg);
  243. }
  244. break;
  245. default:
  246. console.error("Unknown error.");
  247. }
  248. }
  249. _unsubscribe() {
  250. room.off(
  251. ConferenceEvents.CONFERENCE_JOINED, this._handleConferenceJoined);
  252. room.off(
  253. ConferenceEvents.CONFERENCE_FAILED, this._onConferenceFailed);
  254. if (this.reconnectTimeout !== null) {
  255. clearTimeout(this.reconnectTimeout);
  256. }
  257. AuthHandler.closeAuth();
  258. }
  259. _handleConferenceJoined() {
  260. this._unsubscribe();
  261. this._resolve();
  262. }
  263. connect() {
  264. room.join();
  265. }
  266. }
  267. export default {
  268. localId: undefined,
  269. isModerator: false,
  270. audioMuted: false,
  271. videoMuted: false,
  272. isSharingScreen: false,
  273. isDesktopSharingEnabled: false,
  274. /**
  275. * Open new connection and join to the conference.
  276. * @param {object} options
  277. * @param {string} roomName name of the conference
  278. * @returns {Promise}
  279. */
  280. init(options) {
  281. this.roomName = options.roomName;
  282. JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
  283. return JitsiMeetJS.init(config).then(() => {
  284. return Promise.all([
  285. // try to retrieve audio and video
  286. createLocalTracks('audio', 'video')
  287. // if failed then try to retrieve only audio
  288. .catch(() => createLocalTracks('audio'))
  289. // if audio also failed then just return empty array
  290. .catch(() => []),
  291. connect(options.roomName)
  292. ]);
  293. }).then(([tracks, con]) => {
  294. console.log('initialized with %s local tracks', tracks.length);
  295. connection = con;
  296. this._createRoom(tracks);
  297. this.isDesktopSharingEnabled =
  298. JitsiMeetJS.isDesktopSharingEnabled();
  299. // update list of available devices
  300. if (JitsiMeetJS.isDeviceListAvailable() &&
  301. JitsiMeetJS.isDeviceChangeAvailable()) {
  302. JitsiMeetJS.enumerateDevices(
  303. devices => APP.UI.onAvailableDevicesChanged(devices)
  304. );
  305. }
  306. // XXX The API will take care of disconnecting from the XMPP server
  307. // (and, thus, leaving the room) on unload.
  308. return new Promise((resolve, reject) => {
  309. (new ConferenceConnector(resolve, reject)).connect();
  310. });
  311. });
  312. },
  313. /**
  314. * Check if id is id of the local user.
  315. * @param {string} id id to check
  316. * @returns {boolean}
  317. */
  318. isLocalId (id) {
  319. return this.localId === id;
  320. },
  321. /**
  322. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  323. * @param mute true for mute and false for unmute.
  324. */
  325. muteAudio (mute) {
  326. muteLocalAudio(mute);
  327. },
  328. /**
  329. * Returns whether local audio is muted or not.
  330. * @returns {boolean}
  331. */
  332. isLocalAudioMuted() {
  333. return this.audioMuted;
  334. },
  335. /**
  336. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  337. */
  338. toggleAudioMuted () {
  339. this.muteAudio(!this.audioMuted);
  340. },
  341. /**
  342. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  343. * @param mute true for mute and false for unmute.
  344. */
  345. muteVideo (mute) {
  346. muteLocalVideo(mute);
  347. },
  348. /**
  349. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  350. */
  351. toggleVideoMuted () {
  352. this.muteVideo(!this.videoMuted);
  353. },
  354. /**
  355. * Retrieve list of conference participants (without local user).
  356. * @returns {JitsiParticipant[]}
  357. */
  358. listMembers () {
  359. return room.getParticipants();
  360. },
  361. /**
  362. * Retrieve list of ids of conference participants (without local user).
  363. * @returns {string[]}
  364. */
  365. listMembersIds () {
  366. return room.getParticipants().map(p => p.getId());
  367. },
  368. /**
  369. * Checks whether the participant identified by id is a moderator.
  370. * @id id to search for participant
  371. * @return {boolean} whether the participant is moderator
  372. */
  373. isParticipantModerator (id) {
  374. let user = room.getParticipantById(id);
  375. return user && user.isModerator();
  376. },
  377. /**
  378. * Check if SIP is supported.
  379. * @returns {boolean}
  380. */
  381. sipGatewayEnabled () {
  382. return room.isSIPCallingSupported();
  383. },
  384. get membersCount () {
  385. return room.getParticipants().length + 1;
  386. },
  387. /**
  388. * Returns true if the callstats integration is enabled, otherwise returns
  389. * false.
  390. *
  391. * @returns true if the callstats integration is enabled, otherwise returns
  392. * false.
  393. */
  394. isCallstatsEnabled () {
  395. return room.isCallstatsEnabled();
  396. },
  397. /**
  398. * Sends the given feedback through CallStats if enabled.
  399. *
  400. * @param overallFeedback an integer between 1 and 5 indicating the
  401. * user feedback
  402. * @param detailedFeedback detailed feedback from the user. Not yet used
  403. */
  404. sendFeedback (overallFeedback, detailedFeedback) {
  405. return room.sendFeedback (overallFeedback, detailedFeedback);
  406. },
  407. // used by torture currently
  408. isJoined () {
  409. return this._room
  410. && this._room.isJoined();
  411. },
  412. getConnectionState () {
  413. return this._room
  414. && this._room.getConnectionState();
  415. },
  416. getMyUserId () {
  417. return this._room
  418. && this._room.myUserId();
  419. },
  420. /**
  421. * Will be filled with values only when config.debug is enabled.
  422. * Its used by torture to check audio levels.
  423. */
  424. audioLevelsMap: {},
  425. /**
  426. * Returns the stored audio level (stored only if config.debug is enabled)
  427. * @param id the id for the user audio level to return (the id value is
  428. * returned for the participant using getMyUserId() method)
  429. */
  430. getPeerSSRCAudioLevel (id) {
  431. return this.audioLevelsMap[id];
  432. },
  433. /**
  434. * Will check for number of remote particiapnts that have at least one
  435. * remote track.
  436. * @return {boolean} whether we have enough participants with remote streams
  437. */
  438. checkEnoughParticipants (number) {
  439. var participants = this._room.getParticipants();
  440. var foundParticipants = 0;
  441. for (var i = 0; i < participants.length; i += 1) {
  442. if (participants[i].getTracks().length > 0) {
  443. foundParticipants++;
  444. }
  445. }
  446. return foundParticipants >= number;
  447. },
  448. /**
  449. * Returns the stats.
  450. */
  451. getStats() {
  452. return ConnectionQuality.getStats();
  453. },
  454. // end used by torture
  455. getLogs () {
  456. return room.getLogs();
  457. },
  458. _createRoom (localTracks) {
  459. room = connection.initJitsiConference(APP.conference.roomName,
  460. this._getConferenceOptions());
  461. this.localId = room.myUserId();
  462. localTracks.forEach((track) => {
  463. if (track.isAudioTrack()) {
  464. this.useAudioStream(track);
  465. } else if (track.isVideoTrack()) {
  466. this.useVideoStream(track);
  467. }
  468. });
  469. roomLocker = createRoomLocker(room);
  470. this._room = room; // FIXME do not use this
  471. let email = APP.settings.getEmail();
  472. email && sendEmail(email);
  473. let nick = APP.settings.getDisplayName();
  474. if (config.useNicks && !nick) {
  475. nick = APP.UI.askForNickname();
  476. APP.settings.setDisplayName(nick);
  477. }
  478. nick && room.setDisplayName(nick);
  479. this._setupListeners();
  480. },
  481. /**
  482. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  483. * desire to keep room private to this instance and (2) the need of other
  484. * modules to send and receive commands to and from participants.
  485. * Eventually, this instance remains in control with respect to the
  486. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  487. * JitsiConference) is to be used in the implementation of the Command(s)
  488. * API of this instance.
  489. */
  490. commands: {
  491. /**
  492. * Receives notifications from other participants about commands aka
  493. * custom events (sent by sendCommand or sendCommandOnce methods).
  494. * @param command {String} the name of the command
  495. * @param handler {Function} handler for the command
  496. */
  497. addCommandListener () {
  498. room.addCommandListener.apply(room, arguments);
  499. },
  500. /**
  501. * Removes command.
  502. * @param name {String} the name of the command.
  503. */
  504. removeCommand () {
  505. room.removeCommand.apply(room, arguments);
  506. },
  507. /**
  508. * Sends command.
  509. * @param name {String} the name of the command.
  510. * @param values {Object} with keys and values that will be sent.
  511. */
  512. sendCommand () {
  513. room.sendCommand.apply(room, arguments);
  514. },
  515. /**
  516. * Sends command one time.
  517. * @param name {String} the name of the command.
  518. * @param values {Object} with keys and values that will be sent.
  519. */
  520. sendCommandOnce () {
  521. room.sendCommandOnce.apply(room, arguments);
  522. },
  523. },
  524. _getConferenceOptions() {
  525. let options = config;
  526. if(config.enableRecording) {
  527. options.recordingType = (config.hosts &&
  528. (typeof config.hosts.jirecon != "undefined"))?
  529. "jirecon" : "colibri";
  530. }
  531. return options;
  532. },
  533. /**
  534. * Start using provided video stream.
  535. * Stops previous video stream.
  536. * @param {JitsiLocalTrack} [stream] new stream to use or null
  537. * @returns {Promise}
  538. */
  539. useVideoStream (stream) {
  540. let promise = Promise.resolve();
  541. if (localVideo) {
  542. // this calls room.removeTrack internally
  543. // so we don't need to remove it manually
  544. promise = localVideo.dispose();
  545. }
  546. localVideo = stream;
  547. return promise.then(function () {
  548. if (stream) {
  549. return room.addTrack(stream);
  550. }
  551. }).then(() => {
  552. if (stream) {
  553. this.videoMuted = stream.isMuted();
  554. this.isSharingScreen = stream.videoType === 'desktop';
  555. APP.UI.addLocalStream(stream);
  556. } else {
  557. this.videoMuted = false;
  558. this.isSharingScreen = false;
  559. }
  560. APP.UI.setVideoMuted(this.localId, this.videoMuted);
  561. APP.UI.updateDesktopSharingButtons();
  562. });
  563. },
  564. /**
  565. * Start using provided audio stream.
  566. * Stops previous audio stream.
  567. * @param {JitsiLocalTrack} [stream] new stream to use or null
  568. * @returns {Promise}
  569. */
  570. useAudioStream (stream) {
  571. let promise = Promise.resolve();
  572. if (localAudio) {
  573. // this calls room.removeTrack internally
  574. // so we don't need to remove it manually
  575. promise = localAudio.dispose();
  576. }
  577. localAudio = stream;
  578. return promise.then(function () {
  579. if (stream) {
  580. return room.addTrack(stream);
  581. }
  582. }).then(() => {
  583. if (stream) {
  584. this.audioMuted = stream.isMuted();
  585. APP.UI.addLocalStream(stream);
  586. } else {
  587. this.audioMuted = false;
  588. }
  589. APP.UI.setAudioMuted(this.localId, this.audioMuted);
  590. });
  591. },
  592. videoSwitchInProgress: false,
  593. toggleScreenSharing (shareScreen = !this.isSharingScreen) {
  594. if (this.videoSwitchInProgress) {
  595. console.warn("Switch in progress.");
  596. return;
  597. }
  598. if (!this.isDesktopSharingEnabled) {
  599. console.warn("Cannot toggle screen sharing: not supported.");
  600. return;
  601. }
  602. this.videoSwitchInProgress = true;
  603. if (shareScreen) {
  604. createLocalTracks('desktop').then(([stream]) => {
  605. stream.on(
  606. TrackEvents.LOCAL_TRACK_STOPPED,
  607. () => {
  608. // if stream was stopped during screensharing session
  609. // then we should switch to video
  610. // otherwise we stopped it because we already switched
  611. // to video, so nothing to do here
  612. if (this.isSharingScreen) {
  613. this.toggleScreenSharing(false);
  614. }
  615. }
  616. );
  617. return this.useVideoStream(stream);
  618. }).then(() => {
  619. this.videoSwitchInProgress = false;
  620. console.log('sharing local desktop');
  621. }).catch((err) => {
  622. this.videoSwitchInProgress = false;
  623. this.toggleScreenSharing(false);
  624. if(err === TrackErrors.CHROME_EXTENSION_USER_CANCELED)
  625. return;
  626. console.error('failed to share local desktop', err);
  627. if (err === TrackErrors.FIREFOX_EXTENSION_NEEDED) {
  628. APP.UI.showExtensionRequiredDialog(
  629. config.desktopSharingFirefoxExtensionURL
  630. );
  631. return;
  632. }
  633. // Handling:
  634. // TrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  635. // TrackErrors.GENERAL
  636. // and any other
  637. let dialogTxt = APP.translation
  638. .generateTranslationHTML("dialog.failtoinstall");
  639. let dialogTitle = APP.translation
  640. .generateTranslationHTML("dialog.error");
  641. APP.UI.messageHandler.openDialog(
  642. dialogTitle,
  643. dialogTxt,
  644. false
  645. );
  646. });
  647. } else {
  648. createLocalTracks('video').then(
  649. ([stream]) => this.useVideoStream(stream)
  650. ).then(() => {
  651. this.videoSwitchInProgress = false;
  652. console.log('sharing local video');
  653. }).catch((err) => {
  654. this.useVideoStream(null);
  655. this.videoSwitchInProgress = false;
  656. console.error('failed to share local video', err);
  657. });
  658. }
  659. },
  660. /**
  661. * Setup interaction between conference and UI.
  662. */
  663. _setupListeners () {
  664. // add local streams when joined to the conference
  665. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  666. APP.UI.mucJoined();
  667. });
  668. room.on(
  669. ConferenceEvents.AUTH_STATUS_CHANGED,
  670. function (authEnabled, authLogin) {
  671. APP.UI.updateAuthInfo(authEnabled, authLogin);
  672. }
  673. );
  674. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  675. console.log('USER %s connnected', id, user);
  676. APP.API.notifyUserJoined(id);
  677. APP.UI.addUser(id, user.getDisplayName());
  678. // chek the roles for the new user and reflect them
  679. APP.UI.updateUserRole(user);
  680. });
  681. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  682. console.log('USER %s LEFT', id, user);
  683. APP.API.notifyUserLeft(id);
  684. APP.UI.removeUser(id, user.getDisplayName());
  685. APP.UI.stopSharedVideo(id);
  686. });
  687. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  688. if (this.isLocalId(id)) {
  689. console.info(`My role changed, new role: ${role}`);
  690. this.isModerator = room.isModerator();
  691. APP.UI.updateLocalRole(room.isModerator());
  692. } else {
  693. let user = room.getParticipantById(id);
  694. if (user) {
  695. APP.UI.updateUserRole(user);
  696. }
  697. }
  698. });
  699. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  700. if(!track || track.isLocal())
  701. return;
  702. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  703. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  704. });
  705. APP.UI.addRemoteStream(track);
  706. });
  707. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  708. if(!track || track.isLocal())
  709. return;
  710. APP.UI.removeRemoteStream(track);
  711. });
  712. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  713. if(!track)
  714. return;
  715. const handler = (track.getType() === "audio")?
  716. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  717. let id;
  718. const mute = track.isMuted();
  719. if(track.isLocal()){
  720. id = this.localId;
  721. if(track.getType() === "audio") {
  722. this.audioMuted = mute;
  723. } else {
  724. this.videoMuted = mute;
  725. }
  726. } else {
  727. id = track.getParticipantId();
  728. }
  729. handler(id , mute);
  730. });
  731. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  732. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  733. lvl = 0;
  734. }
  735. if(config.debug)
  736. {
  737. this.audioLevelsMap[id] = lvl;
  738. console.log("AudioLevel:" + id + "/" + lvl);
  739. }
  740. APP.UI.setAudioLevel(id, lvl);
  741. });
  742. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  743. //FIXME
  744. if (config.muteLocalVideoIfNotInLastN) {
  745. // TODO mute or unmute if required
  746. // mark video on UI
  747. // APP.UI.markVideoMuted(true/false);
  748. }
  749. });
  750. room.on(
  751. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  752. APP.UI.handleLastNEndpoints(ids, enteringIds);
  753. });
  754. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  755. APP.UI.markDominantSpeaker(id);
  756. });
  757. if (!interfaceConfig.filmStripOnly) {
  758. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  759. APP.UI.markVideoInterrupted(true);
  760. });
  761. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  762. APP.UI.markVideoInterrupted(false);
  763. });
  764. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  765. let nick = getDisplayName(id);
  766. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  767. APP.UI.addMessage(id, nick, text, ts);
  768. });
  769. }
  770. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  771. APP.API.notifyDisplayNameChanged(id, displayName);
  772. APP.UI.changeDisplayName(id, displayName);
  773. });
  774. room.on(ConferenceEvents.RECORDING_STATE_CHANGED, (status, error) => {
  775. if(status == "error") {
  776. console.error(error);
  777. return;
  778. }
  779. APP.UI.updateRecordingState(status);
  780. });
  781. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  782. APP.UI.updateUserStatus(id, status);
  783. });
  784. room.on(ConferenceEvents.KICKED, () => {
  785. APP.UI.hideStats();
  786. APP.UI.notifyKicked();
  787. // FIXME close
  788. });
  789. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  790. APP.UI.updateDTMFSupport(isDTMFSupported);
  791. });
  792. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  793. if (room.isModerator()) {
  794. let promise = roomLocker.isLocked
  795. ? roomLocker.askToUnlock()
  796. : roomLocker.askToLock();
  797. promise.then(() => {
  798. APP.UI.markRoomLocked(roomLocker.isLocked);
  799. });
  800. } else {
  801. roomLocker.notifyModeratorRequired();
  802. }
  803. });
  804. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  805. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  806. if (!interfaceConfig.filmStripOnly) {
  807. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  808. APP.API.notifySendingChatMessage(message);
  809. room.sendTextMessage(message);
  810. });
  811. }
  812. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  813. ConnectionQuality.updateLocalStats(stats);
  814. });
  815. ConnectionQuality.addListener(
  816. CQEvents.LOCALSTATS_UPDATED,
  817. (percent, stats) => {
  818. APP.UI.updateLocalStats(percent, stats);
  819. // send local stats to other users
  820. room.sendCommandOnce(Commands.CONNECTION_QUALITY, {
  821. children: ConnectionQuality.convertToMUCStats(stats),
  822. attributes: {
  823. xmlns: 'http://jitsi.org/jitmeet/stats'
  824. }
  825. });
  826. }
  827. );
  828. // listen to remote stats
  829. room.addCommandListener(Commands.CONNECTION_QUALITY,(values, from) => {
  830. ConnectionQuality.updateRemoteStats(from, values);
  831. });
  832. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  833. (id, percent, stats) => {
  834. APP.UI.updateRemoteStats(id, percent, stats);
  835. });
  836. room.addCommandListener(Commands.ETHERPAD, ({value}) => {
  837. APP.UI.initEtherpad(value);
  838. });
  839. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  840. email = email.trim();
  841. if (email === APP.settings.getEmail()) {
  842. return;
  843. }
  844. APP.settings.setEmail(email);
  845. APP.UI.setUserAvatar(room.myUserId(), email);
  846. sendEmail(email);
  847. });
  848. room.addCommandListener(Commands.EMAIL, (data) => {
  849. APP.UI.setUserAvatar(data.attributes.id, data.value);
  850. });
  851. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  852. nickname = nickname.trim();
  853. if (nickname === APP.settings.getDisplayName()) {
  854. return;
  855. }
  856. APP.settings.setDisplayName(nickname);
  857. room.setDisplayName(nickname);
  858. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  859. });
  860. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  861. (startAudioMuted, startVideoMuted) => {
  862. room.setStartMutedPolicy({
  863. audio: startAudioMuted,
  864. video: startVideoMuted
  865. });
  866. }
  867. );
  868. room.on(
  869. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  870. ({ audio, video }) => {
  871. APP.UI.onStartMutedChanged(audio, video);
  872. }
  873. );
  874. room.on(ConferenceEvents.STARTED_MUTED, () => {
  875. (room.isStartAudioMuted() || room.isStartVideoMuted())
  876. && APP.UI.notifyInitiallyMuted();
  877. });
  878. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  879. APP.UI.inviteParticipants(
  880. roomUrl,
  881. APP.conference.roomName,
  882. roomLocker.password,
  883. APP.settings.getDisplayName()
  884. );
  885. });
  886. room.on(
  887. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  888. APP.UI.updateDevicesAvailability(id, devices);
  889. }
  890. );
  891. // call hangup
  892. APP.UI.addListener(UIEvents.HANGUP, () => {
  893. hangup(true);
  894. });
  895. // logout
  896. APP.UI.addListener(UIEvents.LOGOUT, () => {
  897. AuthHandler.logout(room).then(function (url) {
  898. if (url) {
  899. window.location.href = url;
  900. } else {
  901. hangup(true);
  902. }
  903. });
  904. });
  905. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  906. room.dial(sipNumber);
  907. });
  908. // Starts or stops the recording for the conference.
  909. APP.UI.addListener(UIEvents.RECORDING_TOGGLE, (predefinedToken) => {
  910. if (predefinedToken) {
  911. room.toggleRecording({token: predefinedToken});
  912. return;
  913. }
  914. APP.UI.requestRecordingToken().then((token) => {
  915. room.toggleRecording({token: token});
  916. });
  917. });
  918. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  919. room.setSubject(topic);
  920. });
  921. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  922. APP.UI.setSubject(subject);
  923. });
  924. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  925. room.kickParticipant(id);
  926. });
  927. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  928. room.muteParticipant(id);
  929. });
  930. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  931. AuthHandler.authenticate(room);
  932. });
  933. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  934. room.selectParticipant(id);
  935. });
  936. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  937. var smallVideoId = smallVideo.getId();
  938. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  939. && !APP.conference.isLocalId(smallVideoId))
  940. if (isPinned)
  941. room.pinParticipant(smallVideoId);
  942. // When the library starts supporting multiple pins we would
  943. // pass the isPinned parameter together with the identifier,
  944. // but currently we send null to indicate that we unpin the
  945. // last pinned.
  946. else
  947. room.pinParticipant(null);
  948. });
  949. APP.UI.addListener(
  950. UIEvents.VIDEO_DEVICE_CHANGED,
  951. (cameraDeviceId) => {
  952. APP.settings.setCameraDeviceId(cameraDeviceId);
  953. createLocalTracks('video').then(([stream]) => {
  954. this.useVideoStream(stream);
  955. console.log('switched local video device');
  956. });
  957. }
  958. );
  959. APP.UI.addListener(
  960. UIEvents.AUDIO_DEVICE_CHANGED,
  961. (micDeviceId) => {
  962. APP.settings.setMicDeviceId(micDeviceId);
  963. createLocalTracks('audio').then(([stream]) => {
  964. this.useAudioStream(stream);
  965. console.log('switched local audio device');
  966. });
  967. }
  968. );
  969. APP.UI.addListener(
  970. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  971. );
  972. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  973. (url, state, time, volume) => {
  974. // send start and stop commands once, and remove any updates
  975. // that had left
  976. if (state === 'stop' || state === 'start' || state === 'playing') {
  977. room.removeCommand(Commands.SHARED_VIDEO);
  978. room.sendCommandOnce(Commands.SHARED_VIDEO, {
  979. value: url,
  980. attributes: {
  981. state: state,
  982. time: time,
  983. volume: volume
  984. }
  985. });
  986. }
  987. else {
  988. // in case of paused, in order to allow late users to join
  989. // paused
  990. room.sendCommand(Commands.SHARED_VIDEO, {
  991. value: url,
  992. attributes: {
  993. state: state,
  994. time: time,
  995. volume: volume
  996. }
  997. });
  998. }
  999. });
  1000. room.addCommandListener(
  1001. Commands.SHARED_VIDEO, ({value, attributes}, id) => {
  1002. // if we are not the moderator or
  1003. // the command is coming from a user which is not the moderator
  1004. if (!(this.isLocalId(id) && room.isModerator())
  1005. && !this.isParticipantModerator(id))
  1006. {
  1007. console.warn('Received shared video command ' +
  1008. 'not from moderator');
  1009. return;
  1010. }
  1011. if (attributes.state === 'stop') {
  1012. APP.UI.stopSharedVideo(id, attributes);
  1013. } else if (attributes.state === 'start') {
  1014. APP.UI.showSharedVideo(id, value, attributes);
  1015. } else if (attributes.state === 'playing'
  1016. || attributes.state === 'pause') {
  1017. APP.UI.updateSharedVideo(id, value, attributes);
  1018. }
  1019. });
  1020. }
  1021. };