您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 102KB

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