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

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