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

JitsiConference.js 91KB

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