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

JitsiConference.js 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. /* global Strophe, $, Promise */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var RTC = require("./modules/RTC/RTC");
  4. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  5. var EventEmitter = require("events");
  6. import * as JitsiConferenceErrors from "./JitsiConferenceErrors";
  7. import * as JitsiConferenceEvents from "./JitsiConferenceEvents";
  8. import JitsiParticipant from "./JitsiParticipant";
  9. var Statistics = require("./modules/statistics/statistics");
  10. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  11. import JitsiTrackError from "./JitsiTrackError";
  12. import * as JitsiTrackErrors from "./JitsiTrackErrors";
  13. import * as JitsiTrackEvents from "./JitsiTrackEvents";
  14. var Settings = require("./modules/settings/Settings");
  15. var ComponentsVersions = require("./modules/version/ComponentsVersions");
  16. var GlobalOnErrorHandler = require("./modules/util/GlobalOnErrorHandler");
  17. var JitsiConferenceEventManager = require("./JitsiConferenceEventManager");
  18. var VideoType = require('./service/RTC/VideoType');
  19. var Transcriber = require("./modules/transcription/transcriber");
  20. import ParticipantConnectionStatus
  21. from "./modules/connectivity/ParticipantConnectionStatus";
  22. import TalkMutedDetection from "./modules/TalkMutedDetection";
  23. import ConnectionQuality from "./modules/connectivity/ConnectionQuality";
  24. /**
  25. * Creates a JitsiConference object with the given name and properties.
  26. * Note: this constructor is not a part of the public API (objects should be
  27. * created using JitsiConnection.createConference).
  28. * @param options.config properties / settings related to the conference that will be created.
  29. * @param options.name the name of the conference
  30. * @param options.connection the JitsiConnection object for this JitsiConference.
  31. * @constructor
  32. */
  33. function JitsiConference(options) {
  34. if(!options.name || options.name.toLowerCase() !== options.name) {
  35. var errmsg
  36. = "Invalid conference name (no conference name passed or it "
  37. + "contains invalid characters like capital letters)!";
  38. logger.error(errmsg);
  39. throw new Error(errmsg);
  40. }
  41. this.eventEmitter = new EventEmitter();
  42. this.settings = new Settings();
  43. this.options = options;
  44. this.eventManager = new JitsiConferenceEventManager(this);
  45. this._init(options);
  46. this.componentsVersions = new ComponentsVersions(this);
  47. this.participants = {};
  48. this.lastDominantSpeaker = null;
  49. this.dtmfManager = null;
  50. this.somebodySupportsDTMF = false;
  51. this.authEnabled = false;
  52. this.authIdentity;
  53. this.startAudioMuted = false;
  54. this.startVideoMuted = false;
  55. this.startMutedPolicy = {audio: false, video: false};
  56. this.availableDevices = {
  57. audio: undefined,
  58. video: undefined
  59. };
  60. this.isMutedByFocus = false;
  61. // Flag indicates if the 'onCallEnded' method was ever called on this
  62. // instance. Used to log extra analytics event for debugging purpose.
  63. // We need to know if the potential issue happened before or after
  64. // the restart.
  65. this.wasStopped = false;
  66. /**
  67. * The object which monitors local and remote connection statistics (e.g.
  68. * sending bitrate) and calculates a number which represents the connection
  69. * quality.
  70. */
  71. this.connectionQuality
  72. = new ConnectionQuality(this, this.eventEmitter, options);
  73. /**
  74. * Indicates whether the connection is interrupted or not.
  75. */
  76. this.connectionIsInterrupted = false;
  77. }
  78. /**
  79. * Initializes the conference object properties
  80. * @param options {object}
  81. * @param connection {JitsiConnection} overrides this.connection
  82. */
  83. JitsiConference.prototype._init = function (options) {
  84. if(!options)
  85. options = {};
  86. // Override connection and xmpp properties (Usefull if the connection
  87. // reloaded)
  88. if(options.connection) {
  89. this.connection = options.connection;
  90. this.xmpp = this.connection.xmpp;
  91. // Setup XMPP events only if we have new connection object.
  92. this.eventManager.setupXMPPListeners();
  93. }
  94. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  95. this.settings);
  96. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  97. if(!this.rtc) {
  98. this.rtc = new RTC(this, options);
  99. this.eventManager.setupRTCListeners();
  100. }
  101. this.participantConnectionStatus
  102. = new ParticipantConnectionStatus(
  103. this.rtc, this,
  104. options.config.peerDisconnectedThroughRtcTimeout);
  105. this.participantConnectionStatus.init();
  106. if(!this.statistics) {
  107. this.statistics = new Statistics(this.xmpp, {
  108. callStatsID: this.options.config.callStatsID,
  109. callStatsSecret: this.options.config.callStatsSecret,
  110. callStatsConfIDNamespace:
  111. this.options.config.callStatsConfIDNamespace || window.location.hostname,
  112. callStatsCustomScriptUrl:
  113. this.options.config.callStatsCustomScriptUrl,
  114. roomName: this.options.name
  115. });
  116. }
  117. this.eventManager.setupChatRoomListeners();
  118. // Always add listeners because on reload we are executing leave and the
  119. // listeners are removed from statistics module.
  120. this.eventManager.setupStatisticsListeners();
  121. if (this.options.config.enableTalkWhileMuted) {
  122. new TalkMutedDetection(this, () => {
  123. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED);
  124. });
  125. }
  126. };
  127. /**
  128. * Joins the conference.
  129. * @param password {string} the password
  130. */
  131. JitsiConference.prototype.join = function (password) {
  132. if(this.room)
  133. this.room.join(password);
  134. };
  135. /**
  136. * Check if joined to the conference.
  137. */
  138. JitsiConference.prototype.isJoined = function () {
  139. return this.room && this.room.joined;
  140. };
  141. /**
  142. * Leaves the conference.
  143. * @returns {Promise}
  144. */
  145. JitsiConference.prototype.leave = function () {
  146. if (this.participantConnectionStatus) {
  147. this.participantConnectionStatus.dispose();
  148. this.participantConnectionStatus = null;
  149. }
  150. this.getLocalTracks().forEach(track => this.onTrackRemoved(track));
  151. this.rtc.closeAllDataChannels();
  152. if(this.statistics)
  153. this.statistics.dispose();
  154. // leave the conference
  155. if (this.room) {
  156. let room = this.room;
  157. this.room = null;
  158. return room.leave().catch(() => {
  159. // remove all participants because currently the conference won't
  160. // be usable anyway. This is done on success automatically by the
  161. // ChatRoom instance.
  162. this.getParticipants().forEach(
  163. participant => this.onMemberLeft(participant.getJid()));
  164. });
  165. }
  166. // If this.room == null we are calling second time leave().
  167. return Promise.reject(
  168. new Error("The conference is has been already left"));
  169. };
  170. /**
  171. * Returns name of this conference.
  172. */
  173. JitsiConference.prototype.getName = function () {
  174. return this.options.name;
  175. };
  176. /**
  177. * Check if authentication is enabled for this conference.
  178. */
  179. JitsiConference.prototype.isAuthEnabled = function () {
  180. return this.authEnabled;
  181. };
  182. /**
  183. * Check if user is logged in.
  184. */
  185. JitsiConference.prototype.isLoggedIn = function () {
  186. return !!this.authIdentity;
  187. };
  188. /**
  189. * Get authorized login.
  190. */
  191. JitsiConference.prototype.getAuthLogin = function () {
  192. return this.authIdentity;
  193. };
  194. /**
  195. * Check if external authentication is enabled for this conference.
  196. */
  197. JitsiConference.prototype.isExternalAuthEnabled = function () {
  198. return this.room && this.room.moderator.isExternalAuthEnabled();
  199. };
  200. /**
  201. * Get url for external authentication.
  202. * @param {boolean} [urlForPopup] if true then return url for login popup,
  203. * else url of login page.
  204. * @returns {Promise}
  205. */
  206. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  207. return new Promise(function (resolve, reject) {
  208. if (!this.isExternalAuthEnabled()) {
  209. reject();
  210. return;
  211. }
  212. if (urlForPopup) {
  213. this.room.moderator.getPopupLoginUrl(resolve, reject);
  214. } else {
  215. this.room.moderator.getLoginUrl(resolve, reject);
  216. }
  217. }.bind(this));
  218. };
  219. /**
  220. * Returns the local tracks of the given media type, or all local tracks if no
  221. * specific type is given.
  222. * @param mediaType {MediaType} Optional media type (audio or video).
  223. */
  224. JitsiConference.prototype.getLocalTracks = function (mediaType) {
  225. let tracks = [];
  226. if (this.rtc) {
  227. tracks = this.rtc.localTracks.slice();
  228. }
  229. if (mediaType !== undefined) {
  230. tracks = tracks.filter(
  231. (track) => {
  232. return track && track.getType && track.getType() === mediaType;
  233. });
  234. }
  235. return tracks;
  236. };
  237. /**
  238. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  239. * in JitsiConferenceEvents.
  240. * @param eventId the event ID.
  241. * @param handler handler for the event.
  242. *
  243. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  244. */
  245. JitsiConference.prototype.on = function (eventId, handler) {
  246. if(this.eventEmitter)
  247. this.eventEmitter.on(eventId, handler);
  248. };
  249. /**
  250. * Removes event listener
  251. * @param eventId the event ID.
  252. * @param [handler] optional, the specific handler to unbind
  253. *
  254. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  255. */
  256. JitsiConference.prototype.off = function (eventId, handler) {
  257. if(this.eventEmitter)
  258. this.eventEmitter.removeListener(eventId, handler);
  259. };
  260. // Common aliases for event emitter
  261. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  262. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  263. /**
  264. * Receives notifications from other participants about commands / custom events
  265. * (sent by sendCommand or sendCommandOnce methods).
  266. * @param command {String} the name of the command
  267. * @param handler {Function} handler for the command
  268. */
  269. JitsiConference.prototype.addCommandListener = function (command, handler) {
  270. if(this.room)
  271. this.room.addPresenceListener(command, handler);
  272. };
  273. /**
  274. * Removes command listener
  275. * @param command {String} the name of the command
  276. */
  277. JitsiConference.prototype.removeCommandListener = function (command) {
  278. if(this.room)
  279. this.room.removePresenceListener(command);
  280. };
  281. /**
  282. * Sends text message to the other participants in the conference
  283. * @param message the text message.
  284. */
  285. JitsiConference.prototype.sendTextMessage = function (message) {
  286. if(this.room)
  287. this.room.sendMessage(message);
  288. };
  289. /**
  290. * Send presence command.
  291. * @param name {String} the name of the command.
  292. * @param values {Object} with keys and values that will be sent.
  293. **/
  294. JitsiConference.prototype.sendCommand = function (name, values) {
  295. if(this.room) {
  296. this.room.addToPresence(name, values);
  297. this.room.sendPresence();
  298. }
  299. };
  300. /**
  301. * Send presence command one time.
  302. * @param name {String} the name of the command.
  303. * @param values {Object} with keys and values that will be sent.
  304. **/
  305. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  306. this.sendCommand(name, values);
  307. this.removeCommand(name);
  308. };
  309. /**
  310. * Removes presence command.
  311. * @param name {String} the name of the command.
  312. **/
  313. JitsiConference.prototype.removeCommand = function (name) {
  314. if(this.room)
  315. this.room.removeFromPresence(name);
  316. };
  317. /**
  318. * Sets the display name for this conference.
  319. * @param name the display name to set
  320. */
  321. JitsiConference.prototype.setDisplayName = function(name) {
  322. if(this.room){
  323. // remove previously set nickname
  324. this.room.removeFromPresence("nick");
  325. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  326. this.room.sendPresence();
  327. }
  328. };
  329. /**
  330. * Set new subject for this conference. (available only for moderator)
  331. * @param {string} subject new subject
  332. */
  333. JitsiConference.prototype.setSubject = function (subject) {
  334. if (this.room && this.isModerator()) {
  335. this.room.setSubject(subject);
  336. }
  337. };
  338. /**
  339. * Get a transcriber object for all current participants in this conference
  340. * @return {Transcriber} the transcriber object
  341. */
  342. JitsiConference.prototype.getTranscriber = function(){
  343. if(this.transcriber === undefined){
  344. this.transcriber = new Transcriber();
  345. //add all existing local audio tracks to the transcriber
  346. this.rtc.localTracks.forEach(function (localTrack) {
  347. if(localTrack.isAudioTrack()){
  348. this.transcriber.addTrack(localTrack);
  349. }
  350. }.bind(this));
  351. //and all remote audio tracks
  352. this.rtc.remoteTracks.forEach(function (remoteTrack){
  353. if(remoteTrack.isAudioTrack()){
  354. this.transcriber.addTrack(remoteTrack);
  355. }
  356. }.bind(this));
  357. }
  358. return this.transcriber;
  359. };
  360. /**
  361. * Adds JitsiLocalTrack object to the conference.
  362. * @param track the JitsiLocalTrack object.
  363. * @returns {Promise<JitsiLocalTrack>}
  364. * @throws {Error} if the specified track is a video track and there is already
  365. * another video track in the conference.
  366. */
  367. JitsiConference.prototype.addTrack = function (track) {
  368. if (track.disposed) {
  369. return Promise.reject(
  370. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  371. }
  372. if (track.isVideoTrack()) {
  373. // Ensure there's exactly 1 local video track in the conference.
  374. var localVideoTrack = this.rtc.getLocalVideoTrack();
  375. if (localVideoTrack) {
  376. // Don't be excessively harsh and severe if the API client happens
  377. // to attempt to add the same local video track twice.
  378. if (track === localVideoTrack) {
  379. return Promise.resolve(track);
  380. } else {
  381. return Promise.reject(new Error(
  382. "cannot add second video track to the conference"));
  383. }
  384. }
  385. }
  386. track.ssrcHandler = function (conference, ssrcMap) {
  387. if(ssrcMap[this.getMSID()]){
  388. this._setSSRC(ssrcMap[this.getMSID()]);
  389. conference.room.removeListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  390. this.ssrcHandler);
  391. }
  392. }.bind(track, this);
  393. this.room.addListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  394. track.ssrcHandler);
  395. if(track.isAudioTrack() || (track.isVideoTrack() &&
  396. track.videoType !== VideoType.DESKTOP)) {
  397. // Report active device to statistics
  398. var devices = RTC.getCurrentlyAvailableMediaDevices();
  399. var device = devices.find(function (d) {
  400. return d.kind === track.getTrack().kind + 'input'
  401. && d.label === track.getTrack().label;
  402. });
  403. if(device)
  404. Statistics.sendActiveDeviceListEvent(
  405. RTC.getEventDataForActiveDevice(device));
  406. }
  407. return new Promise(function (resolve, reject) {
  408. this.room.addStream(track.getOriginalStream(), function () {
  409. if (track.isVideoTrack()) {
  410. this.removeCommand("videoType");
  411. this.sendCommand("videoType", {
  412. value: track.videoType,
  413. attributes: {
  414. xmlns: 'http://jitsi.org/jitmeet/video'
  415. }
  416. });
  417. }
  418. this.rtc.addLocalTrack(track);
  419. if (track.startMuted) {
  420. track.mute();
  421. }
  422. // ensure that we're sharing proper "is muted" state
  423. if (track.isAudioTrack()) {
  424. this.room.setAudioMute(track.isMuted());
  425. } else {
  426. this.room.setVideoMute(track.isMuted());
  427. }
  428. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  429. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  430. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  431. track.muteHandler);
  432. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  433. track.audioLevelHandler);
  434. track._setConference(this);
  435. // send event for starting screen sharing
  436. // FIXME: we assume we have only one screen sharing track
  437. // if we change this we need to fix this check
  438. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP)
  439. this.statistics.sendScreenSharingEvent(true);
  440. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  441. resolve(track);
  442. }.bind(this), function (error) {
  443. reject(error);
  444. });
  445. }.bind(this));
  446. };
  447. /**
  448. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  449. * @param audioLevel the audio level
  450. */
  451. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  452. this.eventEmitter.emit(
  453. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  454. this.myUserId(), audioLevel);
  455. };
  456. /**
  457. * Fires TRACK_MUTE_CHANGED change conference event.
  458. * @param track the JitsiTrack object related to the event.
  459. */
  460. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  461. // check if track was muted by focus and now is unmuted by user
  462. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  463. this.isMutedByFocus = false;
  464. // unmute local user on server
  465. this.room.muteParticipant(this.room.myroomjid, false);
  466. }
  467. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  468. };
  469. /**
  470. * Clear JitsiLocalTrack properties and listeners.
  471. * @param track the JitsiLocalTrack object.
  472. */
  473. JitsiConference.prototype.onTrackRemoved = function (track) {
  474. track._setSSRC(null);
  475. track._setConference(null);
  476. this.rtc.removeLocalTrack(track);
  477. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  478. track.muteHandler);
  479. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  480. track.audioLevelHandler);
  481. this.room.removeListener(XMPPEvents.SENDRECV_STREAMS_CHANGED,
  482. track.ssrcHandler);
  483. // send event for stopping screen sharing
  484. // FIXME: we assume we have only one screen sharing track
  485. // if we change this we need to fix this check
  486. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP)
  487. this.statistics.sendScreenSharingEvent(false);
  488. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  489. };
  490. /**
  491. * Removes JitsiLocalTrack object to the conference.
  492. * @param track the JitsiLocalTrack object.
  493. * @returns {Promise}
  494. */
  495. JitsiConference.prototype.removeTrack = function (track) {
  496. if (track.disposed) {
  497. return Promise.reject(
  498. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  499. }
  500. if(!this.room){
  501. if(this.rtc) {
  502. this.onTrackRemoved(track);
  503. }
  504. return Promise.resolve();
  505. }
  506. return new Promise(function (resolve, reject) {
  507. this.room.removeStream(track.getOriginalStream(), function(){
  508. this.onTrackRemoved(track);
  509. resolve();
  510. }.bind(this), function (error) {
  511. reject(error);
  512. }, {
  513. mtype: track.getType(),
  514. type: "remove",
  515. ssrc: track.ssrc});
  516. }.bind(this));
  517. };
  518. /**
  519. * Get role of the local user.
  520. * @returns {string} user role: 'moderator' or 'none'
  521. */
  522. JitsiConference.prototype.getRole = function () {
  523. return this.room.role;
  524. };
  525. /**
  526. * Check if local user is moderator.
  527. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  528. * we're no longer in the conference room then <tt>null</tt> is returned.
  529. */
  530. JitsiConference.prototype.isModerator = function () {
  531. return this.room ? this.room.isModerator() : null;
  532. };
  533. /**
  534. * Set password for the room.
  535. * @param {string} password new password for the room.
  536. * @returns {Promise}
  537. */
  538. JitsiConference.prototype.lock = function (password) {
  539. if (!this.isModerator()) {
  540. return Promise.reject();
  541. }
  542. var conference = this;
  543. return new Promise(function (resolve, reject) {
  544. conference.room.lockRoom(password || "", function () {
  545. resolve();
  546. }, function (err) {
  547. reject(err);
  548. }, function () {
  549. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  550. });
  551. });
  552. };
  553. /**
  554. * Remove password from the room.
  555. * @returns {Promise}
  556. */
  557. JitsiConference.prototype.unlock = function () {
  558. return this.lock();
  559. };
  560. /**
  561. * Elects the participant with the given id to be the selected participant in
  562. * order to receive higher video quality (if simulcast is enabled).
  563. * Or cache it if channel is not created and send it once channel is available.
  564. * @param participantId the identifier of the participant
  565. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  566. */
  567. JitsiConference.prototype.selectParticipant = function(participantId) {
  568. this.rtc.selectEndpoint(participantId);
  569. };
  570. /**
  571. * Elects the participant with the given id to be the pinned participant in
  572. * order to always receive video for this participant (even when last n is
  573. * enabled).
  574. * @param participantId the identifier of the participant
  575. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  576. */
  577. JitsiConference.prototype.pinParticipant = function(participantId) {
  578. this.rtc.pinEndpoint(participantId);
  579. };
  580. /**
  581. * @return Array<JitsiParticipant> an array of all participants in this
  582. * conference.
  583. */
  584. JitsiConference.prototype.getParticipants = function() {
  585. return Object.keys(this.participants).map(function (key) {
  586. return this.participants[key];
  587. }, this);
  588. };
  589. /**
  590. * Returns the number of participants in the conference, including the local
  591. * participant.
  592. * @param countHidden {boolean} Whether or not to include hidden participants
  593. * in the count. Default: false.
  594. **/
  595. JitsiConference.prototype.getParticipantCount
  596. = function(countHidden = false) {
  597. let participants = this.getParticipants();
  598. if (!countHidden) {
  599. participants = participants.filter(p => !p.isHidden());
  600. }
  601. // Add one for the local participant.
  602. return participants.length + 1;
  603. };
  604. /**
  605. * @returns {JitsiParticipant} the participant in this conference with the
  606. * specified id (or undefined if there isn't one).
  607. * @param id the id of the participant.
  608. */
  609. JitsiConference.prototype.getParticipantById = function(id) {
  610. return this.participants[id];
  611. };
  612. /**
  613. * Kick participant from this conference.
  614. * @param {string} id id of the participant to kick
  615. */
  616. JitsiConference.prototype.kickParticipant = function (id) {
  617. var participant = this.getParticipantById(id);
  618. if (!participant) {
  619. return;
  620. }
  621. this.room.kick(participant.getJid());
  622. };
  623. /**
  624. * Mutes a participant.
  625. * @param {string} id The id of the participant to mute.
  626. */
  627. JitsiConference.prototype.muteParticipant = function (id) {
  628. var participant = this.getParticipantById(id);
  629. if (!participant) {
  630. return;
  631. }
  632. this.room.muteParticipant(participant.getJid(), true);
  633. };
  634. /**
  635. * Notifies this JitsiConference that a new member has joined its chat room.
  636. *
  637. * FIXME This should NOT be exposed!
  638. *
  639. * @param jid the jid of the participant in the MUC
  640. * @param nick the display name of the participant
  641. * @param role the role of the participant in the MUC
  642. * @param isHidden indicates if this is a hidden participant (system
  643. * participant for example a recorder).
  644. */
  645. JitsiConference.prototype.onMemberJoined
  646. = function (jid, nick, role, isHidden) {
  647. var id = Strophe.getResourceFromJid(jid);
  648. if (id === 'focus' || this.myUserId() === id) {
  649. return;
  650. }
  651. var participant = new JitsiParticipant(jid, this, nick, isHidden);
  652. participant._role = role;
  653. this.participants[id] = participant;
  654. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  655. // XXX Since disco is checked in multiple places (e.g.
  656. // modules/xmpp/strophe.jingle.js, modules/xmpp/strophe.rayo.js), check it
  657. // here as well.
  658. var disco = this.xmpp.connection.disco;
  659. if (disco) {
  660. disco.info(
  661. jid, "node", function(iq) {
  662. participant._supportsDTMF = $(iq).find(
  663. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  664. this.updateDTMFSupport();
  665. }.bind(this)
  666. );
  667. } else {
  668. // FIXME Should participant._supportsDTMF be assigned false here (and
  669. // this.updateDTMFSupport invoked)?
  670. }
  671. };
  672. JitsiConference.prototype.onMemberLeft = function (jid) {
  673. var id = Strophe.getResourceFromJid(jid);
  674. if (id === 'focus' || this.myUserId() === id) {
  675. return;
  676. }
  677. var participant = this.participants[id];
  678. delete this.participants[id];
  679. var removedTracks = this.rtc.removeRemoteTracks(id);
  680. removedTracks.forEach(function (track) {
  681. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  682. }.bind(this));
  683. // there can be no participant in case the member that left is focus
  684. if (participant)
  685. this.eventEmitter.emit(
  686. JitsiConferenceEvents.USER_LEFT, id, participant);
  687. };
  688. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  689. var id = Strophe.getResourceFromJid(jid);
  690. var participant = this.getParticipantById(id);
  691. if (!participant) {
  692. return;
  693. }
  694. participant._role = role;
  695. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  696. };
  697. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  698. var id = Strophe.getResourceFromJid(jid);
  699. var participant = this.getParticipantById(id);
  700. if (!participant) {
  701. return;
  702. }
  703. if (participant._displayName === displayName)
  704. return;
  705. participant._displayName = displayName;
  706. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  707. };
  708. /**
  709. * Notifies this JitsiConference that a JitsiRemoteTrack was added (into the
  710. * ChatRoom of this JitsiConference).
  711. *
  712. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  713. * JitsiConference
  714. */
  715. JitsiConference.prototype.onTrackAdded = function (track) {
  716. var id = track.getParticipantId();
  717. var participant = this.getParticipantById(id);
  718. if (!participant) {
  719. return;
  720. }
  721. // Add track to JitsiParticipant.
  722. participant._tracks.push(track);
  723. if(this.transcriber){
  724. this.transcriber.addTrack(track);
  725. }
  726. var emitter = this.eventEmitter;
  727. track.addEventListener(
  728. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  729. function () {
  730. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  731. }
  732. );
  733. track.addEventListener(
  734. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  735. function (audioLevel) {
  736. emitter.emit(
  737. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  738. id,
  739. audioLevel);
  740. }
  741. );
  742. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  743. };
  744. /**
  745. * Handles incoming call event.
  746. */
  747. JitsiConference.prototype.onIncomingCall =
  748. function (jingleSession, jingleOffer, now) {
  749. if (!this.room.isFocus(jingleSession.peerjid)) {
  750. // Error cause this should never happen unless something is wrong!
  751. var errmsg = "Rejecting session-initiate from non-focus user: "
  752. + jingleSession.peerjid;
  753. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  754. logger.error(errmsg);
  755. // Terminate the jingle session with a reason
  756. jingleSession.terminate(
  757. 'security-error', 'Only focus can start new sessions',
  758. null /* success callback => we don't care */,
  759. function (error) {
  760. logger.warn(
  761. "An error occurred while trying to terminate"
  762. + " invalid Jingle session", error);
  763. });
  764. return;
  765. }
  766. // Accept incoming call
  767. this.room.setJingleSession(jingleSession);
  768. this.room.connectionTimes["session.initiate"] = now;
  769. // Log "session.restart"
  770. if (this.wasStopped) {
  771. Statistics.sendEventToAll("session.restart");
  772. }
  773. // add info whether call is cross-region
  774. var crossRegion = null;
  775. if (window.jitsiRegionInfo) {
  776. crossRegion = window.jitsiRegionInfo["CrossRegion"];
  777. }
  778. Statistics.analytics.sendEvent(
  779. "session.initiate",
  780. {
  781. value: now - this.room.connectionTimes["muc.joined"],
  782. label: crossRegion
  783. });
  784. try {
  785. jingleSession.initialize(false /* initiator */,this.room);
  786. } catch (error) {
  787. GlobalOnErrorHandler.callErrorHandler(error);
  788. }
  789. this.rtc.onIncommingCall(jingleSession);
  790. // Add local Tracks to the ChatRoom
  791. this.rtc.localTracks.forEach(function(localTrack) {
  792. var ssrcInfo = null;
  793. if(localTrack.isVideoTrack() && localTrack.isMuted()) {
  794. /**
  795. * Handles issues when the stream is added before the peerconnection
  796. * is created. The peerconnection is created when second participant
  797. * enters the call. In that use case the track doesn't have
  798. * information about it's ssrcs and no jingle packets are sent. That
  799. * can cause inconsistent behavior later.
  800. *
  801. * For example:
  802. * If we mute the stream and than second participant enter it's
  803. * remote SDP won't include that track. On unmute we are not sending
  804. * any jingle packets which will brake the unmute.
  805. *
  806. * In order to solve issues like the above one here we have to
  807. * generate the ssrc information for the track .
  808. */
  809. localTrack._setSSRC(
  810. this.room.generateNewStreamSSRCInfo());
  811. ssrcInfo = {
  812. mtype: localTrack.getType(),
  813. type: "addMuted",
  814. ssrc: localTrack.ssrc,
  815. msid: localTrack.initialMSID
  816. };
  817. }
  818. try {
  819. this.room.addStream(
  820. localTrack.getOriginalStream(), function () {}, function () {},
  821. ssrcInfo, true);
  822. } catch(e) {
  823. GlobalOnErrorHandler.callErrorHandler(e);
  824. logger.error(e);
  825. }
  826. }.bind(this));
  827. jingleSession.acceptOffer(jingleOffer, null,
  828. function (error) {
  829. GlobalOnErrorHandler.callErrorHandler(error);
  830. logger.error(
  831. "Failed to accept incoming Jingle session", error);
  832. }
  833. );
  834. // Start callstats as soon as peerconnection is initialized,
  835. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  836. // happen in case if user doesn't have or denied permission to
  837. // both camera and microphone.
  838. this.statistics.startCallStats(jingleSession, this.settings);
  839. this.statistics.startRemoteStats(jingleSession.peerconnection);
  840. };
  841. /**
  842. * Handles the call ended event.
  843. * @param {JingleSessionPC} JingleSession the jingle session which has been
  844. * terminated.
  845. * @param {String} reasonCondition the Jingle reason condition.
  846. * @param {String|null} reasonText human readable reason text which may provide
  847. * more details about why the call has been terminated.
  848. */
  849. JitsiConference.prototype.onCallEnded
  850. = function (JingleSession, reasonCondition, reasonText) {
  851. logger.info("Call ended: " + reasonCondition + " - " + reasonText);
  852. this.wasStopped = true;
  853. // Send session.terminate event
  854. Statistics.sendEventToAll("session.terminate");
  855. // Stop the stats
  856. if (this.statistics) {
  857. this.statistics.stopRemoteStats();
  858. this.statistics.stopCallStats();
  859. }
  860. // Current JingleSession is invalid so set it to null on the room
  861. this.room.setJingleSession(null);
  862. // Let the RTC service do any cleanups
  863. this.rtc.onCallEnded();
  864. // PeerConnection has been closed which means that SSRCs stored in
  865. // JitsiLocalTrack will not match those assigned by the old PeerConnection
  866. // and SSRC replacement logic will not work as expected.
  867. // We want to re-register 'ssrcHandler' of our local tracks, so that they
  868. // will learn what their SSRC from the new PeerConnection which will be
  869. // created on incoming call event.
  870. var self = this;
  871. this.rtc.localTracks.forEach(function(localTrack) {
  872. // Reset SSRC as it will no longer be valid
  873. localTrack._setSSRC(null);
  874. // Bind the handler to fetch new SSRC, it will un register itself once
  875. // it reads the values
  876. self.room.addListener(
  877. XMPPEvents.SENDRECV_STREAMS_CHANGED, localTrack.ssrcHandler);
  878. });
  879. };
  880. JitsiConference.prototype.updateDTMFSupport = function () {
  881. var somebodySupportsDTMF = false;
  882. var participants = this.getParticipants();
  883. // check if at least 1 participant supports DTMF
  884. for (var i = 0; i < participants.length; i += 1) {
  885. if (participants[i].supportsDTMF()) {
  886. somebodySupportsDTMF = true;
  887. break;
  888. }
  889. }
  890. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  891. this.somebodySupportsDTMF = somebodySupportsDTMF;
  892. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  893. }
  894. };
  895. /**
  896. * Allows to check if there is at least one user in the conference
  897. * that supports DTMF.
  898. * @returns {boolean} true if somebody supports DTMF, false otherwise
  899. */
  900. JitsiConference.prototype.isDTMFSupported = function () {
  901. return this.somebodySupportsDTMF;
  902. };
  903. /**
  904. * Returns the local user's ID
  905. * @return {string} local user's ID
  906. */
  907. JitsiConference.prototype.myUserId = function () {
  908. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  909. };
  910. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  911. if (!this.dtmfManager) {
  912. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  913. if (!connection) {
  914. logger.warn("cannot sendTones: no conneciton");
  915. return;
  916. }
  917. var tracks = this.getLocalTracks().filter(function (track) {
  918. return track.isAudioTrack();
  919. });
  920. if (!tracks.length) {
  921. logger.warn("cannot sendTones: no local audio stream");
  922. return;
  923. }
  924. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  925. }
  926. this.dtmfManager.sendTones(tones, duration, pause);
  927. };
  928. /**
  929. * Returns true if the recording is supproted and false if not.
  930. */
  931. JitsiConference.prototype.isRecordingSupported = function () {
  932. if(this.room)
  933. return this.room.isRecordingSupported();
  934. return false;
  935. };
  936. /**
  937. * Returns null if the recording is not supported, "on" if the recording started
  938. * and "off" if the recording is not started.
  939. */
  940. JitsiConference.prototype.getRecordingState = function () {
  941. return (this.room) ? this.room.getRecordingState() : undefined;
  942. };
  943. /**
  944. * Returns the url of the recorded video.
  945. */
  946. JitsiConference.prototype.getRecordingURL = function () {
  947. return (this.room) ? this.room.getRecordingURL() : null;
  948. };
  949. /**
  950. * Starts/stops the recording
  951. */
  952. JitsiConference.prototype.toggleRecording = function (options) {
  953. if(this.room)
  954. return this.room.toggleRecording(options, function (status, error) {
  955. this.eventEmitter.emit(
  956. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  957. }.bind(this));
  958. this.eventEmitter.emit(
  959. JitsiConferenceEvents.RECORDER_STATE_CHANGED, "error",
  960. new Error("The conference is not created yet!"));
  961. };
  962. /**
  963. * Returns true if the SIP calls are supported and false otherwise
  964. */
  965. JitsiConference.prototype.isSIPCallingSupported = function () {
  966. if(this.room)
  967. return this.room.isSIPCallingSupported();
  968. return false;
  969. };
  970. /**
  971. * Dials a number.
  972. * @param number the number
  973. */
  974. JitsiConference.prototype.dial = function (number) {
  975. if(this.room)
  976. return this.room.dial(number);
  977. return new Promise(function(resolve, reject){
  978. reject(new Error("The conference is not created yet!"));});
  979. };
  980. /**
  981. * Hangup an existing call
  982. */
  983. JitsiConference.prototype.hangup = function () {
  984. if(this.room)
  985. return this.room.hangup();
  986. return new Promise(function(resolve, reject){
  987. reject(new Error("The conference is not created yet!"));});
  988. };
  989. /**
  990. * Returns the phone number for joining the conference.
  991. */
  992. JitsiConference.prototype.getPhoneNumber = function () {
  993. if(this.room)
  994. return this.room.getPhoneNumber();
  995. return null;
  996. };
  997. /**
  998. * Returns the pin for joining the conference with phone.
  999. */
  1000. JitsiConference.prototype.getPhonePin = function () {
  1001. if(this.room)
  1002. return this.room.getPhonePin();
  1003. return null;
  1004. };
  1005. /**
  1006. * Returns the connection state for the current room. Its ice connection state
  1007. * for its session.
  1008. */
  1009. JitsiConference.prototype.getConnectionState = function () {
  1010. if(this.room)
  1011. return this.room.getConnectionState();
  1012. return null;
  1013. };
  1014. /**
  1015. * Make all new participants mute their audio/video on join.
  1016. * @param policy {Object} object with 2 boolean properties for video and audio:
  1017. * @param {boolean} audio if audio should be muted.
  1018. * @param {boolean} video if video should be muted.
  1019. */
  1020. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  1021. if (!this.isModerator()) {
  1022. return;
  1023. }
  1024. this.startMutedPolicy = policy;
  1025. this.room.removeFromPresence("startmuted");
  1026. this.room.addToPresence("startmuted", {
  1027. attributes: {
  1028. audio: policy.audio,
  1029. video: policy.video,
  1030. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1031. }
  1032. });
  1033. this.room.sendPresence();
  1034. };
  1035. /**
  1036. * Returns current start muted policy
  1037. * @returns {Object} with 2 proprties - audio and video.
  1038. */
  1039. JitsiConference.prototype.getStartMutedPolicy = function () {
  1040. return this.startMutedPolicy;
  1041. };
  1042. /**
  1043. * Check if audio is muted on join.
  1044. */
  1045. JitsiConference.prototype.isStartAudioMuted = function () {
  1046. return this.startAudioMuted;
  1047. };
  1048. /**
  1049. * Check if video is muted on join.
  1050. */
  1051. JitsiConference.prototype.isStartVideoMuted = function () {
  1052. return this.startVideoMuted;
  1053. };
  1054. /**
  1055. * Get object with internal logs.
  1056. */
  1057. JitsiConference.prototype.getLogs = function () {
  1058. var data = this.xmpp.getJingleLog();
  1059. var metadata = {};
  1060. metadata.time = new Date();
  1061. metadata.url = window.location.href;
  1062. metadata.ua = navigator.userAgent;
  1063. var log = this.xmpp.getXmppLog();
  1064. if (log) {
  1065. metadata.xmpp = log;
  1066. }
  1067. data.metadata = metadata;
  1068. return data;
  1069. };
  1070. /**
  1071. * Returns measured connectionTimes.
  1072. */
  1073. JitsiConference.prototype.getConnectionTimes = function () {
  1074. return this.room.connectionTimes;
  1075. };
  1076. /**
  1077. * Sets a property for the local participant.
  1078. */
  1079. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1080. this.sendCommand("jitsi_participant_" + name, {value: value});
  1081. };
  1082. /**
  1083. * Sends the given feedback through CallStats if enabled.
  1084. *
  1085. * @param overallFeedback an integer between 1 and 5 indicating the
  1086. * user feedback
  1087. * @param detailedFeedback detailed feedback from the user. Not yet used
  1088. */
  1089. JitsiConference.prototype.sendFeedback =
  1090. function(overallFeedback, detailedFeedback){
  1091. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1092. };
  1093. /**
  1094. * Returns true if the callstats integration is enabled, otherwise returns
  1095. * false.
  1096. *
  1097. * @returns true if the callstats integration is enabled, otherwise returns
  1098. * false.
  1099. */
  1100. JitsiConference.prototype.isCallstatsEnabled = function () {
  1101. return this.statistics.isCallstatsEnabled();
  1102. };
  1103. /**
  1104. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1105. * from statistics module)
  1106. * @param track the track
  1107. * @param container the container
  1108. */
  1109. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1110. var ssrc = track.getSSRC();
  1111. if (!container.id || !ssrc) {
  1112. return;
  1113. }
  1114. this.statistics.associateStreamWithVideoTag(
  1115. ssrc, track.isLocal(), track.getUsageLabel(), container.id);
  1116. };
  1117. /**
  1118. * Logs an "application log" message.
  1119. * @param message {string} The message to log. Note that while this can be a
  1120. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1121. * log valid JSON strings, with an "id" field used for distinguishing between
  1122. * message types. E.g.: {id: "recorder_status", status: "off"}
  1123. */
  1124. JitsiConference.prototype.sendApplicationLog = function(message) {
  1125. Statistics.sendLog(message);
  1126. };
  1127. /**
  1128. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1129. * focus.
  1130. * @param mucJid the full MUC address of the user to be checked.
  1131. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1132. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1133. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1134. */
  1135. JitsiConference.prototype._isFocus = function (mucJid) {
  1136. return this.room ? this.room.isFocus(mucJid) : null;
  1137. };
  1138. /**
  1139. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1140. */
  1141. JitsiConference.prototype._fireIncompatibleVersionsEvent = function () {
  1142. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1143. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1144. };
  1145. /**
  1146. * Sends message via the datachannels.
  1147. * @param to {string} the id of the endpoint that should receive the message.
  1148. * If "" the message will be sent to all participants.
  1149. * @param payload {object} the payload of the message.
  1150. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1151. */
  1152. JitsiConference.prototype.sendEndpointMessage = function (to, payload) {
  1153. this.rtc.sendDataChannelMessage(to, payload);
  1154. };
  1155. /**
  1156. * Sends broadcast message via the datachannels.
  1157. * @param payload {object} the payload of the message.
  1158. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1159. */
  1160. JitsiConference.prototype.broadcastEndpointMessage = function (payload) {
  1161. this.sendEndpointMessage("", payload);
  1162. };
  1163. JitsiConference.prototype.isConnectionInterrupted = function () {
  1164. return this.connectionIsInterrupted;
  1165. };
  1166. module.exports = JitsiConference;