選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 96KB

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