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

JitsiConference.js 92KB

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