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

JitsiConference.js 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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 {JitsiParticipant} the participant in this conference with the
  591. * specified id (or undefined if there isn't one).
  592. * @param id the id of the participant.
  593. */
  594. JitsiConference.prototype.getParticipantById = function(id) {
  595. return this.participants[id];
  596. };
  597. /**
  598. * Kick participant from this conference.
  599. * @param {string} id id of the participant to kick
  600. */
  601. JitsiConference.prototype.kickParticipant = function (id) {
  602. var participant = this.getParticipantById(id);
  603. if (!participant) {
  604. return;
  605. }
  606. this.room.kick(participant.getJid());
  607. };
  608. /**
  609. * Mutes a participant.
  610. * @param {string} id The id of the participant to mute.
  611. */
  612. JitsiConference.prototype.muteParticipant = function (id) {
  613. var participant = this.getParticipantById(id);
  614. if (!participant) {
  615. return;
  616. }
  617. this.room.muteParticipant(participant.getJid(), true);
  618. };
  619. /**
  620. * Notifies this JitsiConference that a new member has joined its chat room.
  621. *
  622. * FIXME This should NOT be exposed!
  623. *
  624. * @param jid the jid of the participant in the MUC
  625. * @param nick the display name of the participant
  626. * @param role the role of the participant in the MUC
  627. * @param isHidden indicates if this is a hidden participant (system
  628. * participant for example a recorder).
  629. */
  630. JitsiConference.prototype.onMemberJoined
  631. = function (jid, nick, role, isHidden) {
  632. var id = Strophe.getResourceFromJid(jid);
  633. if (id === 'focus' || this.myUserId() === id) {
  634. return;
  635. }
  636. var participant = new JitsiParticipant(jid, this, nick, isHidden);
  637. participant._role = role;
  638. this.participants[id] = participant;
  639. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  640. // XXX Since disco is checked in multiple places (e.g.
  641. // modules/xmpp/strophe.jingle.js, modules/xmpp/strophe.rayo.js), check it
  642. // here as well.
  643. var disco = this.xmpp.connection.disco;
  644. if (disco) {
  645. disco.info(
  646. jid, "node", function(iq) {
  647. participant._supportsDTMF = $(iq).find(
  648. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  649. this.updateDTMFSupport();
  650. }.bind(this)
  651. );
  652. } else {
  653. // FIXME Should participant._supportsDTMF be assigned false here (and
  654. // this.updateDTMFSupport invoked)?
  655. }
  656. };
  657. JitsiConference.prototype.onMemberLeft = function (jid) {
  658. var id = Strophe.getResourceFromJid(jid);
  659. if (id === 'focus' || this.myUserId() === id) {
  660. return;
  661. }
  662. var participant = this.participants[id];
  663. delete this.participants[id];
  664. var removedTracks = this.rtc.removeRemoteTracks(id);
  665. removedTracks.forEach(function (track) {
  666. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  667. }.bind(this));
  668. // there can be no participant in case the member that left is focus
  669. if (participant)
  670. this.eventEmitter.emit(
  671. JitsiConferenceEvents.USER_LEFT, id, participant);
  672. };
  673. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  674. var id = Strophe.getResourceFromJid(jid);
  675. var participant = this.getParticipantById(id);
  676. if (!participant) {
  677. return;
  678. }
  679. participant._role = role;
  680. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  681. };
  682. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  683. var id = Strophe.getResourceFromJid(jid);
  684. var participant = this.getParticipantById(id);
  685. if (!participant) {
  686. return;
  687. }
  688. if (participant._displayName === displayName)
  689. return;
  690. participant._displayName = displayName;
  691. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  692. };
  693. /**
  694. * Notifies this JitsiConference that a JitsiRemoteTrack was added (into the
  695. * ChatRoom of this JitsiConference).
  696. *
  697. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  698. * JitsiConference
  699. */
  700. JitsiConference.prototype.onTrackAdded = function (track) {
  701. var id = track.getParticipantId();
  702. var participant = this.getParticipantById(id);
  703. if (!participant) {
  704. return;
  705. }
  706. // Add track to JitsiParticipant.
  707. participant._tracks.push(track);
  708. if(this.transcriber){
  709. this.transcriber.addTrack(track);
  710. }
  711. var emitter = this.eventEmitter;
  712. track.addEventListener(
  713. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  714. function () {
  715. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  716. }
  717. );
  718. track.addEventListener(
  719. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  720. function (audioLevel) {
  721. emitter.emit(
  722. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  723. id,
  724. audioLevel);
  725. }
  726. );
  727. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  728. };
  729. /**
  730. * Handles incoming call event.
  731. */
  732. JitsiConference.prototype.onIncomingCall =
  733. function (jingleSession, jingleOffer, now) {
  734. if (!this.room.isFocus(jingleSession.peerjid)) {
  735. // Error cause this should never happen unless something is wrong!
  736. var errmsg = "Rejecting session-initiate from non-focus user: "
  737. + jingleSession.peerjid;
  738. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  739. logger.error(errmsg);
  740. // Terminate the jingle session with a reason
  741. jingleSession.terminate(
  742. 'security-error', 'Only focus can start new sessions',
  743. null /* success callback => we don't care */,
  744. function (error) {
  745. logger.warn(
  746. "An error occurred while trying to terminate"
  747. + " invalid Jingle session", error);
  748. });
  749. return;
  750. }
  751. // Accept incoming call
  752. this.room.setJingleSession(jingleSession);
  753. this.room.connectionTimes["session.initiate"] = now;
  754. // Log "session.restart"
  755. if (this.wasStopped) {
  756. Statistics.sendEventToAll("session.restart");
  757. }
  758. // add info whether call is cross-region
  759. var crossRegion = null;
  760. if (window.jitsiRegionInfo) {
  761. crossRegion = window.jitsiRegionInfo["CrossRegion"];
  762. }
  763. Statistics.analytics.sendEvent(
  764. "session.initiate",
  765. {
  766. value: now - this.room.connectionTimes["muc.joined"],
  767. label: crossRegion
  768. });
  769. try {
  770. jingleSession.initialize(false /* initiator */,this.room);
  771. } catch (error) {
  772. GlobalOnErrorHandler.callErrorHandler(error);
  773. }
  774. this.rtc.onIncommingCall(jingleSession);
  775. // Add local Tracks to the ChatRoom
  776. this.rtc.localTracks.forEach(function(localTrack) {
  777. var ssrcInfo = null;
  778. if(localTrack.isVideoTrack() && localTrack.isMuted()) {
  779. /**
  780. * Handles issues when the stream is added before the peerconnection
  781. * is created. The peerconnection is created when second participant
  782. * enters the call. In that use case the track doesn't have
  783. * information about it's ssrcs and no jingle packets are sent. That
  784. * can cause inconsistent behavior later.
  785. *
  786. * For example:
  787. * If we mute the stream and than second participant enter it's
  788. * remote SDP won't include that track. On unmute we are not sending
  789. * any jingle packets which will brake the unmute.
  790. *
  791. * In order to solve issues like the above one here we have to
  792. * generate the ssrc information for the track .
  793. */
  794. localTrack._setSSRC(
  795. this.room.generateNewStreamSSRCInfo());
  796. ssrcInfo = {
  797. mtype: localTrack.getType(),
  798. type: "addMuted",
  799. ssrc: localTrack.ssrc,
  800. msid: localTrack.initialMSID
  801. };
  802. }
  803. try {
  804. this.room.addStream(
  805. localTrack.getOriginalStream(), function () {}, function () {},
  806. ssrcInfo, true);
  807. } catch(e) {
  808. GlobalOnErrorHandler.callErrorHandler(e);
  809. logger.error(e);
  810. }
  811. }.bind(this));
  812. jingleSession.acceptOffer(jingleOffer, null,
  813. function (error) {
  814. GlobalOnErrorHandler.callErrorHandler(error);
  815. logger.error(
  816. "Failed to accept incoming Jingle session", error);
  817. }
  818. );
  819. // Start callstats as soon as peerconnection is initialized,
  820. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  821. // happen in case if user doesn't have or denied permission to
  822. // both camera and microphone.
  823. this.statistics.startCallStats(jingleSession, this.settings);
  824. this.statistics.startRemoteStats(jingleSession.peerconnection);
  825. };
  826. /**
  827. * Handles the call ended event.
  828. * @param {JingleSessionPC} JingleSession the jingle session which has been
  829. * terminated.
  830. * @param {String} reasonCondition the Jingle reason condition.
  831. * @param {String|null} reasonText human readable reason text which may provide
  832. * more details about why the call has been terminated.
  833. */
  834. JitsiConference.prototype.onCallEnded
  835. = function (JingleSession, reasonCondition, reasonText) {
  836. logger.info("Call ended: " + reasonCondition + " - " + reasonText);
  837. this.wasStopped = true;
  838. // Send session.terminate event
  839. Statistics.sendEventToAll("session.terminate");
  840. // Stop the stats
  841. if (this.statistics) {
  842. this.statistics.stopRemoteStats();
  843. this.statistics.stopCallStats();
  844. }
  845. // Current JingleSession is invalid so set it to null on the room
  846. this.room.setJingleSession(null);
  847. // Let the RTC service do any cleanups
  848. this.rtc.onCallEnded();
  849. // PeerConnection has been closed which means that SSRCs stored in
  850. // JitsiLocalTrack will not match those assigned by the old PeerConnection
  851. // and SSRC replacement logic will not work as expected.
  852. // We want to re-register 'ssrcHandler' of our local tracks, so that they
  853. // will learn what their SSRC from the new PeerConnection which will be
  854. // created on incoming call event.
  855. var self = this;
  856. this.rtc.localTracks.forEach(function(localTrack) {
  857. // Reset SSRC as it will no longer be valid
  858. localTrack._setSSRC(null);
  859. // Bind the handler to fetch new SSRC, it will un register itself once
  860. // it reads the values
  861. self.room.addListener(
  862. XMPPEvents.SENDRECV_STREAMS_CHANGED, localTrack.ssrcHandler);
  863. });
  864. };
  865. JitsiConference.prototype.updateDTMFSupport = function () {
  866. var somebodySupportsDTMF = false;
  867. var participants = this.getParticipants();
  868. // check if at least 1 participant supports DTMF
  869. for (var i = 0; i < participants.length; i += 1) {
  870. if (participants[i].supportsDTMF()) {
  871. somebodySupportsDTMF = true;
  872. break;
  873. }
  874. }
  875. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  876. this.somebodySupportsDTMF = somebodySupportsDTMF;
  877. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  878. }
  879. };
  880. /**
  881. * Allows to check if there is at least one user in the conference
  882. * that supports DTMF.
  883. * @returns {boolean} true if somebody supports DTMF, false otherwise
  884. */
  885. JitsiConference.prototype.isDTMFSupported = function () {
  886. return this.somebodySupportsDTMF;
  887. };
  888. /**
  889. * Returns the local user's ID
  890. * @return {string} local user's ID
  891. */
  892. JitsiConference.prototype.myUserId = function () {
  893. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  894. };
  895. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  896. if (!this.dtmfManager) {
  897. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  898. if (!connection) {
  899. logger.warn("cannot sendTones: no conneciton");
  900. return;
  901. }
  902. var tracks = this.getLocalTracks().filter(function (track) {
  903. return track.isAudioTrack();
  904. });
  905. if (!tracks.length) {
  906. logger.warn("cannot sendTones: no local audio stream");
  907. return;
  908. }
  909. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  910. }
  911. this.dtmfManager.sendTones(tones, duration, pause);
  912. };
  913. /**
  914. * Returns true if the recording is supproted and false if not.
  915. */
  916. JitsiConference.prototype.isRecordingSupported = function () {
  917. if(this.room)
  918. return this.room.isRecordingSupported();
  919. return false;
  920. };
  921. /**
  922. * Returns null if the recording is not supported, "on" if the recording started
  923. * and "off" if the recording is not started.
  924. */
  925. JitsiConference.prototype.getRecordingState = function () {
  926. return (this.room) ? this.room.getRecordingState() : undefined;
  927. };
  928. /**
  929. * Returns the url of the recorded video.
  930. */
  931. JitsiConference.prototype.getRecordingURL = function () {
  932. return (this.room) ? this.room.getRecordingURL() : null;
  933. };
  934. /**
  935. * Starts/stops the recording
  936. */
  937. JitsiConference.prototype.toggleRecording = function (options) {
  938. if(this.room)
  939. return this.room.toggleRecording(options, function (status, error) {
  940. this.eventEmitter.emit(
  941. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  942. }.bind(this));
  943. this.eventEmitter.emit(
  944. JitsiConferenceEvents.RECORDER_STATE_CHANGED, "error",
  945. new Error("The conference is not created yet!"));
  946. };
  947. /**
  948. * Returns true if the SIP calls are supported and false otherwise
  949. */
  950. JitsiConference.prototype.isSIPCallingSupported = function () {
  951. if(this.room)
  952. return this.room.isSIPCallingSupported();
  953. return false;
  954. };
  955. /**
  956. * Dials a number.
  957. * @param number the number
  958. */
  959. JitsiConference.prototype.dial = function (number) {
  960. if(this.room)
  961. return this.room.dial(number);
  962. return new Promise(function(resolve, reject){
  963. reject(new Error("The conference is not created yet!"));});
  964. };
  965. /**
  966. * Hangup an existing call
  967. */
  968. JitsiConference.prototype.hangup = function () {
  969. if(this.room)
  970. return this.room.hangup();
  971. return new Promise(function(resolve, reject){
  972. reject(new Error("The conference is not created yet!"));});
  973. };
  974. /**
  975. * Returns the phone number for joining the conference.
  976. */
  977. JitsiConference.prototype.getPhoneNumber = function () {
  978. if(this.room)
  979. return this.room.getPhoneNumber();
  980. return null;
  981. };
  982. /**
  983. * Returns the pin for joining the conference with phone.
  984. */
  985. JitsiConference.prototype.getPhonePin = function () {
  986. if(this.room)
  987. return this.room.getPhonePin();
  988. return null;
  989. };
  990. /**
  991. * Returns the connection state for the current room. Its ice connection state
  992. * for its session.
  993. */
  994. JitsiConference.prototype.getConnectionState = function () {
  995. if(this.room)
  996. return this.room.getConnectionState();
  997. return null;
  998. };
  999. /**
  1000. * Make all new participants mute their audio/video on join.
  1001. * @param policy {Object} object with 2 boolean properties for video and audio:
  1002. * @param {boolean} audio if audio should be muted.
  1003. * @param {boolean} video if video should be muted.
  1004. */
  1005. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  1006. if (!this.isModerator()) {
  1007. return;
  1008. }
  1009. this.startMutedPolicy = policy;
  1010. this.room.removeFromPresence("startmuted");
  1011. this.room.addToPresence("startmuted", {
  1012. attributes: {
  1013. audio: policy.audio,
  1014. video: policy.video,
  1015. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1016. }
  1017. });
  1018. this.room.sendPresence();
  1019. };
  1020. /**
  1021. * Returns current start muted policy
  1022. * @returns {Object} with 2 proprties - audio and video.
  1023. */
  1024. JitsiConference.prototype.getStartMutedPolicy = function () {
  1025. return this.startMutedPolicy;
  1026. };
  1027. /**
  1028. * Check if audio is muted on join.
  1029. */
  1030. JitsiConference.prototype.isStartAudioMuted = function () {
  1031. return this.startAudioMuted;
  1032. };
  1033. /**
  1034. * Check if video is muted on join.
  1035. */
  1036. JitsiConference.prototype.isStartVideoMuted = function () {
  1037. return this.startVideoMuted;
  1038. };
  1039. /**
  1040. * Get object with internal logs.
  1041. */
  1042. JitsiConference.prototype.getLogs = function () {
  1043. var data = this.xmpp.getJingleLog();
  1044. var metadata = {};
  1045. metadata.time = new Date();
  1046. metadata.url = window.location.href;
  1047. metadata.ua = navigator.userAgent;
  1048. var log = this.xmpp.getXmppLog();
  1049. if (log) {
  1050. metadata.xmpp = log;
  1051. }
  1052. data.metadata = metadata;
  1053. return data;
  1054. };
  1055. /**
  1056. * Returns measured connectionTimes.
  1057. */
  1058. JitsiConference.prototype.getConnectionTimes = function () {
  1059. return this.room.connectionTimes;
  1060. };
  1061. /**
  1062. * Sets a property for the local participant.
  1063. */
  1064. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1065. this.sendCommand("jitsi_participant_" + name, {value: value});
  1066. };
  1067. /**
  1068. * Sends the given feedback through CallStats if enabled.
  1069. *
  1070. * @param overallFeedback an integer between 1 and 5 indicating the
  1071. * user feedback
  1072. * @param detailedFeedback detailed feedback from the user. Not yet used
  1073. */
  1074. JitsiConference.prototype.sendFeedback =
  1075. function(overallFeedback, detailedFeedback){
  1076. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1077. };
  1078. /**
  1079. * Returns true if the callstats integration is enabled, otherwise returns
  1080. * false.
  1081. *
  1082. * @returns true if the callstats integration is enabled, otherwise returns
  1083. * false.
  1084. */
  1085. JitsiConference.prototype.isCallstatsEnabled = function () {
  1086. return this.statistics.isCallstatsEnabled();
  1087. };
  1088. /**
  1089. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1090. * from statistics module)
  1091. * @param track the track
  1092. * @param container the container
  1093. */
  1094. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1095. var ssrc = track.getSSRC();
  1096. if (!container.id || !ssrc) {
  1097. return;
  1098. }
  1099. this.statistics.associateStreamWithVideoTag(
  1100. ssrc, track.isLocal(), track.getUsageLabel(), container.id);
  1101. };
  1102. /**
  1103. * Logs an "application log" message.
  1104. * @param message {string} The message to log. Note that while this can be a
  1105. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1106. * log valid JSON strings, with an "id" field used for distinguishing between
  1107. * message types. E.g.: {id: "recorder_status", status: "off"}
  1108. */
  1109. JitsiConference.prototype.sendApplicationLog = function(message) {
  1110. Statistics.sendLog(message);
  1111. };
  1112. /**
  1113. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1114. * focus.
  1115. * @param mucJid the full MUC address of the user to be checked.
  1116. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1117. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1118. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1119. */
  1120. JitsiConference.prototype._isFocus = function (mucJid) {
  1121. return this.room ? this.room.isFocus(mucJid) : null;
  1122. };
  1123. /**
  1124. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1125. */
  1126. JitsiConference.prototype._fireIncompatibleVersionsEvent = function () {
  1127. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1128. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1129. };
  1130. /**
  1131. * Sends message via the datachannels.
  1132. * @param to {string} the id of the endpoint that should receive the message.
  1133. * If "" the message will be sent to all participants.
  1134. * @param payload {object} the payload of the message.
  1135. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1136. */
  1137. JitsiConference.prototype.sendEndpointMessage = function (to, payload) {
  1138. this.rtc.sendDataChannelMessage(to, payload);
  1139. };
  1140. /**
  1141. * Sends broadcast message via the datachannels.
  1142. * @param payload {object} the payload of the message.
  1143. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1144. */
  1145. JitsiConference.prototype.broadcastEndpointMessage = function (payload) {
  1146. this.sendEndpointMessage("", payload);
  1147. };
  1148. JitsiConference.prototype.isConnectionInterrupted = function () {
  1149. return this.connectionIsInterrupted;
  1150. };
  1151. module.exports = JitsiConference;