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

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