Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiConference.js 40KB

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