Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conference.js 36KB

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