選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 77KB

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