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

JitsiConference.js 97KB

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