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

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