modified lib-jitsi-meet dev repo
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiConference.js 112KB

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