Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

JitsiConference.js 90KB

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