Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

JitsiConference.js 111KB

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