Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiConference.js 105KB

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