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

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