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

JitsiConference.js 113KB

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