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

JitsiConference.js 95KB

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