您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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