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

JitsiConference.js 101KB

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