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

JitsiConference.js 86KB

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