您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 112KB

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