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

JitsiConference.js 104KB

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