You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 98KB

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