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 97KB

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