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

JitsiConference.js 100KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183
  1. /* global __filename, $, Promise */
  2. import { Strophe } from 'strophe.js';
  3. import EventEmitter from 'events';
  4. import { getLogger } from 'jitsi-meet-logger';
  5. import isEqual from 'lodash.isequal';
  6. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  7. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  8. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  9. import JitsiParticipant from './JitsiParticipant';
  10. import JitsiTrackError from './JitsiTrackError';
  11. import * as JitsiTrackErrors from './JitsiTrackErrors';
  12. import * as JitsiTrackEvents from './JitsiTrackEvents';
  13. import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
  14. import JitsiDTMFManager from './modules/DTMF/JitsiDTMFManager';
  15. import P2PDominantSpeakerDetection from './modules/P2PDominantSpeakerDetection';
  16. import RTC from './modules/RTC/RTC';
  17. import TalkMutedDetection from './modules/TalkMutedDetection';
  18. import browser from './modules/browser';
  19. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  20. import IceFailedNotification
  21. from './modules/connectivity/IceFailedNotification';
  22. import ParticipantConnectionStatusHandler
  23. from './modules/connectivity/ParticipantConnectionStatus';
  24. import E2ePing from './modules/e2eping/e2eping';
  25. import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
  26. import RecordingManager from './modules/recording/RecordingManager';
  27. import RttMonitor from './modules/rttmonitor/rttmonitor';
  28. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  29. import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
  30. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  31. import Statistics from './modules/statistics/statistics';
  32. import Transcriber from './modules/transcription/transcriber';
  33. import GlobalOnErrorHandler from './modules/util/GlobalOnErrorHandler';
  34. import RandomUtil from './modules/util/RandomUtil';
  35. import ComponentsVersions from './modules/version/ComponentsVersions';
  36. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  37. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  38. import { JITSI_MEET_MUC_TYPE } from './modules/xmpp/xmpp';
  39. import * as MediaType from './service/RTC/MediaType';
  40. import * as RTCEvents from './service/RTC/RTCEvents';
  41. import VideoType from './service/RTC/VideoType';
  42. import {
  43. ACTION_JINGLE_RESTART,
  44. ACTION_JINGLE_SI_RECEIVED,
  45. ACTION_JINGLE_SI_TIMEOUT,
  46. ACTION_JINGLE_TERMINATE,
  47. ACTION_P2P_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. }
  1471. if (rejectReason) {
  1472. this._rejectIncomingCall(jingleSession, rejectReason);
  1473. } else {
  1474. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1475. }
  1476. };
  1477. /**
  1478. * Handles an incoming call event.
  1479. */
  1480. JitsiConference.prototype.onIncomingCall = function(
  1481. jingleSession,
  1482. jingleOffer,
  1483. now) {
  1484. // Handle incoming P2P call
  1485. if (jingleSession.isP2P) {
  1486. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1487. } else {
  1488. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1489. const description = 'Rejecting session-initiate from non-focus.';
  1490. this._rejectIncomingCall(
  1491. jingleSession, {
  1492. reason: 'security-error',
  1493. reasonDescription: description,
  1494. errorMsg: description
  1495. });
  1496. return;
  1497. }
  1498. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1499. }
  1500. };
  1501. /**
  1502. * Accepts an incoming call event for the JVB jingle session.
  1503. */
  1504. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1505. jingleSession,
  1506. jingleOffer,
  1507. now) {
  1508. // Accept incoming call
  1509. this.jvbJingleSession = jingleSession;
  1510. this.room.connectionTimes['session.initiate'] = now;
  1511. if (this.wasStopped) {
  1512. Statistics.sendAnalyticsAndLog(
  1513. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1514. }
  1515. const serverRegion
  1516. = $(jingleOffer)
  1517. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1518. .attr('region');
  1519. this.eventEmitter.emit(
  1520. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1521. serverRegion);
  1522. this._maybeClearSITimeout();
  1523. Statistics.sendAnalytics(createJingleEvent(
  1524. ACTION_JINGLE_SI_RECEIVED,
  1525. {
  1526. p2p: false,
  1527. value: now
  1528. }));
  1529. try {
  1530. jingleSession.initialize(this.room, this.rtc, this.options.config);
  1531. } catch (error) {
  1532. GlobalOnErrorHandler.callErrorHandler(error);
  1533. }
  1534. // Open a channel with the videobridge.
  1535. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1536. // Add local tracks to the session
  1537. try {
  1538. jingleSession.acceptOffer(
  1539. jingleOffer,
  1540. () => {
  1541. // If for any reason invite for the JVB session arrived after
  1542. // the P2P has been established already the media transfer needs
  1543. // to be turned off here.
  1544. if (this.isP2PActive() && this.jvbJingleSession) {
  1545. this._suspendMediaTransferForJvbConnection();
  1546. }
  1547. },
  1548. error => {
  1549. GlobalOnErrorHandler.callErrorHandler(error);
  1550. logger.error(
  1551. 'Failed to accept incoming Jingle session', error);
  1552. },
  1553. this.getLocalTracks()
  1554. );
  1555. // Start callstats as soon as peerconnection is initialized,
  1556. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1557. // happen in case if user doesn't have or denied permission to
  1558. // both camera and microphone.
  1559. logger.info('Starting CallStats for JVB connection...');
  1560. this.statistics.startCallStats(
  1561. this.jvbJingleSession.peerconnection,
  1562. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1563. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1564. } catch (e) {
  1565. GlobalOnErrorHandler.callErrorHandler(e);
  1566. logger.error(e);
  1567. }
  1568. };
  1569. /**
  1570. * Sets the BridgeChannel.
  1571. *
  1572. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1573. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1574. * BridgeChannel mode.
  1575. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1576. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1577. */
  1578. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1579. let wsUrl = null;
  1580. const webSocket
  1581. = $(offerIq)
  1582. .find('>content>transport>web-socket')
  1583. .first();
  1584. if (webSocket.length === 1) {
  1585. wsUrl = webSocket[0].getAttribute('url');
  1586. }
  1587. let bridgeChannelType;
  1588. switch (this.options.config.openBridgeChannel) {
  1589. case 'datachannel':
  1590. case true:
  1591. case undefined:
  1592. bridgeChannelType = 'datachannel';
  1593. break;
  1594. case 'websocket':
  1595. bridgeChannelType = 'websocket';
  1596. break;
  1597. }
  1598. if (bridgeChannelType === 'datachannel'
  1599. && !browser.supportsDataChannels()) {
  1600. bridgeChannelType = 'websocket';
  1601. }
  1602. if (bridgeChannelType === 'datachannel') {
  1603. this.rtc.initializeBridgeChannel(pc, null);
  1604. } else if (bridgeChannelType === 'websocket' && wsUrl) {
  1605. this.rtc.initializeBridgeChannel(null, wsUrl);
  1606. }
  1607. };
  1608. /**
  1609. * Rejects incoming Jingle call.
  1610. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1611. * @param {object} [options]
  1612. * @param {string} options.reason the name of the reason element as defined
  1613. * by Jingle
  1614. * @param {string} options.reasonDescription the reason description which will
  1615. * be included in Jingle 'session-terminate' message.
  1616. * @param {string} options.errorMsg an error message to be logged on global
  1617. * error handler
  1618. * @private
  1619. */
  1620. JitsiConference.prototype._rejectIncomingCall = function(
  1621. jingleSession,
  1622. options) {
  1623. if (options && options.errorMsg) {
  1624. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1625. }
  1626. // Terminate the jingle session with a reason
  1627. jingleSession.terminate(
  1628. null /* success callback => we don't care */,
  1629. error => {
  1630. logger.warn(
  1631. 'An error occurred while trying to terminate'
  1632. + ' invalid Jingle session', error);
  1633. }, {
  1634. reason: options && options.reason,
  1635. reasonDescription: options && options.reasonDescription,
  1636. sendSessionTerminate: true
  1637. });
  1638. };
  1639. /**
  1640. * Handles the call ended event.
  1641. * XXX is this due to the remote side terminating the Jingle session?
  1642. *
  1643. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1644. * terminated.
  1645. * @param {String} reasonCondition the Jingle reason condition.
  1646. * @param {String|null} reasonText human readable reason text which may provide
  1647. * more details about why the call has been terminated.
  1648. */
  1649. JitsiConference.prototype.onCallEnded = function(
  1650. jingleSession,
  1651. reasonCondition,
  1652. reasonText) {
  1653. logger.info(
  1654. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1655. jingleSession.isP2P}`);
  1656. if (jingleSession === this.jvbJingleSession) {
  1657. this.wasStopped = true;
  1658. Statistics.sendAnalytics(
  1659. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1660. // Stop the stats
  1661. if (this.statistics) {
  1662. this.statistics.stopRemoteStats(
  1663. this.jvbJingleSession.peerconnection);
  1664. logger.info('Stopping JVB CallStats');
  1665. this.statistics.stopCallStats(
  1666. this.jvbJingleSession.peerconnection);
  1667. }
  1668. // Current JVB JingleSession is no longer valid, so set it to null
  1669. this.jvbJingleSession = null;
  1670. // Let the RTC service do any cleanups
  1671. this.rtc.onCallEnded();
  1672. } else if (jingleSession === this.p2pJingleSession) {
  1673. // It's the responder who decides to enforce JVB mode, so that both
  1674. // initiator and responder are aware if it was intentional.
  1675. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1676. logger.info('In forced JVB 121 mode...');
  1677. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1678. } else if (reasonCondition === 'connectivity-error'
  1679. && reasonText === 'ICE FAILED') {
  1680. // It can happen that the other peer detects ICE failed and
  1681. // terminates the session, before we get the event on our side.
  1682. // But we are able to parse the reason and mark it here.
  1683. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1684. }
  1685. this._stopP2PSession();
  1686. } else {
  1687. logger.error(
  1688. 'Received onCallEnded for invalid session',
  1689. jingleSession.sid,
  1690. jingleSession.remoteJid,
  1691. reasonCondition,
  1692. reasonText);
  1693. }
  1694. };
  1695. /**
  1696. * Handles the suspend detected event. Leaves the room and fires suspended.
  1697. * @param {JingleSessionPC} jingleSession
  1698. */
  1699. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1700. if (!jingleSession.isP2P) {
  1701. this.leave();
  1702. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1703. }
  1704. };
  1705. JitsiConference.prototype.updateDTMFSupport = function() {
  1706. let somebodySupportsDTMF = false;
  1707. const participants = this.getParticipants();
  1708. // check if at least 1 participant supports DTMF
  1709. for (let i = 0; i < participants.length; i += 1) {
  1710. if (participants[i].supportsDTMF()) {
  1711. somebodySupportsDTMF = true;
  1712. break;
  1713. }
  1714. }
  1715. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1716. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1717. this.eventEmitter.emit(
  1718. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1719. somebodySupportsDTMF);
  1720. }
  1721. };
  1722. /**
  1723. * Allows to check if there is at least one user in the conference
  1724. * that supports DTMF.
  1725. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1726. */
  1727. JitsiConference.prototype.isDTMFSupported = function() {
  1728. return this.somebodySupportsDTMF;
  1729. };
  1730. /**
  1731. * Returns the local user's ID
  1732. * @return {string} local user's ID
  1733. */
  1734. JitsiConference.prototype.myUserId = function() {
  1735. return (
  1736. this.room && this.room.myroomjid
  1737. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1738. : null);
  1739. };
  1740. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1741. if (!this.dtmfManager) {
  1742. const peerConnection = this.getActivePeerConnection();
  1743. if (!peerConnection) {
  1744. logger.warn('cannot sendTones: no peer connection');
  1745. return;
  1746. }
  1747. const localAudio = this.getLocalAudioTrack();
  1748. if (!localAudio) {
  1749. logger.warn('cannot sendTones: no local audio stream');
  1750. return;
  1751. }
  1752. this.dtmfManager = new JitsiDTMFManager(localAudio, peerConnection);
  1753. }
  1754. this.dtmfManager.sendTones(tones, duration, pause);
  1755. };
  1756. /**
  1757. * Starts recording the current conference.
  1758. *
  1759. * @param {Object} options - Configuration for the recording. See
  1760. * {@link Chatroom#startRecording} for more info.
  1761. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1762. */
  1763. JitsiConference.prototype.startRecording = function(options) {
  1764. if (this.room) {
  1765. return this.recordingManager.startRecording(options);
  1766. }
  1767. return Promise.reject(new Error('The conference is not created yet!'));
  1768. };
  1769. /**
  1770. * Stop a recording session.
  1771. *
  1772. * @param {string} sessionID - The ID of the recording session that
  1773. * should be stopped.
  1774. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1775. */
  1776. JitsiConference.prototype.stopRecording = function(sessionID) {
  1777. if (this.room) {
  1778. return this.recordingManager.stopRecording(sessionID);
  1779. }
  1780. return Promise.reject(new Error('The conference is not created yet!'));
  1781. };
  1782. /**
  1783. * Returns true if the SIP calls are supported and false otherwise
  1784. */
  1785. JitsiConference.prototype.isSIPCallingSupported = function() {
  1786. if (this.room) {
  1787. return this.room.isSIPCallingSupported();
  1788. }
  1789. return false;
  1790. };
  1791. /**
  1792. * Dials a number.
  1793. * @param number the number
  1794. */
  1795. JitsiConference.prototype.dial = function(number) {
  1796. if (this.room) {
  1797. return this.room.dial(number);
  1798. }
  1799. return new Promise((resolve, reject) => {
  1800. reject(new Error('The conference is not created yet!'));
  1801. });
  1802. };
  1803. /**
  1804. * Hangup an existing call
  1805. */
  1806. JitsiConference.prototype.hangup = function() {
  1807. if (this.room) {
  1808. return this.room.hangup();
  1809. }
  1810. return new Promise((resolve, reject) => {
  1811. reject(new Error('The conference is not created yet!'));
  1812. });
  1813. };
  1814. /**
  1815. * Starts the transcription service.
  1816. */
  1817. JitsiConference.prototype.startTranscriber = function() {
  1818. return this.dial('jitsi_meet_transcribe');
  1819. };
  1820. /**
  1821. * Stops the transcription service.
  1822. */
  1823. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  1824. /**
  1825. * Returns the phone number for joining the conference.
  1826. */
  1827. JitsiConference.prototype.getPhoneNumber = function() {
  1828. if (this.room) {
  1829. return this.room.getPhoneNumber();
  1830. }
  1831. return null;
  1832. };
  1833. /**
  1834. * Returns the pin for joining the conference with phone.
  1835. */
  1836. JitsiConference.prototype.getPhonePin = function() {
  1837. if (this.room) {
  1838. return this.room.getPhonePin();
  1839. }
  1840. return null;
  1841. };
  1842. /**
  1843. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1844. * which connection is currently active.
  1845. *
  1846. * @return {TraceablePeerConnection|null} null if there isn't any active
  1847. * <tt>TraceablePeerConnection</tt> currently available.
  1848. * @public (FIXME how to make package local ?)
  1849. */
  1850. JitsiConference.prototype.getActivePeerConnection = function() {
  1851. if (this.isP2PActive()) {
  1852. return this.p2pJingleSession.peerconnection;
  1853. }
  1854. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1855. };
  1856. /**
  1857. * Returns the connection state for the current room. Its ice connection state
  1858. * for its session.
  1859. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1860. * be converted to "connected".
  1861. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1862. * peer connection at this time.
  1863. */
  1864. JitsiConference.prototype.getConnectionState = function() {
  1865. const peerConnection = this.getActivePeerConnection();
  1866. return peerConnection ? peerConnection.getConnectionState() : null;
  1867. };
  1868. /**
  1869. * Make all new participants mute their audio/video on join.
  1870. * @param policy {Object} object with 2 boolean properties for video and audio:
  1871. * @param {boolean} audio if audio should be muted.
  1872. * @param {boolean} video if video should be muted.
  1873. */
  1874. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  1875. if (!this.isModerator()) {
  1876. return;
  1877. }
  1878. this.startMutedPolicy = policy;
  1879. this.room.removeFromPresence('startmuted');
  1880. this.room.addToPresence('startmuted', {
  1881. attributes: {
  1882. audio: policy.audio,
  1883. video: policy.video,
  1884. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  1885. }
  1886. });
  1887. this.room.sendPresence();
  1888. };
  1889. /**
  1890. * Returns current start muted policy
  1891. * @returns {Object} with 2 properties - audio and video.
  1892. */
  1893. JitsiConference.prototype.getStartMutedPolicy = function() {
  1894. return this.startMutedPolicy;
  1895. };
  1896. /**
  1897. * Check if audio is muted on join.
  1898. */
  1899. JitsiConference.prototype.isStartAudioMuted = function() {
  1900. return this.startAudioMuted;
  1901. };
  1902. /**
  1903. * Check if video is muted on join.
  1904. */
  1905. JitsiConference.prototype.isStartVideoMuted = function() {
  1906. return this.startVideoMuted;
  1907. };
  1908. /**
  1909. * Get object with internal logs.
  1910. */
  1911. JitsiConference.prototype.getLogs = function() {
  1912. const data = this.xmpp.getJingleLog();
  1913. const metadata = {};
  1914. metadata.time = new Date();
  1915. metadata.url = window.location.href;
  1916. metadata.ua = navigator.userAgent;
  1917. const log = this.xmpp.getXmppLog();
  1918. if (log) {
  1919. metadata.xmpp = log;
  1920. }
  1921. data.metadata = metadata;
  1922. return data;
  1923. };
  1924. /**
  1925. * Returns measured connectionTimes.
  1926. */
  1927. JitsiConference.prototype.getConnectionTimes = function() {
  1928. return this.room.connectionTimes;
  1929. };
  1930. /**
  1931. * Sets a property for the local participant.
  1932. */
  1933. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  1934. this.sendCommand(`jitsi_participant_${name}`, { value });
  1935. };
  1936. /**
  1937. * Removes a property for the local participant and sends the updated presence.
  1938. */
  1939. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  1940. this.removeCommand(`jitsi_participant_${name}`);
  1941. this.room.sendPresence();
  1942. };
  1943. /**
  1944. * Gets a local participant property.
  1945. *
  1946. * @return value of the local participant property if the tagName exists in the
  1947. * list of properties, otherwise returns undefined.
  1948. */
  1949. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  1950. const property = this.room.presMap.nodes.find(prop =>
  1951. prop.tagName === `jitsi_participant_${name}`
  1952. );
  1953. return property ? property.value : undefined;
  1954. };
  1955. /**
  1956. * Sends the given feedback through CallStats if enabled.
  1957. *
  1958. * @param overallFeedback an integer between 1 and 5 indicating the
  1959. * user feedback
  1960. * @param detailedFeedback detailed feedback from the user. Not yet used
  1961. * @returns {Promise} Resolves if feedback is submitted successfully.
  1962. */
  1963. JitsiConference.prototype.sendFeedback = function(
  1964. overallFeedback,
  1965. detailedFeedback) {
  1966. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  1967. };
  1968. /**
  1969. * Returns true if the callstats integration is enabled, otherwise returns
  1970. * false.
  1971. *
  1972. * @returns true if the callstats integration is enabled, otherwise returns
  1973. * false.
  1974. */
  1975. JitsiConference.prototype.isCallstatsEnabled = function() {
  1976. return this.statistics.isCallstatsEnabled();
  1977. };
  1978. /**
  1979. * Handles track attached to container (Calls associateStreamWithVideoTag method
  1980. * from statistics module)
  1981. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  1982. * @param container the container
  1983. */
  1984. JitsiConference.prototype._onTrackAttach = function(track, container) {
  1985. const isLocal = track.isLocal();
  1986. let ssrc = null;
  1987. const isP2P = track.isP2P;
  1988. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  1989. const peerConnection
  1990. = isP2P
  1991. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  1992. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  1993. if (isLocal) {
  1994. // Local tracks have SSRC stored on per peer connection basis
  1995. if (peerConnection) {
  1996. ssrc = peerConnection.getLocalSSRC(track);
  1997. }
  1998. } else {
  1999. ssrc = track.getSSRC();
  2000. }
  2001. if (!container.id || !ssrc || !peerConnection) {
  2002. return;
  2003. }
  2004. this.statistics.associateStreamWithVideoTag(
  2005. peerConnection,
  2006. ssrc,
  2007. isLocal,
  2008. remoteUserId,
  2009. track.getUsageLabel(),
  2010. container.id);
  2011. };
  2012. /**
  2013. * Logs an "application log" message.
  2014. * @param message {string} The message to log. Note that while this can be a
  2015. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2016. * log valid JSON strings, with an "id" field used for distinguishing between
  2017. * message types. E.g.: {id: "recorder_status", status: "off"}
  2018. */
  2019. JitsiConference.prototype.sendApplicationLog = function(message) {
  2020. Statistics.sendLog(message);
  2021. };
  2022. /**
  2023. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2024. * focus.
  2025. * @param mucJid the full MUC address of the user to be checked.
  2026. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2027. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2028. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2029. */
  2030. JitsiConference.prototype._isFocus = function(mucJid) {
  2031. return this.room ? this.room.isFocus(mucJid) : null;
  2032. };
  2033. /**
  2034. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2035. */
  2036. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2037. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2038. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2039. };
  2040. /**
  2041. * Sends a message via the data channel.
  2042. * @param to {string} the id of the endpoint that should receive the message.
  2043. * If "" the message will be sent to all participants.
  2044. * @param payload {object} the payload of the message.
  2045. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2046. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2047. */
  2048. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2049. this.rtc.sendChannelMessage(to, payload);
  2050. };
  2051. /**
  2052. * Sends a broadcast message via the data channel.
  2053. * @param payload {object} the payload of the message.
  2054. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2055. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2056. */
  2057. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2058. this.sendEndpointMessage('', payload);
  2059. };
  2060. /**
  2061. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2062. * broadcasts it to all endpoints in the conference.
  2063. * @param {string} to The ID of the endpoint/participant which is to receive
  2064. * the message, or '' to broadcast the message to all endpoints in the
  2065. * conference.
  2066. * @param {string|object} message the message to send. If this is of type
  2067. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2068. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2069. * JSON before being sent.
  2070. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2071. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2072. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2073. */
  2074. JitsiConference.prototype.sendMessage = function(
  2075. message,
  2076. to = '',
  2077. sendThroughVideobridge = false) {
  2078. const messageType = typeof message;
  2079. // Through videobridge we support only objects. Through XMPP we support
  2080. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2081. // regular chat messages).
  2082. if (messageType !== 'object'
  2083. && (sendThroughVideobridge || messageType !== 'string')) {
  2084. logger.error(`Can not send a message of type ${messageType}`);
  2085. return;
  2086. }
  2087. if (sendThroughVideobridge) {
  2088. this.sendEndpointMessage(to, message);
  2089. } else {
  2090. let messageToSend = message;
  2091. // Name of packet extension of message stanza to send the required
  2092. // message in.
  2093. let elementName = 'body';
  2094. if (messageType === 'object') {
  2095. elementName = 'json-message';
  2096. // Mark as valid JSON message if not already
  2097. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2098. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2099. }
  2100. try {
  2101. messageToSend = JSON.stringify(messageToSend);
  2102. } catch (e) {
  2103. logger.error('Can not send a message, stringify failed: ', e);
  2104. return;
  2105. }
  2106. }
  2107. if (to) {
  2108. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2109. } else {
  2110. // Broadcast
  2111. this.sendTextMessage(messageToSend, elementName);
  2112. }
  2113. }
  2114. };
  2115. JitsiConference.prototype.isConnectionInterrupted = function() {
  2116. return this.isP2PActive()
  2117. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2118. };
  2119. /**
  2120. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2121. * @param {JingleSessionPC} session
  2122. * @private
  2123. */
  2124. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2125. if (session.isP2P) {
  2126. this.isP2PConnectionInterrupted = true;
  2127. } else {
  2128. this.isJvbConnectionInterrupted = true;
  2129. }
  2130. if (session.isP2P === this.isP2PActive()) {
  2131. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2132. }
  2133. };
  2134. /**
  2135. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2136. * @param {JingleSessionPC} session
  2137. * @private
  2138. */
  2139. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2140. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2141. // eventually come up with the new offer (at least for the time being).
  2142. if (session.isP2P) {
  2143. // Add p2pFailed property to analytics to distinguish, between "good"
  2144. // and "bad" connection
  2145. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2146. if (this.p2pJingleSession) {
  2147. Statistics.sendAnalyticsAndLog(
  2148. createP2PEvent(
  2149. ACTION_P2P_FAILED,
  2150. {
  2151. initiator: this.p2pJingleSession.isInitiator
  2152. }));
  2153. }
  2154. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2155. } else if (session && this.jvbJingleSession === session) {
  2156. if (this.xmpp.isPingSupported()) {
  2157. this._delayedIceFailed = new IceFailedNotification(this);
  2158. this._delayedIceFailed.start(session);
  2159. } else {
  2160. // Let Jicofo know that the JVB's ICE connection has failed
  2161. logger.info('PING not supported - sending ICE failed immediately');
  2162. session.sendIceFailedNotification();
  2163. }
  2164. }
  2165. };
  2166. /**
  2167. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2168. * @param {JingleSessionPC} session
  2169. * @private
  2170. */
  2171. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2172. if (session.isP2P) {
  2173. this.isP2PConnectionInterrupted = false;
  2174. } else {
  2175. this.isJvbConnectionInterrupted = false;
  2176. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2177. }
  2178. if (session.isP2P === this.isP2PActive()) {
  2179. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2180. }
  2181. };
  2182. /**
  2183. * Accept incoming P2P Jingle call.
  2184. * @param {JingleSessionPC} jingleSession the session instance
  2185. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2186. * @private
  2187. */
  2188. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2189. jingleSession,
  2190. jingleOffer) {
  2191. this.isP2PConnectionInterrupted = false;
  2192. // Accept the offer
  2193. this.p2pJingleSession = jingleSession;
  2194. this.p2pJingleSession.initialize(this.room, this.rtc, this.options.config);
  2195. logger.info('Starting CallStats for P2P connection...');
  2196. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2197. if (this.options.config.enableStatsID) {
  2198. const participant = this.participants[remoteID];
  2199. if (participant) {
  2200. remoteID = participant.getStatsID() || remoteID;
  2201. }
  2202. }
  2203. this.statistics.startCallStats(
  2204. this.p2pJingleSession.peerconnection,
  2205. remoteID);
  2206. const localTracks = this.getLocalTracks();
  2207. this.p2pJingleSession.acceptOffer(
  2208. jingleOffer,
  2209. () => {
  2210. logger.debug('Got RESULT for P2P "session-accept"');
  2211. },
  2212. error => {
  2213. logger.error(
  2214. 'Failed to accept incoming P2P Jingle session', error);
  2215. },
  2216. localTracks);
  2217. };
  2218. /**
  2219. * Adds remote tracks to the conference associated with the JVB session.
  2220. * @private
  2221. */
  2222. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2223. this._addRemoteTracks(
  2224. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2225. };
  2226. /**
  2227. * Adds remote tracks to the conference associated with the P2P session.
  2228. * @private
  2229. */
  2230. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2231. this._addRemoteTracks(
  2232. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2233. };
  2234. /**
  2235. * Generates fake "remote track added" events for given Jingle session.
  2236. * @param {string} logName the session's nickname which will appear in log
  2237. * messages.
  2238. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2239. * @private
  2240. */
  2241. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2242. for (const track of remoteTracks) {
  2243. logger.info(`Adding remote ${logName} track: ${track}`);
  2244. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_ADDED, track);
  2245. }
  2246. };
  2247. /**
  2248. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2249. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2250. * the P2P connection if the event comes from the P2P session.
  2251. * @param {JingleSessionPC} jingleSession the session instance.
  2252. * @private
  2253. */
  2254. JitsiConference.prototype._onIceConnectionEstablished = function(
  2255. jingleSession) {
  2256. if (this.p2pJingleSession !== null) {
  2257. // store the establishment time of the p2p session as a field of the
  2258. // JitsiConference because the p2pJingleSession might get disposed (thus
  2259. // the value is lost).
  2260. this.p2pEstablishmentDuration
  2261. = this.p2pJingleSession.establishmentDuration;
  2262. }
  2263. if (this.jvbJingleSession !== null) {
  2264. this.jvbEstablishmentDuration
  2265. = this.jvbJingleSession.establishmentDuration;
  2266. }
  2267. let done = false;
  2268. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2269. // We don't care about the JVB case, there's nothing to be done
  2270. if (!jingleSession.isP2P) {
  2271. done = true;
  2272. } else if (this.p2pJingleSession !== jingleSession) {
  2273. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2274. done = true;
  2275. } else if (!jingleSession.isInitiator
  2276. && typeof forceJVB121Ratio === 'number'
  2277. && Math.random() < forceJVB121Ratio) {
  2278. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2279. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2280. this._stopP2PSession('decline', 'force JVB121');
  2281. done = true;
  2282. }
  2283. if (!isNaN(this.p2pEstablishmentDuration)
  2284. && !isNaN(this.jvbEstablishmentDuration)) {
  2285. const establishmentDurationDiff
  2286. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2287. Statistics.sendAnalytics(
  2288. ICE_ESTABLISHMENT_DURATION_DIFF,
  2289. { value: establishmentDurationDiff });
  2290. }
  2291. if (jingleSession.isP2P === this.isP2PActive()) {
  2292. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2293. }
  2294. if (done) {
  2295. return;
  2296. }
  2297. // Update P2P status and emit events
  2298. this._setP2PStatus(true);
  2299. // Remove remote tracks
  2300. if (this.jvbJingleSession) {
  2301. this._removeRemoteJVBTracks();
  2302. } else {
  2303. logger.info('Not removing remote JVB tracks - no session yet');
  2304. }
  2305. this._addRemoteP2PTracks();
  2306. // Stop media transfer over the JVB connection
  2307. if (this.jvbJingleSession) {
  2308. this._suspendMediaTransferForJvbConnection();
  2309. }
  2310. logger.info('Starting remote stats with p2p connection');
  2311. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2312. Statistics.sendAnalyticsAndLog(
  2313. createP2PEvent(
  2314. ACTION_P2P_ESTABLISHED,
  2315. {
  2316. initiator: this.p2pJingleSession.isInitiator
  2317. }));
  2318. };
  2319. /**
  2320. * Called when the chat room reads a new list of properties from jicofo's
  2321. * presence. The properties may have changed, but they don't have to.
  2322. *
  2323. * @param {Object} properties - The properties keyed by the property name
  2324. * ('key').
  2325. * @private
  2326. */
  2327. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2328. const changed = !isEqual(properties, this.properties);
  2329. this.properties = properties;
  2330. if (changed) {
  2331. this.eventEmitter.emit(
  2332. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2333. this.properties);
  2334. // Some of the properties need to be added to analytics events.
  2335. const analyticsKeys = [
  2336. // The number of jitsi-videobridge instances currently used for the
  2337. // conference.
  2338. 'bridge-count',
  2339. // The conference creation time (set by jicofo).
  2340. 'created-ms',
  2341. 'octo-enabled'
  2342. ];
  2343. analyticsKeys.forEach(key => {
  2344. if (properties[key] !== undefined) {
  2345. Statistics.analytics.addPermanentProperties({
  2346. [key.replace('-', '_')]: properties[key]
  2347. });
  2348. }
  2349. });
  2350. }
  2351. };
  2352. /**
  2353. * Gets a conference property with a given key.
  2354. *
  2355. * @param {string} key - The key.
  2356. * @returns {*} The value
  2357. */
  2358. JitsiConference.prototype.getProperty = function(key) {
  2359. return this.properties[key];
  2360. };
  2361. /**
  2362. * Clears the deferred start P2P task if it has been scheduled.
  2363. * @private
  2364. */
  2365. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2366. if (this.deferredStartP2PTask) {
  2367. logger.info('Cleared deferred start P2P task');
  2368. clearTimeout(this.deferredStartP2PTask);
  2369. this.deferredStartP2PTask = null;
  2370. }
  2371. };
  2372. /**
  2373. * Removes from the conference remote tracks associated with the JVB
  2374. * connection.
  2375. * @private
  2376. */
  2377. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2378. this._removeRemoteTracks(
  2379. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2380. };
  2381. /**
  2382. * Removes from the conference remote tracks associated with the P2P
  2383. * connection.
  2384. * @private
  2385. */
  2386. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2387. this._removeRemoteTracks(
  2388. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2389. };
  2390. /**
  2391. * Generates fake "remote track removed" events for given Jingle session.
  2392. * @param {string} sessionNickname the session's nickname which will appear in
  2393. * log messages.
  2394. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2395. * @private
  2396. */
  2397. JitsiConference.prototype._removeRemoteTracks = function(
  2398. sessionNickname,
  2399. remoteTracks) {
  2400. for (const track of remoteTracks) {
  2401. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2402. this.rtc.eventEmitter.emit(RTCEvents.REMOTE_TRACK_REMOVED, track);
  2403. }
  2404. };
  2405. /**
  2406. * Resumes media transfer over the JVB connection.
  2407. * @private
  2408. */
  2409. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2410. logger.info('Resuming media transfer over the JVB connection...');
  2411. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2412. () => {
  2413. logger.info('Resumed media transfer over the JVB connection!');
  2414. },
  2415. error => {
  2416. logger.error(
  2417. 'Failed to resume media transfer over the JVB connection:',
  2418. error);
  2419. });
  2420. };
  2421. /**
  2422. * Sets new P2P status and updates some events/states hijacked from
  2423. * the <tt>JitsiConference</tt>.
  2424. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2425. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2426. * @private
  2427. */
  2428. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2429. if (this.p2p === newStatus) {
  2430. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2431. return;
  2432. }
  2433. this.p2p = newStatus;
  2434. if (newStatus) {
  2435. logger.info('Peer to peer connection established!');
  2436. // When we end up in a valid P2P session need to reset the properties
  2437. // in case they have persisted, after session with another peer.
  2438. Statistics.analytics.addPermanentProperties({
  2439. p2pFailed: false,
  2440. forceJvb121: false
  2441. });
  2442. // Sync up video transfer active in case p2pJingleSession not existed
  2443. // when the lastN value was being adjusted.
  2444. const isVideoActive = this.rtc.getLastN() !== 0;
  2445. this.p2pJingleSession
  2446. .setMediaTransferActive(true, isVideoActive)
  2447. .catch(error => {
  2448. logger.error(
  2449. 'Failed to sync up P2P video transfer status'
  2450. + `(${isVideoActive})`, error);
  2451. });
  2452. } else {
  2453. logger.info('Peer to peer connection closed!');
  2454. }
  2455. // Put the JVB connection on hold/resume
  2456. if (this.jvbJingleSession) {
  2457. this.statistics.sendConnectionResumeOrHoldEvent(
  2458. this.jvbJingleSession.peerconnection, !newStatus);
  2459. }
  2460. // Clear dtmfManager, so that it can be recreated with new connection
  2461. this.dtmfManager = null;
  2462. // Update P2P status
  2463. this.eventEmitter.emit(
  2464. JitsiConferenceEvents.P2P_STATUS,
  2465. this,
  2466. this.p2p);
  2467. // Refresh connection interrupted/restored
  2468. this.eventEmitter.emit(
  2469. this.isConnectionInterrupted()
  2470. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2471. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2472. };
  2473. /**
  2474. * Starts new P2P session.
  2475. * @param {string} remoteJid the JID of the remote participant
  2476. * @private
  2477. */
  2478. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2479. this._maybeClearDeferredStartP2P();
  2480. if (this.p2pJingleSession) {
  2481. logger.error('P2P session already started!');
  2482. return;
  2483. }
  2484. this.isP2PConnectionInterrupted = false;
  2485. this.p2pJingleSession
  2486. = this.xmpp.connection.jingle.newP2PJingleSession(
  2487. this.room.myroomjid,
  2488. remoteJid);
  2489. logger.info(
  2490. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2491. this.p2pJingleSession.initialize(this.room, this.rtc, this.options.config);
  2492. logger.info('Starting CallStats for P2P connection...');
  2493. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2494. if (this.options.config.enableStatsID) {
  2495. const participant = this.participants[remoteID];
  2496. if (participant) {
  2497. remoteID = participant.getStatsID() || remoteID;
  2498. }
  2499. }
  2500. this.statistics.startCallStats(
  2501. this.p2pJingleSession.peerconnection,
  2502. remoteID);
  2503. // NOTE one may consider to start P2P with the local tracks detached,
  2504. // but no data will be sent until ICE succeeds anyway. And we switch
  2505. // immediately once the P2P ICE connects.
  2506. const localTracks = this.getLocalTracks();
  2507. this.p2pJingleSession.invite(localTracks);
  2508. };
  2509. /**
  2510. * Suspends media transfer over the JVB connection.
  2511. * @private
  2512. */
  2513. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2514. logger.info('Suspending media transfer over the JVB connection...');
  2515. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2516. () => {
  2517. logger.info('Suspended media transfer over the JVB connection !');
  2518. },
  2519. error => {
  2520. logger.error(
  2521. 'Failed to suspend media transfer over the JVB connection:',
  2522. error);
  2523. });
  2524. };
  2525. /**
  2526. * Method when called will decide whether it's the time to start or stop
  2527. * the P2P session.
  2528. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2529. * originates from the user left event.
  2530. * @private
  2531. */
  2532. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2533. if (!browser.supportsP2P()
  2534. || !this.isP2PEnabled()
  2535. || this.isP2PTestModeEnabled()) {
  2536. logger.info('Auto P2P disabled');
  2537. return;
  2538. }
  2539. const peers = this.getParticipants();
  2540. const peerCount = peers.length;
  2541. const isModerator = this.isModerator();
  2542. const hasBotPeer
  2543. = peers.find(p => p._botType === 'poltergeist') !== undefined;
  2544. // FIXME 1 peer and it must *support* P2P switching
  2545. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2546. logger.debug(
  2547. `P2P? isModerator: ${isModerator}, peerCount: ${
  2548. peerCount}, hasBotPeer: ${hasBotPeer} => ${
  2549. shouldBeInP2P}`);
  2550. // Clear deferred "start P2P" task
  2551. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2552. this._maybeClearDeferredStartP2P();
  2553. }
  2554. // Start peer to peer session
  2555. if (!this.p2pJingleSession && shouldBeInP2P) {
  2556. const peer = peerCount && peers[0];
  2557. const myId = this.myUserId();
  2558. const peersId = peer.getId();
  2559. if (myId > peersId) {
  2560. logger.debug(
  2561. 'I\'m the bigger peersId - '
  2562. + 'the other peer should start P2P', myId, peersId);
  2563. return;
  2564. } else if (myId === peersId) {
  2565. logger.error('The same IDs ? ', myId, peersId);
  2566. return;
  2567. }
  2568. const jid = peer.getJid();
  2569. if (userLeftEvent) {
  2570. if (this.deferredStartP2PTask) {
  2571. logger.error('Deferred start P2P task\'s been set already!');
  2572. return;
  2573. }
  2574. logger.info(
  2575. `Will start P2P with: ${jid} after ${
  2576. this.backToP2PDelay} seconds...`);
  2577. this.deferredStartP2PTask = setTimeout(
  2578. this._startP2PSession.bind(this, jid),
  2579. this.backToP2PDelay * 1000);
  2580. } else {
  2581. logger.info(`Will start P2P with: ${jid}`);
  2582. this._startP2PSession(jid);
  2583. }
  2584. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2585. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2586. // Log that there will be a switch back to the JVB connection
  2587. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2588. Statistics.sendAnalyticsAndLog(
  2589. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2590. }
  2591. this._stopP2PSession();
  2592. }
  2593. };
  2594. /**
  2595. * Stops the current P2P session.
  2596. * @param {string} [reason="success"] one of the Jingle "reason" element
  2597. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2598. * @param {string} [reasonDescription="Turing off P2P session"] text
  2599. * description that will be included in the session terminate message
  2600. * @private
  2601. */
  2602. JitsiConference.prototype._stopP2PSession = function(
  2603. reason,
  2604. reasonDescription) {
  2605. if (!this.p2pJingleSession) {
  2606. logger.error('No P2P session to be stopped!');
  2607. return;
  2608. }
  2609. const wasP2PEstablished = this.isP2PActive();
  2610. // Swap remote tracks, but only if the P2P has been fully established
  2611. if (wasP2PEstablished) {
  2612. if (this.jvbJingleSession) {
  2613. this._resumeMediaTransferForJvbConnection();
  2614. }
  2615. // Remove remote P2P tracks
  2616. this._removeRemoteP2PTracks();
  2617. }
  2618. // Stop P2P stats
  2619. logger.info('Stopping remote stats for P2P connection');
  2620. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2621. logger.info('Stopping CallStats for P2P connection');
  2622. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2623. this.p2pJingleSession.terminate(
  2624. () => {
  2625. logger.info('P2P session terminate RESULT');
  2626. },
  2627. error => {
  2628. // Because both initiator and responder are simultaneously
  2629. // terminating their JingleSessions in case of the 'to JVB switch'
  2630. // when 3rd participant joins, both will dispose their sessions and
  2631. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2632. // want to log this as an error since it's expected behaviour.
  2633. //
  2634. // We want them both to terminate, because in case of initiator's
  2635. // crash the responder would stay in P2P mode until ICE fails which
  2636. // could take up to 20 seconds.
  2637. //
  2638. // NOTE lack of 'reason' is considered as graceful session terminate
  2639. // where both initiator and responder terminate their sessions
  2640. // simultaneously.
  2641. if (reason) {
  2642. logger.error(
  2643. 'An error occurred while trying to terminate'
  2644. + ' P2P Jingle session', error);
  2645. }
  2646. }, {
  2647. reason: reason ? reason : 'success',
  2648. reasonDescription: reasonDescription
  2649. ? reasonDescription : 'Turing off P2P session',
  2650. sendSessionTerminate: this.room
  2651. && this.getParticipantById(
  2652. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2653. });
  2654. this.p2pJingleSession = null;
  2655. // Update P2P status and other affected events/states
  2656. this._setP2PStatus(false);
  2657. if (wasP2PEstablished) {
  2658. // Add back remote JVB tracks
  2659. if (this.jvbJingleSession) {
  2660. this._addRemoteJVBTracks();
  2661. } else {
  2662. logger.info('Not adding remote JVB tracks - no session yet');
  2663. }
  2664. }
  2665. };
  2666. /**
  2667. * Checks whether or not the conference is currently in the peer to peer mode.
  2668. * Being in peer to peer mode means that the direct connection has been
  2669. * established and the P2P connection is being used for media transmission.
  2670. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2671. */
  2672. JitsiConference.prototype.isP2PActive = function() {
  2673. return this.p2p;
  2674. };
  2675. /**
  2676. * Returns the current ICE state of the P2P connection.
  2677. * NOTE: method is used by the jitsi-meet-torture tests.
  2678. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2679. * no P2P connection.
  2680. */
  2681. JitsiConference.prototype.getP2PConnectionState = function() {
  2682. if (this.isP2PActive()) {
  2683. return this.p2pJingleSession.peerconnection.getConnectionState();
  2684. }
  2685. return null;
  2686. };
  2687. /**
  2688. * Manually starts new P2P session (should be used only in the tests).
  2689. */
  2690. JitsiConference.prototype.startP2PSession = function() {
  2691. const peers = this.getParticipants();
  2692. // Start peer to peer session
  2693. if (peers.length === 1) {
  2694. const peerJid = peers[0].getJid();
  2695. this._startP2PSession(peerJid);
  2696. } else {
  2697. throw new Error(
  2698. 'There must be exactly 1 participant to start the P2P session !');
  2699. }
  2700. };
  2701. /**
  2702. * Manually stops the current P2P session (should be used only in the tests)
  2703. */
  2704. JitsiConference.prototype.stopP2PSession = function() {
  2705. this._stopP2PSession();
  2706. };
  2707. /**
  2708. * Get a summary of how long current participants have been the dominant speaker
  2709. * @returns {object}
  2710. */
  2711. JitsiConference.prototype.getSpeakerStats = function() {
  2712. return this.speakerStatsCollector.getStats();
  2713. };
  2714. /**
  2715. * Sets the maximum video size the local participant should receive from remote
  2716. * participants.
  2717. *
  2718. * @param {number} maxFrameHeightPixels the maximum frame height, in pixels,
  2719. * this receiver is willing to receive.
  2720. * @returns {void}
  2721. */
  2722. JitsiConference.prototype.setReceiverVideoConstraint = function(
  2723. maxFrameHeight) {
  2724. this.rtc.setReceiverVideoConstraint(maxFrameHeight);
  2725. };
  2726. /**
  2727. * Creates a video SIP GW session and returns it if service is enabled. Before
  2728. * creating a session one need to check whether video SIP GW service is
  2729. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2730. * if there are available nodes to serve this request, after creating the
  2731. * session those nodes can be taken and the request about using the
  2732. * created session can fail.
  2733. *
  2734. * @param {string} sipAddress - The sip address to be used.
  2735. * @param {string} displayName - The display name to be used for this session.
  2736. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2737. * initialised and there is no room.
  2738. */
  2739. JitsiConference.prototype.createVideoSIPGWSession
  2740. = function(sipAddress, displayName) {
  2741. if (!this.room) {
  2742. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2743. }
  2744. return this.videoSIPGWHandler
  2745. .createVideoSIPGWSession(sipAddress, displayName);
  2746. };