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

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