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

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