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

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