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

JitsiConference.js 101KB

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