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

JitsiConference.js 97KB

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