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

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