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

JitsiConference.js 93KB

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