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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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. // add local streams when joined to the conference
  667. room.on(ConferenceEvents.CONFERENCE_JOINED, () => {
  668. APP.UI.mucJoined();
  669. });
  670. room.on(
  671. ConferenceEvents.AUTH_STATUS_CHANGED,
  672. function (authEnabled, authLogin) {
  673. APP.UI.updateAuthInfo(authEnabled, authLogin);
  674. }
  675. );
  676. room.on(ConferenceEvents.USER_JOINED, (id, user) => {
  677. console.log('USER %s connnected', id, user);
  678. APP.API.notifyUserJoined(id);
  679. APP.UI.addUser(id, user.getDisplayName());
  680. // chek the roles for the new user and reflect them
  681. APP.UI.updateUserRole(user);
  682. });
  683. room.on(ConferenceEvents.USER_LEFT, (id, user) => {
  684. console.log('USER %s LEFT', id, user);
  685. APP.API.notifyUserLeft(id);
  686. APP.UI.removeUser(id, user.getDisplayName());
  687. APP.UI.stopSharedVideo(id);
  688. });
  689. room.on(ConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  690. if (this.isLocalId(id)) {
  691. console.info(`My role changed, new role: ${role}`);
  692. this.isModerator = room.isModerator();
  693. APP.UI.updateLocalRole(room.isModerator());
  694. } else {
  695. let user = room.getParticipantById(id);
  696. if (user) {
  697. APP.UI.updateUserRole(user);
  698. }
  699. }
  700. });
  701. room.on(ConferenceEvents.TRACK_ADDED, (track) => {
  702. if(!track || track.isLocal())
  703. return;
  704. track.on(TrackEvents.TRACK_VIDEOTYPE_CHANGED, (type) => {
  705. APP.UI.onPeerVideoTypeChanged(track.getParticipantId(), type);
  706. });
  707. APP.UI.addRemoteStream(track);
  708. });
  709. room.on(ConferenceEvents.TRACK_REMOVED, (track) => {
  710. if(!track || track.isLocal())
  711. return;
  712. APP.UI.removeRemoteStream(track);
  713. });
  714. room.on(ConferenceEvents.TRACK_MUTE_CHANGED, (track) => {
  715. if(!track)
  716. return;
  717. const handler = (track.getType() === "audio")?
  718. APP.UI.setAudioMuted : APP.UI.setVideoMuted;
  719. let id;
  720. const mute = track.isMuted();
  721. if(track.isLocal()){
  722. id = this.localId;
  723. if(track.getType() === "audio") {
  724. this.audioMuted = mute;
  725. } else {
  726. this.videoMuted = mute;
  727. }
  728. } else {
  729. id = track.getParticipantId();
  730. }
  731. handler(id , mute);
  732. });
  733. room.on(ConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  734. if(this.isLocalId(id) && localAudio && localAudio.isMuted()) {
  735. lvl = 0;
  736. }
  737. if(config.debug)
  738. {
  739. this.audioLevelsMap[id] = lvl;
  740. console.log("AudioLevel:" + id + "/" + lvl);
  741. }
  742. APP.UI.setAudioLevel(id, lvl);
  743. });
  744. room.on(ConferenceEvents.IN_LAST_N_CHANGED, (inLastN) => {
  745. //FIXME
  746. if (config.muteLocalVideoIfNotInLastN) {
  747. // TODO mute or unmute if required
  748. // mark video on UI
  749. // APP.UI.markVideoMuted(true/false);
  750. }
  751. });
  752. room.on(
  753. ConferenceEvents.LAST_N_ENDPOINTS_CHANGED, (ids, enteringIds) => {
  754. APP.UI.handleLastNEndpoints(ids, enteringIds);
  755. });
  756. room.on(ConferenceEvents.DOMINANT_SPEAKER_CHANGED, (id) => {
  757. APP.UI.markDominantSpeaker(id);
  758. });
  759. if (!interfaceConfig.filmStripOnly) {
  760. room.on(ConferenceEvents.CONNECTION_INTERRUPTED, () => {
  761. APP.UI.markVideoInterrupted(true);
  762. });
  763. room.on(ConferenceEvents.CONNECTION_RESTORED, () => {
  764. APP.UI.markVideoInterrupted(false);
  765. });
  766. room.on(ConferenceEvents.MESSAGE_RECEIVED, (id, text, ts) => {
  767. let nick = getDisplayName(id);
  768. APP.API.notifyReceivedChatMessage(id, nick, text, ts);
  769. APP.UI.addMessage(id, nick, text, ts);
  770. });
  771. }
  772. room.on(ConferenceEvents.DISPLAY_NAME_CHANGED, (id, displayName) => {
  773. APP.API.notifyDisplayNameChanged(id, displayName);
  774. APP.UI.changeDisplayName(id, displayName);
  775. });
  776. room.on(ConferenceEvents.RECORDER_STATE_CHANGED, (status, error) => {
  777. console.log("Received recorder status change: ", status, error);
  778. if(status == "error") {
  779. console.error(error);
  780. return;
  781. }
  782. APP.UI.updateRecordingState(status);
  783. });
  784. room.on(ConferenceEvents.USER_STATUS_CHANGED, function (id, status) {
  785. APP.UI.updateUserStatus(id, status);
  786. });
  787. room.on(ConferenceEvents.KICKED, () => {
  788. APP.UI.hideStats();
  789. APP.UI.notifyKicked();
  790. // FIXME close
  791. });
  792. room.on(ConferenceEvents.DTMF_SUPPORT_CHANGED, (isDTMFSupported) => {
  793. APP.UI.updateDTMFSupport(isDTMFSupported);
  794. });
  795. APP.UI.addListener(UIEvents.ROOM_LOCK_CLICKED, () => {
  796. if (room.isModerator()) {
  797. let promise = roomLocker.isLocked
  798. ? roomLocker.askToUnlock()
  799. : roomLocker.askToLock();
  800. promise.then(() => {
  801. APP.UI.markRoomLocked(roomLocker.isLocked);
  802. });
  803. } else {
  804. roomLocker.notifyModeratorRequired();
  805. }
  806. });
  807. APP.UI.addListener(UIEvents.AUDIO_MUTED, muteLocalAudio);
  808. APP.UI.addListener(UIEvents.VIDEO_MUTED, muteLocalVideo);
  809. if (!interfaceConfig.filmStripOnly) {
  810. APP.UI.addListener(UIEvents.MESSAGE_CREATED, (message) => {
  811. APP.API.notifySendingChatMessage(message);
  812. room.sendTextMessage(message);
  813. });
  814. }
  815. room.on(ConferenceEvents.CONNECTION_STATS, function (stats) {
  816. ConnectionQuality.updateLocalStats(stats);
  817. });
  818. ConnectionQuality.addListener(
  819. CQEvents.LOCALSTATS_UPDATED,
  820. (percent, stats) => {
  821. APP.UI.updateLocalStats(percent, stats);
  822. // send local stats to other users
  823. room.sendCommandOnce(this.commands.defaults.CONNECTION_QUALITY,
  824. {
  825. children: ConnectionQuality.convertToMUCStats(stats),
  826. attributes: {
  827. xmlns: 'http://jitsi.org/jitmeet/stats'
  828. }
  829. });
  830. }
  831. );
  832. // listen to remote stats
  833. room.addCommandListener(this.commands.defaults.CONNECTION_QUALITY,
  834. (values, from) => {
  835. ConnectionQuality.updateRemoteStats(from, values);
  836. });
  837. ConnectionQuality.addListener(CQEvents.REMOTESTATS_UPDATED,
  838. (id, percent, stats) => {
  839. APP.UI.updateRemoteStats(id, percent, stats);
  840. });
  841. room.addCommandListener(this.commands.defaults.ETHERPAD, ({value}) => {
  842. APP.UI.initEtherpad(value);
  843. });
  844. APP.UI.addListener(UIEvents.EMAIL_CHANGED, (email = '') => {
  845. email = email.trim();
  846. if (email === APP.settings.getEmail()) {
  847. return;
  848. }
  849. APP.settings.setEmail(email);
  850. APP.UI.setUserAvatar(room.myUserId(), email);
  851. sendEmail(this.commands.defaults.EMAIL, email);
  852. });
  853. room.addCommandListener(this.commands.defaults.EMAIL, (data) => {
  854. APP.UI.setUserAvatar(data.attributes.id, data.value);
  855. });
  856. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, (nickname = '') => {
  857. nickname = nickname.trim();
  858. if (nickname === APP.settings.getDisplayName()) {
  859. return;
  860. }
  861. APP.settings.setDisplayName(nickname);
  862. room.setDisplayName(nickname);
  863. APP.UI.changeDisplayName(APP.conference.localId, nickname);
  864. });
  865. APP.UI.addListener(UIEvents.START_MUTED_CHANGED,
  866. (startAudioMuted, startVideoMuted) => {
  867. room.setStartMutedPolicy({
  868. audio: startAudioMuted,
  869. video: startVideoMuted
  870. });
  871. }
  872. );
  873. room.on(
  874. ConferenceEvents.START_MUTED_POLICY_CHANGED,
  875. ({ audio, video }) => {
  876. APP.UI.onStartMutedChanged(audio, video);
  877. }
  878. );
  879. room.on(ConferenceEvents.STARTED_MUTED, () => {
  880. (room.isStartAudioMuted() || room.isStartVideoMuted())
  881. && APP.UI.notifyInitiallyMuted();
  882. });
  883. APP.UI.addListener(UIEvents.USER_INVITED, (roomUrl) => {
  884. APP.UI.inviteParticipants(
  885. roomUrl,
  886. APP.conference.roomName,
  887. roomLocker.password,
  888. APP.settings.getDisplayName()
  889. );
  890. });
  891. room.on(
  892. ConferenceEvents.AVAILABLE_DEVICES_CHANGED, function (id, devices) {
  893. APP.UI.updateDevicesAvailability(id, devices);
  894. }
  895. );
  896. // call hangup
  897. APP.UI.addListener(UIEvents.HANGUP, () => {
  898. hangup(true);
  899. });
  900. // logout
  901. APP.UI.addListener(UIEvents.LOGOUT, () => {
  902. AuthHandler.logout(room).then(function (url) {
  903. if (url) {
  904. window.location.href = url;
  905. } else {
  906. hangup(true);
  907. }
  908. });
  909. });
  910. APP.UI.addListener(UIEvents.SIP_DIAL, (sipNumber) => {
  911. room.dial(sipNumber);
  912. });
  913. // Starts or stops the recording for the conference.
  914. APP.UI.addListener(UIEvents.RECORDING_TOGGLED, (options) => {
  915. room.toggleRecording(options);
  916. });
  917. APP.UI.addListener(UIEvents.SUBJECT_CHANGED, (topic) => {
  918. room.setSubject(topic);
  919. });
  920. room.on(ConferenceEvents.SUBJECT_CHANGED, function (subject) {
  921. APP.UI.setSubject(subject);
  922. });
  923. APP.UI.addListener(UIEvents.USER_KICKED, (id) => {
  924. room.kickParticipant(id);
  925. });
  926. APP.UI.addListener(UIEvents.REMOTE_AUDIO_MUTED, (id) => {
  927. room.muteParticipant(id);
  928. });
  929. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  930. AuthHandler.authenticate(room);
  931. });
  932. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT, (id) => {
  933. room.selectParticipant(id);
  934. });
  935. APP.UI.addListener(UIEvents.PINNED_ENDPOINT, (smallVideo, isPinned) => {
  936. var smallVideoId = smallVideo.getId();
  937. if (smallVideo.getVideoType() === VIDEO_CONTAINER_TYPE
  938. && !APP.conference.isLocalId(smallVideoId))
  939. if (isPinned)
  940. room.pinParticipant(smallVideoId);
  941. // When the library starts supporting multiple pins we would
  942. // pass the isPinned parameter together with the identifier,
  943. // but currently we send null to indicate that we unpin the
  944. // last pinned.
  945. else
  946. room.pinParticipant(null);
  947. });
  948. APP.UI.addListener(
  949. UIEvents.VIDEO_DEVICE_CHANGED,
  950. (cameraDeviceId) => {
  951. APP.settings.setCameraDeviceId(cameraDeviceId);
  952. createLocalTracks('video').then(([stream]) => {
  953. this.useVideoStream(stream);
  954. console.log('switched local video device');
  955. });
  956. }
  957. );
  958. APP.UI.addListener(
  959. UIEvents.AUDIO_DEVICE_CHANGED,
  960. (micDeviceId) => {
  961. APP.settings.setMicDeviceId(micDeviceId);
  962. createLocalTracks('audio').then(([stream]) => {
  963. this.useAudioStream(stream);
  964. console.log('switched local audio device');
  965. });
  966. }
  967. );
  968. APP.UI.addListener(
  969. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  970. );
  971. APP.UI.addListener(UIEvents.UPDATE_SHARED_VIDEO,
  972. (url, state, time, volume) => {
  973. // send start and stop commands once, and remove any updates
  974. // that had left
  975. if (state === 'stop' || state === 'start' || state === 'playing') {
  976. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  977. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  978. value: url,
  979. attributes: {
  980. state: state,
  981. time: time,
  982. volume: volume
  983. }
  984. });
  985. }
  986. else {
  987. // in case of paused, in order to allow late users to join
  988. // paused
  989. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  990. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  991. value: url,
  992. attributes: {
  993. state: state,
  994. time: time,
  995. volume: volume
  996. }
  997. });
  998. }
  999. });
  1000. room.addCommandListener(
  1001. this.commands.defaults.SHARED_VIDEO, ({value, attributes}, id) => {
  1002. if (attributes.state === 'stop') {
  1003. APP.UI.stopSharedVideo(id, attributes);
  1004. } else if (attributes.state === 'start') {
  1005. APP.UI.showSharedVideo(id, value, attributes);
  1006. } else if (attributes.state === 'playing'
  1007. || attributes.state === 'pause') {
  1008. APP.UI.updateSharedVideo(id, value, attributes);
  1009. }
  1010. });
  1011. }
  1012. };