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 102KB

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