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

JitsiConference.js 101KB

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