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

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