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

JitsiConference.js 76KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  1. /* global __filename, Strophe, Promise */
  2. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  3. import ComponentsVersions from './modules/version/ComponentsVersions';
  4. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  5. import { getLogger } from 'jitsi-meet-logger';
  6. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  7. import EventEmitter from 'events';
  8. import * as JingleSessionState from './modules/xmpp/JingleSessionState';
  9. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  10. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  11. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  12. import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
  13. import JitsiParticipant from './JitsiParticipant';
  14. import JitsiTrackError from './JitsiTrackError';
  15. import * as JitsiTrackErrors from './JitsiTrackErrors';
  16. import * as JitsiTrackEvents from './JitsiTrackEvents';
  17. import * as MediaType from './service/RTC/MediaType';
  18. import ParticipantConnectionStatusHandler
  19. from './modules/connectivity/ParticipantConnectionStatus';
  20. import RTC from './modules/RTC/RTC';
  21. import RTCBrowserType from './modules/RTC/RTCBrowserType';
  22. import * as RTCEvents from './service/RTC/RTCEvents';
  23. import Statistics from './modules/statistics/statistics';
  24. import TalkMutedDetection from './modules/TalkMutedDetection';
  25. import Transcriber from './modules/transcription/transcriber';
  26. import VideoType from './service/RTC/VideoType';
  27. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  28. import * as XMPPEvents from './service/xmpp/XMPPEvents';
  29. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  30. const logger = getLogger(__filename);
  31. /**
  32. * Creates a JitsiConference object with the given name and properties.
  33. * Note: this constructor is not a part of the public API (objects should be
  34. * created using JitsiConnection.createConference).
  35. * @param options.config properties / settings related to the conference that
  36. * will be created.
  37. * @param options.name the name of the conference
  38. * @param options.connection the JitsiConnection object for this
  39. * JitsiConference.
  40. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  41. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  42. * calculated and submitted to the analytics module.
  43. * @param {boolean} [options.config.enableP2P] when set to <tt>true</tt>
  44. * the peer to peer mode will be enabled. It means that when there are only 2
  45. * participants in the conference an attempt to make direct connection will be
  46. * made. If the connection succeeds the conference will stop sending data
  47. * through the JVB connection and will use the direct one instead.
  48. * @param {number} [options.config.backToP2PDelay=5] a delay given in seconds,
  49. * before the conference switches back to P2P, after the 3rd participant has
  50. * left the room.
  51. * @param {number} [options.config.channelLastN=-1] The requested amount of
  52. * videos are going to be delivered after the value is in effect. Set to -1 for
  53. * unlimited or all available videos.
  54. * @constructor
  55. *
  56. * FIXME Make all methods which are called from lib-internal classes
  57. * to non-public (use _). To name a few:
  58. * {@link JitsiConference.onLocalRoleChanged}
  59. * {@link JitsiConference.onUserRoleChanged}
  60. * {@link JitsiConference.onMemberLeft}
  61. * and so on...
  62. */
  63. export default function JitsiConference(options) {
  64. if (!options.name || options.name.toLowerCase() !== options.name) {
  65. const errmsg
  66. = 'Invalid conference name (no conference name passed or it '
  67. + 'contains invalid characters like capital letters)!';
  68. logger.error(errmsg);
  69. throw new Error(errmsg);
  70. }
  71. this.eventEmitter = new EventEmitter();
  72. this.options = options;
  73. this.eventManager = new JitsiConferenceEventManager(this);
  74. this.participants = {};
  75. this._init(options);
  76. this.componentsVersions = new ComponentsVersions(this);
  77. /**
  78. * Jingle session instance for the JVB connection.
  79. * @type {JingleSessionPC}
  80. */
  81. this.jvbJingleSession = null;
  82. this.lastDominantSpeaker = null;
  83. this.dtmfManager = null;
  84. this.somebodySupportsDTMF = false;
  85. this.authEnabled = false;
  86. this.startAudioMuted = false;
  87. this.startVideoMuted = false;
  88. this.startMutedPolicy = {
  89. audio: false,
  90. video: false
  91. };
  92. this.availableDevices = {
  93. audio: undefined,
  94. video: undefined
  95. };
  96. this.isMutedByFocus = false;
  97. // Flag indicates if the 'onCallEnded' method was ever called on this
  98. // instance. Used to log extra analytics event for debugging purpose.
  99. // We need to know if the potential issue happened before or after
  100. // the restart.
  101. this.wasStopped = false;
  102. /**
  103. * The object which monitors local and remote connection statistics (e.g.
  104. * sending bitrate) and calculates a number which represents the connection
  105. * quality.
  106. */
  107. this.connectionQuality
  108. = new ConnectionQuality(this, this.eventEmitter, options);
  109. /**
  110. * Reports average RTP statistics to the analytics module.
  111. * @type {AvgRTPStatsReporter}
  112. */
  113. this.avgRtpStatsReporter
  114. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  115. /**
  116. * Indicates whether the connection is interrupted or not.
  117. */
  118. this.isJvbConnectionInterrupted = false;
  119. /**
  120. * The object which tracks active speaker times
  121. */
  122. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  123. /* P2P related fields below: */
  124. /**
  125. * Stores reference to deferred start P2P task. It's created when 3rd
  126. * participant leaves the room in order to avoid ping pong effect (it
  127. * could be just a page reload).
  128. * @type {number|null}
  129. */
  130. this.deferredStartP2PTask = null;
  131. const delay = parseInt(options.config.backToP2PDelay, 10);
  132. /**
  133. * A delay given in seconds, before the conference switches back to P2P
  134. * after the 3rd participant has left.
  135. * @type {number}
  136. */
  137. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  138. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  139. /**
  140. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  141. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  142. * and running.
  143. * @type {boolean}
  144. */
  145. this.isP2PConnectionInterrupted = false;
  146. /**
  147. * Flag set to <tt>true</tt> when P2P session has been established
  148. * (ICE has been connected) and this conference is currently in the peer to
  149. * peer mode (P2P connection is the active one).
  150. * @type {boolean}
  151. */
  152. this.p2p = false;
  153. /**
  154. * A JingleSession for the direct peer to peer connection.
  155. * @type {JingleSessionPC}
  156. */
  157. this.p2pJingleSession = null;
  158. }
  159. // FIXME convert JitsiConference to ES6 - ASAP !
  160. JitsiConference.prototype.constructor = JitsiConference;
  161. /**
  162. * Initializes the conference object properties
  163. * @param options {object}
  164. * @param options.connection {JitsiConnection} overrides this.connection
  165. */
  166. JitsiConference.prototype._init = function(options = {}) {
  167. // Override connection and xmpp properties (Useful if the connection
  168. // reloaded)
  169. if (options.connection) {
  170. this.connection = options.connection;
  171. this.xmpp = this.connection.xmpp;
  172. // Setup XMPP events only if we have new connection object.
  173. this.eventManager.setupXMPPListeners();
  174. }
  175. this.room = this.xmpp.createRoom(this.options.name, this.options.config);
  176. // Connection interrupted/restored listeners
  177. this._onIceConnectionInterrupted
  178. = this._onIceConnectionInterrupted.bind(this);
  179. this.room.addListener(
  180. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  181. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  182. this.room.addListener(
  183. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  184. this._onIceConnectionEstablished
  185. = this._onIceConnectionEstablished.bind(this);
  186. this.room.addListener(
  187. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  188. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  189. if (!this.rtc) {
  190. this.rtc = new RTC(this, options);
  191. this.eventManager.setupRTCListeners();
  192. }
  193. this.participantConnectionStatus
  194. = new ParticipantConnectionStatusHandler(
  195. this.rtc,
  196. this,
  197. { // Both these options are not public API, leaving it here only
  198. // as an entry point through config for tuning up purposes.
  199. // Default values should be adjusted as soon as optimal values
  200. // are discovered.
  201. rtcMuteTimeout:
  202. this.options.config._peerConnStatusRtcMuteTimeout,
  203. outOfLastNTimeout:
  204. this.options.config._peerConnStatusOutOfLastNTimeout
  205. });
  206. this.participantConnectionStatus.init();
  207. if (!this.statistics) {
  208. this.statistics = new Statistics(this.xmpp, {
  209. callStatsID: this.options.config.callStatsID,
  210. callStatsSecret: this.options.config.callStatsSecret,
  211. callStatsConfIDNamespace:
  212. this.options.config.callStatsConfIDNamespace
  213. || window.location.hostname,
  214. callStatsCustomScriptUrl:
  215. this.options.config.callStatsCustomScriptUrl,
  216. callStatsAliasName: this.myUserId(),
  217. roomName: this.options.name
  218. });
  219. }
  220. this.eventManager.setupChatRoomListeners();
  221. // Always add listeners because on reload we are executing leave and the
  222. // listeners are removed from statistics module.
  223. this.eventManager.setupStatisticsListeners();
  224. if (this.options.config.enableTalkWhileMuted) {
  225. // eslint-disable-next-line no-new
  226. new TalkMutedDetection(
  227. this,
  228. () =>
  229. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  230. }
  231. if ('channelLastN' in options.config) {
  232. this.setLastN(options.config.channelLastN);
  233. }
  234. };
  235. /**
  236. * Joins the conference.
  237. * @param password {string} the password
  238. */
  239. JitsiConference.prototype.join = function(password) {
  240. if (this.room) {
  241. this.room.join(password);
  242. }
  243. };
  244. /**
  245. * Check if joined to the conference.
  246. */
  247. JitsiConference.prototype.isJoined = function() {
  248. return this.room && this.room.joined;
  249. };
  250. /**
  251. * Leaves the conference.
  252. * @returns {Promise}
  253. */
  254. JitsiConference.prototype.leave = function() {
  255. if (this.participantConnectionStatus) {
  256. this.participantConnectionStatus.dispose();
  257. this.participantConnectionStatus = null;
  258. }
  259. if (this.avgRtpStatsReporter) {
  260. this.avgRtpStatsReporter.dispose();
  261. this.avgRtpStatsReporter = null;
  262. }
  263. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  264. this.rtc.closeAllDataChannels();
  265. if (this.statistics) {
  266. this.statistics.dispose();
  267. }
  268. // Close both JVb and P2P JingleSessions
  269. if (this.jvbJingleSession) {
  270. this.jvbJingleSession.close();
  271. this.jvbJingleSession = null;
  272. }
  273. if (this.p2pJingleSession) {
  274. this.p2pJingleSession.close();
  275. this.p2pJingleSession = null;
  276. }
  277. // leave the conference
  278. if (this.room) {
  279. const room = this.room;
  280. // Unregister connection state listeners
  281. room.removeListener(
  282. XMPPEvents.CONNECTION_INTERRUPTED,
  283. this._onIceConnectionInterrupted);
  284. room.removeListener(
  285. XMPPEvents.CONNECTION_RESTORED,
  286. this._onIceConnectionRestored);
  287. room.removeListener(
  288. XMPPEvents.CONNECTION_ESTABLISHED,
  289. this._onIceConnectionEstablished);
  290. this.room = null;
  291. return room.leave().catch(() => {
  292. // remove all participants because currently the conference won't
  293. // be usable anyway. This is done on success automatically by the
  294. // ChatRoom instance.
  295. this.getParticipants().forEach(
  296. participant => this.onMemberLeft(participant.getJid()));
  297. });
  298. }
  299. // If this.room == null we are calling second time leave().
  300. return Promise.reject(
  301. new Error('The conference is has been already left'));
  302. };
  303. /**
  304. * Returns name of this conference.
  305. */
  306. JitsiConference.prototype.getName = function() {
  307. return this.options.name;
  308. };
  309. /**
  310. * Check if authentication is enabled for this conference.
  311. */
  312. JitsiConference.prototype.isAuthEnabled = function() {
  313. return this.authEnabled;
  314. };
  315. /**
  316. * Check if user is logged in.
  317. */
  318. JitsiConference.prototype.isLoggedIn = function() {
  319. return Boolean(this.authIdentity);
  320. };
  321. /**
  322. * Get authorized login.
  323. */
  324. JitsiConference.prototype.getAuthLogin = function() {
  325. return this.authIdentity;
  326. };
  327. /**
  328. * Check if external authentication is enabled for this conference.
  329. */
  330. JitsiConference.prototype.isExternalAuthEnabled = function() {
  331. return this.room && this.room.moderator.isExternalAuthEnabled();
  332. };
  333. /**
  334. * Get url for external authentication.
  335. * @param {boolean} [urlForPopup] if true then return url for login popup,
  336. * else url of login page.
  337. * @returns {Promise}
  338. */
  339. JitsiConference.prototype.getExternalAuthUrl = function(urlForPopup) {
  340. return new Promise((resolve, reject) => {
  341. if (!this.isExternalAuthEnabled()) {
  342. reject();
  343. return;
  344. }
  345. if (urlForPopup) {
  346. this.room.moderator.getPopupLoginUrl(resolve, reject);
  347. } else {
  348. this.room.moderator.getLoginUrl(resolve, reject);
  349. }
  350. });
  351. };
  352. /**
  353. * Returns the local tracks of the given media type, or all local tracks if no
  354. * specific type is given.
  355. * @param {MediaType} [mediaType] Optional media type (audio or video).
  356. */
  357. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  358. let tracks = [];
  359. if (this.rtc) {
  360. tracks = this.rtc.getLocalTracks(mediaType);
  361. }
  362. return tracks;
  363. };
  364. /**
  365. * Obtains local audio track.
  366. * @return {JitsiLocalTrack|null}
  367. */
  368. JitsiConference.prototype.getLocalAudioTrack = function() {
  369. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  370. };
  371. /**
  372. * Obtains local video track.
  373. * @return {JitsiLocalTrack|null}
  374. */
  375. JitsiConference.prototype.getLocalVideoTrack = function() {
  376. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  377. };
  378. /**
  379. * Attaches a handler for events(For example - "participant joined".) in the
  380. * conference. All possible event are defined in JitsiConferenceEvents.
  381. * @param eventId the event ID.
  382. * @param handler handler for the event.
  383. *
  384. * Note: consider adding eventing functionality by extending an EventEmitter
  385. * impl, instead of rolling ourselves
  386. */
  387. JitsiConference.prototype.on = function(eventId, handler) {
  388. if (this.eventEmitter) {
  389. this.eventEmitter.on(eventId, handler);
  390. }
  391. };
  392. /**
  393. * Removes event listener
  394. * @param eventId the event ID.
  395. * @param [handler] optional, the specific handler to unbind
  396. *
  397. * Note: consider adding eventing functionality by extending an EventEmitter
  398. * impl, instead of rolling ourselves
  399. */
  400. JitsiConference.prototype.off = function(eventId, handler) {
  401. if (this.eventEmitter) {
  402. this.eventEmitter.removeListener(eventId, handler);
  403. }
  404. };
  405. // Common aliases for event emitter
  406. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  407. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  408. /**
  409. * Receives notifications from other participants about commands / custom events
  410. * (sent by sendCommand or sendCommandOnce methods).
  411. * @param command {String} the name of the command
  412. * @param handler {Function} handler for the command
  413. */
  414. JitsiConference.prototype.addCommandListener = function(command, handler) {
  415. if (this.room) {
  416. this.room.addPresenceListener(command, handler);
  417. }
  418. };
  419. /**
  420. * Removes command listener
  421. * @param command {String} the name of the command
  422. */
  423. JitsiConference.prototype.removeCommandListener = function(command) {
  424. if (this.room) {
  425. this.room.removePresenceListener(command);
  426. }
  427. };
  428. /**
  429. * Sends text message to the other participants in the conference
  430. * @param message the text message.
  431. */
  432. JitsiConference.prototype.sendTextMessage = function(message) {
  433. if (this.room) {
  434. this.room.sendMessage(message);
  435. }
  436. };
  437. /**
  438. * Send presence command.
  439. * @param name {String} the name of the command.
  440. * @param values {Object} with keys and values that will be sent.
  441. **/
  442. JitsiConference.prototype.sendCommand = function(name, values) {
  443. if (this.room) {
  444. this.room.addToPresence(name, values);
  445. this.room.sendPresence();
  446. }
  447. };
  448. /**
  449. * Send presence command one time.
  450. * @param name {String} the name of the command.
  451. * @param values {Object} with keys and values that will be sent.
  452. **/
  453. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  454. this.sendCommand(name, values);
  455. this.removeCommand(name);
  456. };
  457. /**
  458. * Removes presence command.
  459. * @param name {String} the name of the command.
  460. **/
  461. JitsiConference.prototype.removeCommand = function(name) {
  462. if (this.room) {
  463. this.room.removeFromPresence(name);
  464. }
  465. };
  466. /**
  467. * Sets the display name for this conference.
  468. * @param name the display name to set
  469. */
  470. JitsiConference.prototype.setDisplayName = function(name) {
  471. if (this.room) {
  472. // remove previously set nickname
  473. this.room.removeFromPresence('nick');
  474. this.room.addToPresence('nick', {
  475. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  476. value: name
  477. });
  478. this.room.sendPresence();
  479. }
  480. };
  481. /**
  482. * Set new subject for this conference. (available only for moderator)
  483. * @param {string} subject new subject
  484. */
  485. JitsiConference.prototype.setSubject = function(subject) {
  486. if (this.room && this.isModerator()) {
  487. this.room.setSubject(subject);
  488. }
  489. };
  490. /**
  491. * Get a transcriber object for all current participants in this conference
  492. * @return {Transcriber} the transcriber object
  493. */
  494. JitsiConference.prototype.getTranscriber = function() {
  495. if (this.transcriber === undefined) {
  496. this.transcriber = new Transcriber();
  497. // add all existing local audio tracks to the transcriber
  498. const localAudioTracks = this.getLocalTracks(MediaType.AUDIO);
  499. for (const localAudio of localAudioTracks) {
  500. this.transcriber.addTrack(localAudio);
  501. }
  502. // and all remote audio tracks
  503. const remoteAudioTracks = this.rtc.getRemoteTracks(MediaType.AUDIO);
  504. for (const remoteTrack of remoteAudioTracks) {
  505. this.transcriber.addTrack(remoteTrack);
  506. }
  507. }
  508. return this.transcriber;
  509. };
  510. /**
  511. * Adds JitsiLocalTrack object to the conference.
  512. * @param track the JitsiLocalTrack object.
  513. * @returns {Promise<JitsiLocalTrack>}
  514. * @throws {Error} if the specified track is a video track and there is already
  515. * another video track in the conference.
  516. */
  517. JitsiConference.prototype.addTrack = function(track) {
  518. if (track.isVideoTrack()) {
  519. // Ensure there's exactly 1 local video track in the conference.
  520. const localVideoTrack = this.rtc.getLocalVideoTrack();
  521. if (localVideoTrack) {
  522. // Don't be excessively harsh and severe if the API client happens
  523. // to attempt to add the same local video track twice.
  524. if (track === localVideoTrack) {
  525. return Promise.resolve(track);
  526. }
  527. return Promise.reject(new Error(
  528. 'cannot add second video track to the conference'));
  529. }
  530. }
  531. return this.replaceTrack(null, track);
  532. };
  533. /**
  534. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  535. * @param {TraceablePeerConnection|null} tpc
  536. * @param audioLevel the audio level
  537. */
  538. JitsiConference.prototype._fireAudioLevelChangeEvent
  539. = function(tpc, audioLevel) {
  540. const activeTpc = this.getActivePeerConnection();
  541. // There will be no TraceablePeerConnection if audio levels do not come from
  542. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  543. // Audio Analyser API and emits local audio levels events through
  544. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  545. // optional.
  546. if (tpc === null || activeTpc === tpc) {
  547. this.eventEmitter.emit(
  548. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  549. this.myUserId(), audioLevel);
  550. }
  551. };
  552. /**
  553. * Fires TRACK_MUTE_CHANGED change conference event.
  554. * @param track the JitsiTrack object related to the event.
  555. */
  556. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  557. // check if track was muted by focus and now is unmuted by user
  558. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  559. this.isMutedByFocus = false;
  560. // unmute local user on server
  561. this.room.muteParticipant(this.room.myroomjid, false);
  562. }
  563. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  564. };
  565. /**
  566. * Clear JitsiLocalTrack properties and listeners.
  567. * @param track the JitsiLocalTrack object.
  568. */
  569. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  570. track._setConference(null);
  571. this.rtc.removeLocalTrack(track);
  572. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  573. track.muteHandler);
  574. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  575. track.audioLevelHandler);
  576. // send event for stopping screen sharing
  577. // FIXME: we assume we have only one screen sharing track
  578. // if we change this we need to fix this check
  579. if (track.isVideoTrack() && track.videoType === VideoType.DESKTOP) {
  580. this.statistics.sendScreenSharingEvent(false);
  581. }
  582. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  583. };
  584. /**
  585. * Removes JitsiLocalTrack from the conference and performs
  586. * a new offer/answer cycle.
  587. * @param {JitsiLocalTrack} track
  588. * @returns {Promise}
  589. */
  590. JitsiConference.prototype.removeTrack = function(track) {
  591. return this.replaceTrack(track, null);
  592. };
  593. /**
  594. * Replaces oldTrack with newTrack and performs a single offer/answer
  595. * cycle after both operations are done. Either oldTrack or newTrack
  596. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  597. * effectively just removes 'oldTrack'
  598. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  599. * @param {JitsiLocalTrack} newTrack the new stream to use
  600. * @returns {Promise} resolves when the replacement is finished
  601. */
  602. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  603. // First do the removal of the oldTrack at the JitsiConference level
  604. if (oldTrack) {
  605. if (oldTrack.disposed) {
  606. return Promise.reject(
  607. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  608. }
  609. }
  610. if (newTrack) {
  611. if (newTrack.disposed) {
  612. return Promise.reject(
  613. new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  614. }
  615. }
  616. // Now replace the stream at the lower levels
  617. return this._doReplaceTrack(oldTrack, newTrack)
  618. .then(() => {
  619. if (oldTrack) {
  620. this.onLocalTrackRemoved(oldTrack);
  621. }
  622. if (newTrack) {
  623. // Now handle the addition of the newTrack at the
  624. // JitsiConference level
  625. this._setupNewTrack(newTrack);
  626. }
  627. return Promise.resolve();
  628. }, error => Promise.reject(new Error(error)));
  629. };
  630. /**
  631. * Replaces the tracks at the lower level by going through the Jingle session
  632. * and WebRTC peer connection. The method will resolve immediately if there is
  633. * currently no JingleSession started.
  634. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  635. * the process or <tt>null</t> if the method should act as "add track"
  636. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  637. * <tt>null</tt> if the method should act as "remove track"
  638. * @return {Promise} resolved when the process is done or rejected with a string
  639. * which describes the error.
  640. * @private
  641. */
  642. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  643. const replaceTrackPromises = [];
  644. if (this.jvbJingleSession) {
  645. replaceTrackPromises.push(
  646. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  647. } else {
  648. logger.info('_doReplaceTrack - no JVB JingleSession');
  649. }
  650. if (this.p2pJingleSession) {
  651. replaceTrackPromises.push(
  652. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  653. } else {
  654. logger.info('_doReplaceTrack - no P2P JingleSession');
  655. }
  656. return Promise.all(replaceTrackPromises);
  657. };
  658. /**
  659. * Operations related to creating a new track
  660. * @param {JitsiLocalTrack} newTrack the new track being created
  661. */
  662. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  663. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  664. && newTrack.videoType !== VideoType.DESKTOP)) {
  665. // Report active device to statistics
  666. const devices = RTC.getCurrentlyAvailableMediaDevices();
  667. const device
  668. = devices.find(
  669. d =>
  670. d.kind === `${newTrack.getTrack().kind}input`
  671. && d.label === newTrack.getTrack().label);
  672. if (device) {
  673. Statistics.sendActiveDeviceListEvent(
  674. RTC.getEventDataForActiveDevice(device));
  675. }
  676. }
  677. if (newTrack.isVideoTrack()) {
  678. this.removeCommand('videoType');
  679. this.sendCommand('videoType', {
  680. value: newTrack.videoType,
  681. attributes: {
  682. xmlns: 'http://jitsi.org/jitmeet/video'
  683. }
  684. });
  685. }
  686. this.rtc.addLocalTrack(newTrack);
  687. // ensure that we're sharing proper "is muted" state
  688. if (newTrack.isAudioTrack()) {
  689. this.room.setAudioMute(newTrack.isMuted());
  690. } else {
  691. this.room.setVideoMute(newTrack.isMuted());
  692. }
  693. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  694. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  695. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  696. newTrack.muteHandler);
  697. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  698. newTrack.audioLevelHandler);
  699. newTrack._setConference(this);
  700. // send event for starting screen sharing
  701. // FIXME: we assume we have only one screen sharing track
  702. // if we change this we need to fix this check
  703. if (newTrack.isVideoTrack() && newTrack.videoType === VideoType.DESKTOP) {
  704. this.statistics.sendScreenSharingEvent(true);
  705. }
  706. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  707. };
  708. /**
  709. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  710. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  711. * removed on video mute).
  712. * @param {JitsiLocalTrack} track the local track that will be added as part of
  713. * the unmute operation.
  714. * @return {Promise} resolved when the process is done or rejected with a string
  715. * which describes the error.
  716. */
  717. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  718. const addAsUnmutePromises = [];
  719. if (this.jvbJingleSession) {
  720. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  721. } else {
  722. logger.info(
  723. 'Add local MediaStream as unmute -'
  724. + ' no JVB Jingle session started yet');
  725. }
  726. if (this.p2pJingleSession) {
  727. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  728. } else {
  729. logger.info(
  730. 'Add local MediaStream as unmute -'
  731. + ' no P2P Jingle session started yet');
  732. }
  733. return Promise.all(addAsUnmutePromises);
  734. };
  735. /**
  736. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  737. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  738. * that is to stop sending any data and turn off the HW camera device.
  739. * @param {JitsiLocalTrack} track the local track that will be removed.
  740. * @return {Promise}
  741. */
  742. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  743. const removeAsMutePromises = [];
  744. if (this.jvbJingleSession) {
  745. removeAsMutePromises.push(
  746. this.jvbJingleSession.removeTrackAsMute(track));
  747. } else {
  748. logger.info(
  749. 'Remove local MediaStream - no JVB JingleSession started yet');
  750. }
  751. if (this.p2pJingleSession) {
  752. removeAsMutePromises.push(
  753. this.p2pJingleSession.removeTrackAsMute(track));
  754. } else {
  755. logger.info(
  756. 'Remove local MediaStream - no P2P JingleSession started yet');
  757. }
  758. return Promise.all(removeAsMutePromises);
  759. };
  760. /**
  761. * Get role of the local user.
  762. * @returns {string} user role: 'moderator' or 'none'
  763. */
  764. JitsiConference.prototype.getRole = function() {
  765. return this.room.role;
  766. };
  767. /**
  768. * Check if local user is moderator.
  769. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  770. * we're no longer in the conference room then <tt>null</tt> is returned.
  771. */
  772. JitsiConference.prototype.isModerator = function() {
  773. return this.room ? this.room.isModerator() : null;
  774. };
  775. /**
  776. * Set password for the room.
  777. * @param {string} password new password for the room.
  778. * @returns {Promise}
  779. */
  780. JitsiConference.prototype.lock = function(password) {
  781. if (!this.isModerator()) {
  782. return Promise.reject();
  783. }
  784. return new Promise((resolve, reject) => {
  785. this.room.lockRoom(
  786. password || '',
  787. () => resolve(),
  788. err => reject(err),
  789. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  790. });
  791. };
  792. /**
  793. * Remove password from the room.
  794. * @returns {Promise}
  795. */
  796. JitsiConference.prototype.unlock = function() {
  797. return this.lock();
  798. };
  799. /**
  800. * Elects the participant with the given id to be the selected participant in
  801. * order to receive higher video quality (if simulcast is enabled).
  802. * Or cache it if channel is not created and send it once channel is available.
  803. * @param participantId the identifier of the participant
  804. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  805. */
  806. JitsiConference.prototype.selectParticipant = function(participantId) {
  807. this.rtc.selectEndpoint(participantId);
  808. };
  809. /**
  810. * Elects the participant with the given id to be the pinned participant in
  811. * order to always receive video for this participant (even when last n is
  812. * enabled).
  813. * @param participantId the identifier of the participant
  814. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  815. */
  816. JitsiConference.prototype.pinParticipant = function(participantId) {
  817. this.rtc.pinEndpoint(participantId);
  818. };
  819. /**
  820. * Selects a new value for "lastN". The requested amount of videos are going
  821. * to be delivered after the value is in effect. Set to -1 for unlimited or
  822. * all available videos.
  823. * @param lastN the new number of videos the user would like to receive.
  824. * @throws Error or RangeError if the given value is not a number or is smaller
  825. * than -1.
  826. */
  827. JitsiConference.prototype.setLastN = function(lastN) {
  828. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  829. throw new Error(`Invalid value for lastN: ${lastN}`);
  830. }
  831. const n = Number(lastN);
  832. if (n < -1) {
  833. throw new RangeError('lastN cannot be smaller than -1');
  834. }
  835. this.rtc.setLastN(n);
  836. };
  837. /**
  838. * Checks if the participant given by participantId is currently included in
  839. * the last N.
  840. * @param {string} participantId the identifier of the participant we would
  841. * like to check.
  842. * @return {boolean} true if the participant with id is in the last N set or
  843. * if there's no last N set, false otherwise.
  844. * @deprecated this method should never be used to figure out the UI, but
  845. * {@link ParticipantConnectionStatus} should be used instead.
  846. */
  847. JitsiConference.prototype.isInLastN = function(participantId) {
  848. return this.rtc.isInLastN(participantId);
  849. };
  850. /**
  851. * @return Array<JitsiParticipant> an array of all participants in this
  852. * conference.
  853. */
  854. JitsiConference.prototype.getParticipants = function() {
  855. return Object.keys(this.participants).map(function(key) {
  856. return this.participants[key];
  857. }, this);
  858. };
  859. /**
  860. * Returns the number of participants in the conference, including the local
  861. * participant.
  862. * @param countHidden {boolean} Whether or not to include hidden participants
  863. * in the count. Default: false.
  864. **/
  865. JitsiConference.prototype.getParticipantCount
  866. = function(countHidden = false) {
  867. let participants = this.getParticipants();
  868. if (!countHidden) {
  869. participants = participants.filter(p => !p.isHidden());
  870. }
  871. // Add one for the local participant.
  872. return participants.length + 1;
  873. };
  874. /**
  875. * @returns {JitsiParticipant} the participant in this conference with the
  876. * specified id (or undefined if there isn't one).
  877. * @param id the id of the participant.
  878. */
  879. JitsiConference.prototype.getParticipantById = function(id) {
  880. return this.participants[id];
  881. };
  882. /**
  883. * Kick participant from this conference.
  884. * @param {string} id id of the participant to kick
  885. */
  886. JitsiConference.prototype.kickParticipant = function(id) {
  887. const participant = this.getParticipantById(id);
  888. if (!participant) {
  889. return;
  890. }
  891. this.room.kick(participant.getJid());
  892. };
  893. /**
  894. * Mutes a participant.
  895. * @param {string} id The id of the participant to mute.
  896. */
  897. JitsiConference.prototype.muteParticipant = function(id) {
  898. const participant = this.getParticipantById(id);
  899. if (!participant) {
  900. return;
  901. }
  902. this.room.muteParticipant(participant.getJid(), true);
  903. };
  904. /* eslint-disable max-params */
  905. /**
  906. * Notifies this JitsiConference that a new member has joined its chat room.
  907. *
  908. * FIXME This should NOT be exposed!
  909. *
  910. * @param jid the jid of the participant in the MUC
  911. * @param nick the display name of the participant
  912. * @param role the role of the participant in the MUC
  913. * @param isHidden indicates if this is a hidden participant (system
  914. * participant for example a recorder).
  915. */
  916. JitsiConference.prototype.onMemberJoined = function(jid, nick, role, isHidden) {
  917. const id = Strophe.getResourceFromJid(jid);
  918. if (id === 'focus' || this.myUserId() === id) {
  919. return;
  920. }
  921. const participant = new JitsiParticipant(jid, this, nick, isHidden);
  922. participant._role = role;
  923. this.participants[id] = participant;
  924. this.eventEmitter.emit(
  925. JitsiConferenceEvents.USER_JOINED,
  926. id,
  927. participant);
  928. this.xmpp.caps.getFeatures(jid)
  929. .then(features => {
  930. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  931. this.updateDTMFSupport();
  932. },
  933. error => logger.error(`Failed to discover features of ${jid}`, error));
  934. this._maybeStartOrStopP2P();
  935. };
  936. /* eslint-enable max-params */
  937. JitsiConference.prototype.onMemberLeft = function(jid) {
  938. const id = Strophe.getResourceFromJid(jid);
  939. if (id === 'focus' || this.myUserId() === id) {
  940. return;
  941. }
  942. const participant = this.participants[id];
  943. delete this.participants[id];
  944. const removedTracks = this.rtc.removeRemoteTracks(id);
  945. removedTracks.forEach(
  946. track =>
  947. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  948. // there can be no participant in case the member that left is focus
  949. if (participant) {
  950. this.eventEmitter.emit(
  951. JitsiConferenceEvents.USER_LEFT, id, participant);
  952. }
  953. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  954. };
  955. /**
  956. * Method called on local MUC role change.
  957. * @param {string} role the name of new user's role as defined by XMPP MUC.
  958. */
  959. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  960. // Emit role changed for local JID
  961. this.eventEmitter.emit(
  962. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  963. // Maybe start P2P
  964. this._maybeStartOrStopP2P();
  965. };
  966. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  967. const id = Strophe.getResourceFromJid(jid);
  968. const participant = this.getParticipantById(id);
  969. if (!participant) {
  970. return;
  971. }
  972. participant._role = role;
  973. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  974. };
  975. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  976. const id = Strophe.getResourceFromJid(jid);
  977. const participant = this.getParticipantById(id);
  978. if (!participant) {
  979. return;
  980. }
  981. if (participant._displayName === displayName) {
  982. return;
  983. }
  984. participant._displayName = displayName;
  985. this.eventEmitter.emit(
  986. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  987. id,
  988. displayName);
  989. };
  990. /**
  991. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  992. * the conference.
  993. *
  994. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  995. * JitsiConference
  996. */
  997. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  998. if (track.isP2P && !this.isP2PActive()) {
  999. logger.info(
  1000. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1001. return;
  1002. } else if (!track.isP2P && this.isP2PActive()) {
  1003. logger.info(
  1004. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1005. return;
  1006. }
  1007. const id = track.getParticipantId();
  1008. const participant = this.getParticipantById(id);
  1009. if (!participant) {
  1010. logger.error(`No participant found for id: ${id}`);
  1011. return;
  1012. }
  1013. // Add track to JitsiParticipant.
  1014. participant._tracks.push(track);
  1015. if (this.transcriber) {
  1016. this.transcriber.addTrack(track);
  1017. }
  1018. const emitter = this.eventEmitter;
  1019. track.addEventListener(
  1020. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1021. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1022. track.addEventListener(
  1023. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1024. (tpc, audioLevel) => {
  1025. const activeTPC = this.getActivePeerConnection();
  1026. if (activeTPC === tpc) {
  1027. emitter.emit(
  1028. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1029. id,
  1030. audioLevel);
  1031. }
  1032. }
  1033. );
  1034. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1035. };
  1036. /**
  1037. * Callback called by the Jingle plugin when 'session-answer' is received.
  1038. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1039. * received.
  1040. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1041. */
  1042. // eslint-disable-next-line no-unused-vars
  1043. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1044. if (this.p2pJingleSession === session) {
  1045. logger.info('P2P setAnswer');
  1046. this.p2pJingleSession.setAnswer(answer);
  1047. }
  1048. };
  1049. /**
  1050. * Callback called by the Jingle plugin when 'transport-info' is received.
  1051. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1052. * received
  1053. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1054. * element
  1055. */
  1056. // eslint-disable-next-line no-unused-vars
  1057. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1058. if (this.p2pJingleSession === session) {
  1059. logger.info('P2P addIceCandidates');
  1060. this.p2pJingleSession.addIceCandidates(transportInfo);
  1061. }
  1062. };
  1063. /**
  1064. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1065. * the conference.
  1066. *
  1067. * @param {JitsiRemoteTrack} removedTrack
  1068. */
  1069. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1070. let consumed = false;
  1071. this.getParticipants().forEach(participant => {
  1072. const tracks = participant.getTracks();
  1073. for (let i = 0; i < tracks.length; i++) {
  1074. if (tracks[i] === removedTrack) {
  1075. // Since the tracks have been compared and are
  1076. // considered equal the result of splice can be ignored.
  1077. participant._tracks.splice(i, 1);
  1078. this.eventEmitter.emit(
  1079. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1080. if (this.transcriber) {
  1081. this.transcriber.removeTrack(removedTrack);
  1082. }
  1083. consumed = true;
  1084. break;
  1085. }
  1086. }
  1087. }, this);
  1088. if (!consumed) {
  1089. if ((this.isP2PActive() && !removedTrack.isP2P)
  1090. || (!this.isP2PActive() && removedTrack.isP2P)) {
  1091. // A remote track can be removed either as a result of
  1092. // 'source-remove' or the P2P logic which removes remote tracks
  1093. // explicitly when switching between JVB and P2P connections.
  1094. // The check above filters out the P2P logic case which should not
  1095. // result in an error (which just goes over all remote tracks).
  1096. return;
  1097. }
  1098. logger.error(
  1099. 'Failed to match remote track on remove'
  1100. + ' with any of the participants',
  1101. removedTrack.getStreamId(),
  1102. removedTrack.getParticipantId());
  1103. }
  1104. };
  1105. /**
  1106. * Handles incoming call event.
  1107. */
  1108. JitsiConference.prototype.onIncomingCall
  1109. = function(jingleSession, jingleOffer, now) {
  1110. // Handle incoming P2P call
  1111. if (jingleSession.isP2P) {
  1112. const role = this.room.getMemberRole(jingleSession.peerjid);
  1113. if (role !== 'moderator') {
  1114. // Reject incoming P2P call
  1115. this._rejectIncomingCallNonModerator(jingleSession);
  1116. } else if (!RTCBrowserType.isP2PSupported()) {
  1117. // Reject incoming P2P call (already in progress)
  1118. this._rejectIncomingCall(
  1119. jingleSession, {
  1120. reasonTag: 'unsupported-applications',
  1121. reasonMsg: 'P2P not supported',
  1122. errorMsg: 'This client does not support P2P connections'
  1123. });
  1124. } else if (this.p2pJingleSession) {
  1125. // Reject incoming P2P call (already in progress)
  1126. this._rejectIncomingCall(
  1127. jingleSession, {
  1128. reasonTag: 'busy',
  1129. reasonMsg: 'P2P already in progress',
  1130. errorMsg: 'Duplicated P2P "session-initiate"'
  1131. });
  1132. } else {
  1133. // Accept incoming P2P call
  1134. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1135. }
  1136. return;
  1137. } else if (!this.room.isFocus(jingleSession.peerjid)) {
  1138. this._rejectIncomingCall(jingleSession);
  1139. return;
  1140. }
  1141. // Accept incoming call
  1142. this.jvbJingleSession = jingleSession;
  1143. this.room.connectionTimes['session.initiate'] = now;
  1144. // Log "session.restart"
  1145. if (this.wasStopped) {
  1146. Statistics.sendEventToAll('session.restart');
  1147. }
  1148. // add info whether call is cross-region
  1149. let crossRegion = null;
  1150. // TODO: remove deprecated cross region property from this specific event
  1151. // once all existing deployments include analytics changes
  1152. if (window.jitsiDeploymentInfo) {
  1153. crossRegion = window.jitsiDeploymentInfo.CrossRegion;
  1154. }
  1155. Statistics.analytics.sendEvent(
  1156. 'session.initiate', {
  1157. value: now - this.room.connectionTimes['muc.joined'],
  1158. label: crossRegion
  1159. });
  1160. try {
  1161. jingleSession.initialize(false /* initiator */, this.room, this.rtc);
  1162. } catch (error) {
  1163. GlobalOnErrorHandler.callErrorHandler(error);
  1164. }
  1165. this.rtc.initializeDataChannels(jingleSession.peerconnection);
  1166. // Add local tracks to the session
  1167. try {
  1168. jingleSession.acceptOffer(
  1169. jingleOffer,
  1170. null /* success */,
  1171. error => {
  1172. GlobalOnErrorHandler.callErrorHandler(error);
  1173. logger.error(
  1174. 'Failed to accept incoming Jingle session', error);
  1175. },
  1176. this.getLocalTracks()
  1177. );
  1178. // Start callstats as soon as peerconnection is initialized,
  1179. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1180. // happen in case if user doesn't have or denied permission to
  1181. // both camera and microphone.
  1182. logger.info('Starting CallStats for JVB connection...');
  1183. this.statistics.startCallStats(
  1184. this.jvbJingleSession.peerconnection,
  1185. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1186. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1187. } catch (e) {
  1188. GlobalOnErrorHandler.callErrorHandler(e);
  1189. logger.error(e);
  1190. }
  1191. };
  1192. /**
  1193. * Rejects incoming Jingle call with 'security-error'. Method should be used to
  1194. * reject calls initiated by unauthorised entities.
  1195. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1196. * @private
  1197. */
  1198. JitsiConference.prototype._rejectIncomingCallNonModerator
  1199. = function(jingleSession) {
  1200. this._rejectIncomingCall(
  1201. jingleSession,
  1202. {
  1203. reasonTag: 'security-error',
  1204. reasonMsg: 'Only focus can start new sessions',
  1205. errorMsg: 'Rejecting session-initiate from non-focus and'
  1206. + `non-moderator user: ${jingleSession.peerjid}`
  1207. });
  1208. };
  1209. /**
  1210. * Rejects incoming Jingle call.
  1211. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1212. * @param {object} [options]
  1213. * @param {string} options.reasonTag the name of the reason element as defined
  1214. * by Jingle
  1215. * @param {string} options.reasonMsg the reason description which will
  1216. * be included in Jingle 'session-terminate' message.
  1217. * @param {string} options.errorMsg an error message to be logged on global
  1218. * error handler
  1219. * @private
  1220. */
  1221. JitsiConference.prototype._rejectIncomingCall
  1222. = function(jingleSession, options) {
  1223. if (options && options.errorMsg) {
  1224. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1225. }
  1226. // Terminate the jingle session with a reason
  1227. jingleSession.terminate(
  1228. options && options.reasonTag,
  1229. options && options.reasonMsg,
  1230. null /* success callback => we don't care */,
  1231. error => {
  1232. logger.warn(
  1233. 'An error occurred while trying to terminate'
  1234. + ' invalid Jingle session', error);
  1235. });
  1236. };
  1237. /**
  1238. * Handles the call ended event.
  1239. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1240. * terminated.
  1241. * @param {String} reasonCondition the Jingle reason condition.
  1242. * @param {String|null} reasonText human readable reason text which may provide
  1243. * more details about why the call has been terminated.
  1244. */
  1245. JitsiConference.prototype.onCallEnded
  1246. = function(jingleSession, reasonCondition, reasonText) {
  1247. logger.info(
  1248. `Call ended: ${reasonCondition} - ${reasonText
  1249. } P2P ?${jingleSession.isP2P}`);
  1250. if (jingleSession === this.jvbJingleSession) {
  1251. this.wasStopped = true;
  1252. // Send session.terminate event
  1253. Statistics.sendEventToAll('session.terminate');
  1254. // Stop the stats
  1255. if (this.statistics) {
  1256. this.statistics.stopRemoteStats(
  1257. this.jvbJingleSession.peerconnection);
  1258. logger.info('Stopping JVB CallStats');
  1259. this.statistics.stopCallStats(
  1260. this.jvbJingleSession.peerconnection);
  1261. }
  1262. // Current JVB JingleSession is no longer valid, so set it to null
  1263. this.jvbJingleSession = null;
  1264. // Let the RTC service do any cleanups
  1265. this.rtc.onCallEnded();
  1266. } else if (jingleSession === this.p2pJingleSession) {
  1267. this._stopP2PSession();
  1268. } else {
  1269. logger.error(
  1270. 'Received onCallEnded for invalid session',
  1271. jingleSession.sid,
  1272. jingleSession.peerjid,
  1273. reasonCondition,
  1274. reasonText);
  1275. }
  1276. };
  1277. /**
  1278. * Handles the suspend detected event. Leaves the room and fires suspended.
  1279. * @param {JingleSessionPC} jingleSession
  1280. */
  1281. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1282. if (!jingleSession.isP2P) {
  1283. this.leave();
  1284. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1285. }
  1286. };
  1287. JitsiConference.prototype.updateDTMFSupport = function() {
  1288. let somebodySupportsDTMF = false;
  1289. const participants = this.getParticipants();
  1290. // check if at least 1 participant supports DTMF
  1291. for (let i = 0; i < participants.length; i += 1) {
  1292. if (participants[i].supportsDTMF()) {
  1293. somebodySupportsDTMF = true;
  1294. break;
  1295. }
  1296. }
  1297. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1298. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1299. this.eventEmitter.emit(
  1300. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1301. somebodySupportsDTMF);
  1302. }
  1303. };
  1304. /**
  1305. * Allows to check if there is at least one user in the conference
  1306. * that supports DTMF.
  1307. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1308. */
  1309. JitsiConference.prototype.isDTMFSupported = function() {
  1310. return this.somebodySupportsDTMF;
  1311. };
  1312. /**
  1313. * Returns the local user's ID
  1314. * @return {string} local user's ID
  1315. */
  1316. JitsiConference.prototype.myUserId = function() {
  1317. return (
  1318. this.room
  1319. && this.room.myroomjid
  1320. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1321. : null);
  1322. };
  1323. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1324. if (!this.dtmfManager) {
  1325. const peerConnection = this.getActivePeerConnection();
  1326. if (!peerConnection) {
  1327. logger.warn('cannot sendTones: no peer connection');
  1328. return;
  1329. }
  1330. const localAudio = this.getLocalAudioTrack();
  1331. if (!localAudio) {
  1332. logger.warn('cannot sendTones: no local audio stream');
  1333. return;
  1334. }
  1335. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1336. }
  1337. this.dtmfManager.sendTones(tones, duration, pause);
  1338. };
  1339. /**
  1340. * Returns true if recording is supported and false if not.
  1341. */
  1342. JitsiConference.prototype.isRecordingSupported = function() {
  1343. if (this.room) {
  1344. return this.room.isRecordingSupported();
  1345. }
  1346. return false;
  1347. };
  1348. /**
  1349. * Returns null if the recording is not supported, "on" if the recording started
  1350. * and "off" if the recording is not started.
  1351. */
  1352. JitsiConference.prototype.getRecordingState = function() {
  1353. return this.room ? this.room.getRecordingState() : undefined;
  1354. };
  1355. /**
  1356. * Returns the url of the recorded video.
  1357. */
  1358. JitsiConference.prototype.getRecordingURL = function() {
  1359. return this.room ? this.room.getRecordingURL() : null;
  1360. };
  1361. /**
  1362. * Starts/stops the recording
  1363. */
  1364. JitsiConference.prototype.toggleRecording = function(options) {
  1365. if (this.room) {
  1366. return this.room.toggleRecording(options, (status, error) => {
  1367. this.eventEmitter.emit(
  1368. JitsiConferenceEvents.RECORDER_STATE_CHANGED, status, error);
  1369. });
  1370. }
  1371. this.eventEmitter.emit(
  1372. JitsiConferenceEvents.RECORDER_STATE_CHANGED, 'error',
  1373. new Error('The conference is not created yet!'));
  1374. };
  1375. /**
  1376. * Returns true if the SIP calls are supported and false otherwise
  1377. */
  1378. JitsiConference.prototype.isSIPCallingSupported = function() {
  1379. if (this.room) {
  1380. return this.room.isSIPCallingSupported();
  1381. }
  1382. return false;
  1383. };
  1384. /**
  1385. * Dials a number.
  1386. * @param number the number
  1387. */
  1388. JitsiConference.prototype.dial = function(number) {
  1389. if (this.room) {
  1390. return this.room.dial(number);
  1391. }
  1392. return new Promise((resolve, reject) => {
  1393. reject(new Error('The conference is not created yet!'));
  1394. });
  1395. };
  1396. /**
  1397. * Hangup an existing call
  1398. */
  1399. JitsiConference.prototype.hangup = function() {
  1400. if (this.room) {
  1401. return this.room.hangup();
  1402. }
  1403. return new Promise((resolve, reject) => {
  1404. reject(new Error('The conference is not created yet!'));
  1405. });
  1406. };
  1407. /**
  1408. * Returns the phone number for joining the conference.
  1409. */
  1410. JitsiConference.prototype.getPhoneNumber = function() {
  1411. if (this.room) {
  1412. return this.room.getPhoneNumber();
  1413. }
  1414. return null;
  1415. };
  1416. /**
  1417. * Returns the pin for joining the conference with phone.
  1418. */
  1419. JitsiConference.prototype.getPhonePin = function() {
  1420. if (this.room) {
  1421. return this.room.getPhonePin();
  1422. }
  1423. return null;
  1424. };
  1425. /**
  1426. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1427. * which connection is currently active.
  1428. *
  1429. * @return {TraceablePeerConnection|null} null if there isn't any active
  1430. * <tt>TraceablePeerConnection</tt> currently available.
  1431. * @public (FIXME how to make package local ?)
  1432. */
  1433. JitsiConference.prototype.getActivePeerConnection = function() {
  1434. if (this.isP2PActive()) {
  1435. return this.p2pJingleSession.peerconnection;
  1436. }
  1437. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1438. };
  1439. /**
  1440. * Returns the connection state for the current room. Its ice connection state
  1441. * for its session.
  1442. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1443. * be converted to "connected".
  1444. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1445. * peer connection at this time.
  1446. */
  1447. JitsiConference.prototype.getConnectionState = function() {
  1448. const peerConnection = this.getActivePeerConnection();
  1449. return peerConnection ? peerConnection.getConnectionState() : null;
  1450. };
  1451. /**
  1452. * Make all new participants mute their audio/video on join.
  1453. * @param policy {Object} object with 2 boolean properties for video and audio:
  1454. * @param {boolean} audio if audio should be muted.
  1455. * @param {boolean} video if video should be muted.
  1456. */
  1457. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1458. if (!this.isModerator()) {
  1459. return;
  1460. }
  1461. this.startMutedPolicy = policy;
  1462. this.room.removeFromPresence('startmuted');
  1463. this.room.addToPresence('startmuted', {
  1464. attributes: {
  1465. audio: policy.audio,
  1466. video: policy.video,
  1467. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1468. }
  1469. });
  1470. this.room.sendPresence();
  1471. };
  1472. /**
  1473. * Returns current start muted policy
  1474. * @returns {Object} with 2 properties - audio and video.
  1475. */
  1476. JitsiConference.prototype.getStartMutedPolicy = function() {
  1477. return this.startMutedPolicy;
  1478. };
  1479. /**
  1480. * Check if audio is muted on join.
  1481. */
  1482. JitsiConference.prototype.isStartAudioMuted = function() {
  1483. return this.startAudioMuted;
  1484. };
  1485. /**
  1486. * Check if video is muted on join.
  1487. */
  1488. JitsiConference.prototype.isStartVideoMuted = function() {
  1489. return this.startVideoMuted;
  1490. };
  1491. /**
  1492. * Get object with internal logs.
  1493. */
  1494. JitsiConference.prototype.getLogs = function() {
  1495. const data = this.xmpp.getJingleLog();
  1496. const metadata = {};
  1497. metadata.time = new Date();
  1498. metadata.url = window.location.href;
  1499. metadata.ua = navigator.userAgent;
  1500. const log = this.xmpp.getXmppLog();
  1501. if (log) {
  1502. metadata.xmpp = log;
  1503. }
  1504. data.metadata = metadata;
  1505. return data;
  1506. };
  1507. /**
  1508. * Returns measured connectionTimes.
  1509. */
  1510. JitsiConference.prototype.getConnectionTimes = function() {
  1511. return this.room.connectionTimes;
  1512. };
  1513. /**
  1514. * Sets a property for the local participant.
  1515. */
  1516. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1517. this.sendCommand(`jitsi_participant_${name}`, { value });
  1518. };
  1519. /**
  1520. * Sends the given feedback through CallStats if enabled.
  1521. *
  1522. * @param overallFeedback an integer between 1 and 5 indicating the
  1523. * user feedback
  1524. * @param detailedFeedback detailed feedback from the user. Not yet used
  1525. */
  1526. JitsiConference.prototype.sendFeedback
  1527. = function(overallFeedback, detailedFeedback) {
  1528. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1529. };
  1530. /**
  1531. * Returns true if the callstats integration is enabled, otherwise returns
  1532. * false.
  1533. *
  1534. * @returns true if the callstats integration is enabled, otherwise returns
  1535. * false.
  1536. */
  1537. JitsiConference.prototype.isCallstatsEnabled = function() {
  1538. return this.statistics.isCallstatsEnabled();
  1539. };
  1540. /**
  1541. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1542. * from statistics module)
  1543. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1544. * @param container the container
  1545. */
  1546. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1547. const isLocal = track.isLocal();
  1548. let ssrc = null;
  1549. const isP2P = track.isP2P;
  1550. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  1551. const peerConnection
  1552. = isP2P
  1553. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  1554. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1555. if (isLocal) {
  1556. // Local tracks have SSRC stored on per peer connection basis
  1557. if (peerConnection) {
  1558. ssrc = peerConnection.getLocalSSRC(track);
  1559. }
  1560. } else {
  1561. ssrc = track.getSSRC();
  1562. }
  1563. if (!container.id || !ssrc || !peerConnection) {
  1564. return;
  1565. }
  1566. this.statistics.associateStreamWithVideoTag(
  1567. peerConnection,
  1568. ssrc,
  1569. isLocal,
  1570. remoteUserId,
  1571. track.getUsageLabel(),
  1572. container.id);
  1573. };
  1574. /**
  1575. * Logs an "application log" message.
  1576. * @param message {string} The message to log. Note that while this can be a
  1577. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  1578. * log valid JSON strings, with an "id" field used for distinguishing between
  1579. * message types. E.g.: {id: "recorder_status", status: "off"}
  1580. */
  1581. JitsiConference.prototype.sendApplicationLog = function(message) {
  1582. Statistics.sendLog(message);
  1583. };
  1584. /**
  1585. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1586. * focus.
  1587. * @param mucJid the full MUC address of the user to be checked.
  1588. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  1589. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  1590. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  1591. */
  1592. JitsiConference.prototype._isFocus = function(mucJid) {
  1593. return this.room ? this.room.isFocus(mucJid) : null;
  1594. };
  1595. /**
  1596. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  1597. */
  1598. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  1599. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  1600. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  1601. };
  1602. /**
  1603. * Sends a message via the data channel.
  1604. * @param to {string} the id of the endpoint that should receive the message.
  1605. * If "" the message will be sent to all participants.
  1606. * @param payload {object} the payload of the message.
  1607. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1608. */
  1609. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  1610. this.rtc.sendDataChannelMessage(to, payload);
  1611. };
  1612. /**
  1613. * Sends a broadcast message via the data channel.
  1614. * @param payload {object} the payload of the message.
  1615. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1616. */
  1617. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  1618. this.sendEndpointMessage('', payload);
  1619. };
  1620. JitsiConference.prototype.isConnectionInterrupted = function() {
  1621. return this.isP2PActive()
  1622. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  1623. };
  1624. /**
  1625. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  1626. * @param {JingleSessionPC} session
  1627. * @private
  1628. */
  1629. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  1630. if (session.isP2P) {
  1631. this.isP2PConnectionInterrupted = true;
  1632. } else {
  1633. this.isJvbConnectionInterrupted = true;
  1634. }
  1635. if (session.isP2P === this.isP2PActive()) {
  1636. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  1637. }
  1638. };
  1639. /**
  1640. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  1641. * @param {JingleSessionPC} session
  1642. * @private
  1643. */
  1644. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  1645. // We do nothing for the JVB connection, because it's up to the Jicofo to
  1646. // eventually come up with the new offer (at least for the time being).
  1647. if (session.isP2P) {
  1648. if (this.p2pJingleSession && this.p2pJingleSession.isInitiator) {
  1649. Statistics.sendEventToAll('p2p.failed');
  1650. }
  1651. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  1652. }
  1653. };
  1654. /**
  1655. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  1656. * @param {JingleSessionPC} session
  1657. * @private
  1658. */
  1659. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  1660. if (session.isP2P) {
  1661. this.isP2PConnectionInterrupted = false;
  1662. } else {
  1663. this.isJvbConnectionInterrupted = false;
  1664. }
  1665. if (session.isP2P === this.isP2PActive()) {
  1666. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  1667. }
  1668. };
  1669. /**
  1670. * Accept incoming P2P Jingle call.
  1671. * @param {JingleSessionPC} jingleSession the session instance
  1672. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  1673. * @private
  1674. */
  1675. JitsiConference.prototype._acceptP2PIncomingCall
  1676. = function(jingleSession, jingleOffer) {
  1677. jingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1678. this.isP2PConnectionInterrupted = false;
  1679. // Accept the offer
  1680. this.p2pJingleSession = jingleSession;
  1681. this.p2pJingleSession.initialize(
  1682. false /* initiator */, this.room, this.rtc);
  1683. logger.info('Starting CallStats for P2P connection...');
  1684. this.statistics.startCallStats(
  1685. this.p2pJingleSession.peerconnection,
  1686. Strophe.getResourceFromJid(this.p2pJingleSession.peerjid));
  1687. const localTracks = this.getLocalTracks();
  1688. this.p2pJingleSession.acceptOffer(
  1689. jingleOffer,
  1690. () => {
  1691. logger.debug('Got RESULT for P2P "session-accept"');
  1692. },
  1693. error => {
  1694. logger.error(
  1695. 'Failed to accept incoming P2P Jingle session', error);
  1696. },
  1697. localTracks);
  1698. };
  1699. /**
  1700. * Adds remote tracks to the conference associated with the JVB session.
  1701. * @private
  1702. */
  1703. JitsiConference.prototype._addRemoteJVBTracks = function() {
  1704. this._addRemoteTracks(
  1705. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1706. };
  1707. /**
  1708. * Adds remote tracks to the conference associated with the P2P session.
  1709. * @private
  1710. */
  1711. JitsiConference.prototype._addRemoteP2PTracks = function() {
  1712. this._addRemoteTracks(
  1713. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1714. };
  1715. /**
  1716. * Generates fake "remote track added" events for given Jingle session.
  1717. * @param {string} logName the session's nickname which will appear in log
  1718. * messages.
  1719. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  1720. * @private
  1721. */
  1722. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  1723. for (const track of remoteTracks) {
  1724. logger.info(`Adding remote ${logName} track: ${track}`);
  1725. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, track);
  1726. }
  1727. };
  1728. /**
  1729. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  1730. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  1731. * the P2P connection if the event comes from the P2P session.
  1732. * @param {JingleSessionPC} jingleSession the session instance.
  1733. * @private
  1734. */
  1735. JitsiConference.prototype._onIceConnectionEstablished
  1736. = function(jingleSession) {
  1737. // We don't care about the JVB case, there's nothing to be done
  1738. if (!jingleSession.isP2P) {
  1739. return;
  1740. } else if (this.p2pJingleSession !== jingleSession) {
  1741. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  1742. return;
  1743. }
  1744. // Update P2P status and emit events
  1745. this._setP2PStatus(true);
  1746. // Remove remote tracks
  1747. if (this.jvbJingleSession) {
  1748. this._removeRemoteJVBTracks();
  1749. } else {
  1750. logger.info('Not removing remote JVB tracks - no session yet');
  1751. }
  1752. // Add remote tracks
  1753. this._addRemoteP2PTracks();
  1754. // Stop media transfer over the JVB connection
  1755. if (this.jvbJingleSession) {
  1756. this._suspendMediaTransferForJvbConnection();
  1757. }
  1758. // Start remote stats
  1759. logger.info('Starting remote stats with p2p connection');
  1760. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  1761. // Log the P2P established event
  1762. if (this.p2pJingleSession.isInitiator) {
  1763. Statistics.sendEventToAll('p2p.established');
  1764. }
  1765. };
  1766. /**
  1767. * Clears the deferred start P2P task if it has been scheduled.
  1768. * @private
  1769. */
  1770. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  1771. if (this.deferredStartP2PTask) {
  1772. logger.info('Cleared deferred start P2P task');
  1773. clearTimeout(this.deferredStartP2PTask);
  1774. this.deferredStartP2PTask = null;
  1775. }
  1776. };
  1777. /**
  1778. * Removes from the conference remote tracks associated with the JVB
  1779. * connection.
  1780. * @private
  1781. */
  1782. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  1783. this._removeRemoteTracks(
  1784. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  1785. };
  1786. /**
  1787. * Removes from the conference remote tracks associated with the P2P
  1788. * connection.
  1789. * @private
  1790. */
  1791. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  1792. this._removeRemoteTracks(
  1793. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  1794. };
  1795. /**
  1796. * Generates fake "remote track removed" events for given Jingle session.
  1797. * @param {string} sessionNickname the session's nickname which will appear in
  1798. * log messages.
  1799. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  1800. * @private
  1801. */
  1802. JitsiConference.prototype._removeRemoteTracks
  1803. = function(sessionNickname, remoteTracks) {
  1804. for (const track of remoteTracks) {
  1805. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  1806. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  1807. }
  1808. };
  1809. /**
  1810. * Resumes media transfer over the JVB connection.
  1811. * @private
  1812. */
  1813. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  1814. logger.info('Resuming media transfer over the JVB connection...');
  1815. this.jvbJingleSession.setMediaTransferActive(true).then(
  1816. () => {
  1817. logger.info('Resumed media transfer over the JVB connection!');
  1818. },
  1819. error => {
  1820. logger.error(
  1821. 'Failed to resume media transfer over the JVB connection:',
  1822. error);
  1823. });
  1824. };
  1825. /**
  1826. * Sets new P2P status and updates some events/states hijacked from
  1827. * the <tt>JitsiConference</tt>.
  1828. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  1829. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  1830. * @private
  1831. */
  1832. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  1833. if (this.p2p === newStatus) {
  1834. logger.error(`Called _setP2PStatus with the same status: ${newStatus}`);
  1835. return;
  1836. }
  1837. this.p2p = newStatus;
  1838. if (newStatus) {
  1839. logger.info('Peer to peer connection established!');
  1840. } else {
  1841. logger.info('Peer to peer connection closed!');
  1842. }
  1843. // Put the JVB connection on hold/resume
  1844. if (this.jvbJingleSession) {
  1845. this.statistics.sendConnectionResumeOrHoldEvent(
  1846. this.jvbJingleSession.peerconnection, !newStatus);
  1847. }
  1848. // Clear dtmfManager, so that it can be recreated with new connection
  1849. this.dtmfManager = null;
  1850. // Update P2P status
  1851. this.eventEmitter.emit(
  1852. JitsiConferenceEvents.P2P_STATUS,
  1853. this,
  1854. this.p2p);
  1855. // Refresh connection interrupted/restored
  1856. this.eventEmitter.emit(
  1857. this.isConnectionInterrupted()
  1858. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  1859. : JitsiConferenceEvents.CONNECTION_RESTORED);
  1860. };
  1861. /**
  1862. * Starts new P2P session.
  1863. * @param {string} peerJid the JID of the remote participant
  1864. * @private
  1865. */
  1866. JitsiConference.prototype._startP2PSession = function(peerJid) {
  1867. this._maybeClearDeferredStartP2P();
  1868. if (this.p2pJingleSession) {
  1869. logger.error('P2P session already started!');
  1870. return;
  1871. }
  1872. this.isP2PConnectionInterrupted = false;
  1873. this.p2pJingleSession
  1874. = this.xmpp.connection.jingle.newP2PJingleSession(
  1875. this.room.myroomjid,
  1876. peerJid);
  1877. this.p2pJingleSession.setSSRCOwnerJid(this.room.myroomjid);
  1878. logger.info('Created new P2P JingleSession', this.room.myroomjid, peerJid);
  1879. this.p2pJingleSession.initialize(true /* initiator */, this.room, this.rtc);
  1880. logger.info('Starting CallStats for P2P connection...');
  1881. this.statistics.startCallStats(
  1882. this.p2pJingleSession.peerconnection,
  1883. Strophe.getResourceFromJid(this.p2pJingleSession.peerjid));
  1884. // NOTE one may consider to start P2P with the local tracks detached,
  1885. // but no data will be sent until ICE succeeds anyway. And we switch
  1886. // immediately once the P2P ICE connects.
  1887. const localTracks = this.getLocalTracks();
  1888. this.p2pJingleSession.invite(localTracks);
  1889. };
  1890. /**
  1891. * Suspends media transfer over the JVB connection.
  1892. * @private
  1893. */
  1894. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  1895. logger.info('Suspending media transfer over the JVB connection...');
  1896. this.jvbJingleSession.setMediaTransferActive(false).then(
  1897. () => {
  1898. logger.info('Suspended media transfer over the JVB connection !');
  1899. },
  1900. error => {
  1901. logger.error(
  1902. 'Failed to suspend media transfer over the JVB connection:',
  1903. error);
  1904. });
  1905. };
  1906. /**
  1907. * Method when called will decide whether it's the time to start or stop
  1908. * the P2P session.
  1909. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  1910. * originates from the user left event.
  1911. * @private
  1912. */
  1913. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  1914. if (!this.options.config.enableP2P || !RTCBrowserType.isP2PSupported()) {
  1915. logger.info('Auto P2P disabled');
  1916. return;
  1917. }
  1918. const peers = this.getParticipants();
  1919. const peerCount = peers.length;
  1920. const isModerator = this.isModerator();
  1921. // FIXME 1 peer and it must *support* P2P switching
  1922. const shouldBeInP2P = peerCount === 1;
  1923. logger.debug(
  1924. `P2P? isModerator: ${isModerator
  1925. }, peerCount: ${peerCount} => ${shouldBeInP2P}`);
  1926. // Clear deferred "start P2P" task
  1927. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  1928. this._maybeClearDeferredStartP2P();
  1929. }
  1930. // Start peer to peer session
  1931. if (isModerator && !this.p2pJingleSession && shouldBeInP2P) {
  1932. const peer = peerCount && peers[0];
  1933. // Everyone is a moderator ?
  1934. if (isModerator && peer.getRole() === 'moderator') {
  1935. const myId = this.myUserId();
  1936. const peersId = peer.getId();
  1937. if (myId > peersId) {
  1938. logger.debug(
  1939. 'Everyone\'s a moderator - '
  1940. + 'the other peer should start P2P', myId, peersId);
  1941. return;
  1942. } else if (myId === peersId) {
  1943. logger.error('The same IDs ? ', myId, peersId);
  1944. return;
  1945. }
  1946. }
  1947. const jid = peer.getJid();
  1948. if (userLeftEvent) {
  1949. if (this.deferredStartP2PTask) {
  1950. logger.error('Deferred start P2P task\'s been set already!');
  1951. return;
  1952. }
  1953. logger.info(
  1954. `Will start P2P with: ${jid
  1955. } after ${this.backToP2PDelay} seconds...`);
  1956. this.deferredStartP2PTask = setTimeout(
  1957. this._startP2PSession.bind(this, jid),
  1958. this.backToP2PDelay * 1000);
  1959. } else {
  1960. logger.info(`Will start P2P with: ${jid}`);
  1961. this._startP2PSession(jid);
  1962. }
  1963. } else if (isModerator && this.p2pJingleSession && !shouldBeInP2P) {
  1964. logger.info(`Will stop P2P with: ${this.p2pJingleSession.peerjid}`);
  1965. // Log that there will be a switch back to the JVB connection
  1966. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  1967. Statistics.sendEventToAll('p2p.switch_to_jvb');
  1968. }
  1969. this._stopP2PSession();
  1970. }
  1971. };
  1972. /**
  1973. * Stops the current P2P session.
  1974. * @param {string} [reason="success"] one of the Jingle "reason" element
  1975. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  1976. * @param {string} [reasonDescription="Turing off P2P session"] text
  1977. * description that will be included in the session terminate message
  1978. * @private
  1979. */
  1980. JitsiConference.prototype._stopP2PSession
  1981. = function(reason, reasonDescription) {
  1982. if (!this.p2pJingleSession) {
  1983. logger.error('No P2P session to be stopped!');
  1984. return;
  1985. }
  1986. const wasP2PEstablished = this.isP2PActive();
  1987. // Swap remote tracks, but only if the P2P has been fully established
  1988. if (wasP2PEstablished) {
  1989. this._resumeMediaTransferForJvbConnection();
  1990. // Remove remote P2P tracks
  1991. this._removeRemoteP2PTracks();
  1992. }
  1993. // Stop P2P stats
  1994. logger.info('Stopping remote stats for P2P connection');
  1995. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  1996. logger.info('Stopping CallStats for P2P connection');
  1997. this.statistics.stopCallStats(
  1998. this.p2pJingleSession.peerconnection);
  1999. if (JingleSessionState.ENDED !== this.p2pJingleSession.state) {
  2000. this.p2pJingleSession.terminate(
  2001. reason ? reason : 'success',
  2002. reasonDescription
  2003. ? reasonDescription : 'Turing off P2P session',
  2004. () => {
  2005. logger.info('P2P session terminate RESULT');
  2006. },
  2007. error => {
  2008. logger.warn(
  2009. 'An error occurred while trying to terminate'
  2010. + ' P2P Jingle session', error);
  2011. });
  2012. }
  2013. this.p2pJingleSession = null;
  2014. // Update P2P status and other affected events/states
  2015. this._setP2PStatus(false);
  2016. if (wasP2PEstablished) {
  2017. // Add back remote JVB tracks
  2018. if (this.jvbJingleSession) {
  2019. this._addRemoteJVBTracks();
  2020. } else {
  2021. logger.info('Not adding remote JVB tracks - no session yet');
  2022. }
  2023. }
  2024. };
  2025. /**
  2026. * Checks whether or not the conference is currently in the peer to peer mode.
  2027. * Being in peer to peer mode means that the direct connection has been
  2028. * established and the P2P connection is being used for media transmission.
  2029. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2030. */
  2031. JitsiConference.prototype.isP2PActive = function() {
  2032. return this.p2p;
  2033. };
  2034. /**
  2035. * Returns the current ICE state of the P2P connection.
  2036. * NOTE: method is used by the jitsi-meet-torture tests.
  2037. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2038. * no P2P connection.
  2039. */
  2040. JitsiConference.prototype.getP2PConnectionState = function() {
  2041. if (this.isP2PActive()) {
  2042. return this.p2pJingleSession.peerconnection.getConnectionState();
  2043. }
  2044. return null;
  2045. };
  2046. /**
  2047. * Manually starts new P2P session (should be used only in the tests).
  2048. */
  2049. JitsiConference.prototype.startP2PSession = function() {
  2050. const peers = this.getParticipants();
  2051. // Start peer to peer session
  2052. if (peers.length === 1) {
  2053. const peerJid = peers[0].getJid();
  2054. this._startP2PSession(peerJid);
  2055. } else {
  2056. throw new Error(
  2057. 'There must be exactly 1 participant to start the P2P session !');
  2058. }
  2059. };
  2060. /**
  2061. * Manually stops the current P2P session (should be used only in the tests)
  2062. */
  2063. JitsiConference.prototype.stopP2PSession = function() {
  2064. this._stopP2PSession();
  2065. };
  2066. /**
  2067. * Get a summary of how long current participants have been the dominant speaker
  2068. * @returns {object}
  2069. */
  2070. JitsiConference.prototype.getSpeakerStats = function() {
  2071. return this.speakerStatsCollector.getStats();
  2072. };
  2073. /**
  2074. * Get video SIP GW handler, if missing will create one.
  2075. *
  2076. * @returns {VideoSIPGW} video SIP GW handler.
  2077. */
  2078. JitsiConference.prototype._getVideoSIPGWHandle = function() {
  2079. if (!this.videoSIPGWHandler) {
  2080. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  2081. logger.info('Created VideoSIPGW');
  2082. }
  2083. return this.videoSIPGWHandler;
  2084. };
  2085. /**
  2086. * Checks whether video SIP GW service is available.
  2087. *
  2088. * @returns {boolean} whether video SIP GW service is available.
  2089. */
  2090. JitsiConference.prototype.isVideoSIPGWAvailable = function() {
  2091. return this._getVideoSIPGWHandle().isVideoSIPGWAvailable();
  2092. };
  2093. /**
  2094. * Creates a video SIP GW session and returns it if service is enabled. Before
  2095. * creating a session one need to check whether video SIP GW service is
  2096. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2097. * if there are available nodes to serve this request, after creating the
  2098. * session those nodes can be taken and the request about using the
  2099. * created session can fail.
  2100. *
  2101. * @param {string} sipAddress - The sip address to be used.
  2102. * @param {string} displayName - The display name to be used for this session.
  2103. * @returns {JitsiVideoSIPGWSession|null} Returns null if conference is not
  2104. * initialised and there is no room.
  2105. */
  2106. JitsiConference.prototype.createVideoSIPGWSession
  2107. = function(sipAddress, displayName) {
  2108. if (!this.room) {
  2109. return null;
  2110. }
  2111. return this._getVideoSIPGWHandle()
  2112. .createVideoSIPGWSession(sipAddress, displayName);
  2113. };