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.

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