You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 80KB

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