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

conference.js 37KB

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