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

JitsiConference.js 99KB

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