Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

JitsiConference.js 89KB

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