Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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