Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 100KB

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