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

JitsiConference.js 139KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133
  1. import { getLogger } from '@jitsi/logger';
  2. import $ from 'jquery';
  3. import isEqual from 'lodash.isequal';
  4. import { Strophe } from 'strophe.js';
  5. import * as JitsiConferenceErrors from './JitsiConferenceErrors';
  6. import JitsiConferenceEventManager from './JitsiConferenceEventManager';
  7. import * as JitsiConferenceEvents from './JitsiConferenceEvents';
  8. import JitsiParticipant from './JitsiParticipant';
  9. import JitsiTrackError from './JitsiTrackError';
  10. import * as JitsiTrackErrors from './JitsiTrackErrors';
  11. import * as JitsiTrackEvents from './JitsiTrackEvents';
  12. import authenticateAndUpgradeRole from './authenticateAndUpgradeRole';
  13. import { CodecSelection } from './modules/RTC/CodecSelection';
  14. import RTC from './modules/RTC/RTC';
  15. import { SS_DEFAULT_FRAME_RATE } from './modules/RTC/ScreenObtainer';
  16. import browser from './modules/browser';
  17. import ConnectionQuality from './modules/connectivity/ConnectionQuality';
  18. import IceFailedHandling from './modules/connectivity/IceFailedHandling';
  19. import * as DetectionEvents from './modules/detection/DetectionEvents';
  20. import NoAudioSignalDetection from './modules/detection/NoAudioSignalDetection';
  21. import P2PDominantSpeakerDetection from './modules/detection/P2PDominantSpeakerDetection';
  22. import VADAudioAnalyser from './modules/detection/VADAudioAnalyser';
  23. import VADNoiseDetection from './modules/detection/VADNoiseDetection';
  24. import VADTalkMutedDetection from './modules/detection/VADTalkMutedDetection';
  25. import { E2EEncryption } from './modules/e2ee/E2EEncryption';
  26. import E2ePing from './modules/e2eping/e2eping';
  27. import Jvb121EventGenerator from './modules/event/Jvb121EventGenerator';
  28. import FeatureFlags from './modules/flags/FeatureFlags';
  29. import { LiteModeContext } from './modules/litemode/LiteModeContext';
  30. import ReceiveVideoController from './modules/qualitycontrol/ReceiveVideoController';
  31. import SendVideoController from './modules/qualitycontrol/SendVideoController';
  32. import RecordingManager from './modules/recording/RecordingManager';
  33. import Settings from './modules/settings/Settings';
  34. import AudioOutputProblemDetector from './modules/statistics/AudioOutputProblemDetector';
  35. import AvgRTPStatsReporter from './modules/statistics/AvgRTPStatsReporter';
  36. import LocalStatsCollector from './modules/statistics/LocalStatsCollector';
  37. import SpeakerStatsCollector from './modules/statistics/SpeakerStatsCollector';
  38. import Statistics from './modules/statistics/statistics';
  39. import EventEmitter from './modules/util/EventEmitter';
  40. import { safeSubtract } from './modules/util/MathUtil';
  41. import RandomUtil from './modules/util/RandomUtil';
  42. import ComponentsVersions from './modules/version/ComponentsVersions';
  43. import VideoSIPGW from './modules/videosipgw/VideoSIPGW';
  44. import * as VideoSIPGWConstants from './modules/videosipgw/VideoSIPGWConstants';
  45. import SignalingLayerImpl from './modules/xmpp/SignalingLayerImpl';
  46. import {
  47. FEATURE_E2EE,
  48. FEATURE_JIGASI,
  49. JITSI_MEET_MUC_TYPE
  50. } from './modules/xmpp/xmpp';
  51. import { BridgeVideoType } from './service/RTC/BridgeVideoType';
  52. import { CodecMimeType } from './service/RTC/CodecMimeType';
  53. import { MediaType } from './service/RTC/MediaType';
  54. import RTCEvents from './service/RTC/RTCEvents';
  55. import { SignalingEvents } from './service/RTC/SignalingEvents';
  56. import { getMediaTypeFromSourceName, getSourceNameForJitsiTrack } from './service/RTC/SignalingLayer';
  57. import { VideoType } from './service/RTC/VideoType';
  58. import {
  59. ACTION_JINGLE_RESTART,
  60. ACTION_JINGLE_SI_RECEIVED,
  61. ACTION_JINGLE_SI_TIMEOUT,
  62. ACTION_JINGLE_TERMINATE,
  63. ACTION_P2P_DECLINED,
  64. ACTION_P2P_ESTABLISHED,
  65. ACTION_P2P_FAILED,
  66. ACTION_P2P_SWITCH_TO_JVB,
  67. ICE_ESTABLISHMENT_DURATION_DIFF,
  68. createConferenceEvent,
  69. createJingleEvent,
  70. createP2PEvent
  71. } from './service/statistics/AnalyticsEvents';
  72. import { XMPPEvents } from './service/xmpp/XMPPEvents';
  73. const logger = getLogger(__filename);
  74. /**
  75. * How long since Jicofo is supposed to send a session-initiate, before
  76. * {@link ACTION_JINGLE_SI_TIMEOUT} analytics event is sent (in ms).
  77. * @type {number}
  78. */
  79. const JINGLE_SI_TIMEOUT = 5000;
  80. /**
  81. * Checks if a given string is a valid video codec mime type.
  82. *
  83. * @param {string} codec the codec string that needs to be validated.
  84. * @returns {CodecMimeType|null} mime type if valid, null otherwise.
  85. * @private
  86. */
  87. function _getCodecMimeType(codec) {
  88. if (typeof codec === 'string') {
  89. return Object.values(CodecMimeType).find(value => value === codec.toLowerCase());
  90. }
  91. return null;
  92. }
  93. /**
  94. * Creates a JitsiConference object with the given name and properties.
  95. * Note: this constructor is not a part of the public API (objects should be
  96. * created using JitsiConnection.createConference).
  97. * @param options.config properties / settings related to the conference that
  98. * will be created.
  99. * @param options.name the name of the conference
  100. * @param options.connection the JitsiConnection object for this
  101. * JitsiConference.
  102. * @param {number} [options.config.avgRtpStatsN=15] how many samples are to be
  103. * collected by {@link AvgRTPStatsReporter}, before arithmetic mean is
  104. * calculated and submitted to the analytics module.
  105. * @param {boolean} [options.config.enableIceRestart=false] - enables the ICE
  106. * restart logic.
  107. * @param {boolean} [options.config.p2p.enabled] when set to <tt>true</tt>
  108. * the peer to peer mode will be enabled. It means that when there are only 2
  109. * participants in the conference an attempt to make direct connection will be
  110. * made. If the connection succeeds the conference will stop sending data
  111. * through the JVB connection and will use the direct one instead.
  112. * @param {number} [options.config.p2p.backToP2PDelay=5] a delay given in
  113. * seconds, before the conference switches back to P2P, after the 3rd
  114. * participant has left the room.
  115. * @param {number} [options.config.channelLastN=-1] The requested amount of
  116. * videos are going to be delivered after the value is in effect. Set to -1 for
  117. * unlimited or all available videos.
  118. * @constructor
  119. *
  120. * FIXME Make all methods which are called from lib-internal classes
  121. * to non-public (use _). To name a few:
  122. * {@link JitsiConference.onLocalRoleChanged}
  123. * {@link JitsiConference.onUserRoleChanged}
  124. * {@link JitsiConference.onMemberLeft}
  125. * and so on...
  126. */
  127. export default function JitsiConference(options) {
  128. if (!options.name || options.name.toLowerCase() !== options.name.toString()) {
  129. const errmsg
  130. = 'Invalid conference name (no conference name passed or it '
  131. + 'contains invalid characters like capital letters)!';
  132. const additionalLogMsg = options.name
  133. ? `roomName=${options.name}; condition - ${options.name.toLowerCase()}!==${options.name.toString()}`
  134. : 'No room name passed!';
  135. logger.error(`${errmsg} ${additionalLogMsg}`);
  136. throw new Error(errmsg);
  137. }
  138. this.connection = options.connection;
  139. this.xmpp = this.connection?.xmpp;
  140. if (this.xmpp.isRoomCreated(options.name, options.customDomain)) {
  141. const errmsg = 'A conference with the same name has already been created!';
  142. delete this.connection;
  143. delete this.xmpp;
  144. logger.error(errmsg);
  145. throw new Error(errmsg);
  146. }
  147. this.eventEmitter = new EventEmitter();
  148. this.options = options;
  149. this.eventManager = new JitsiConferenceEventManager(this);
  150. /**
  151. * List of all the participants in the conference.
  152. * @type {Map<string, JitsiParticipant>};
  153. */
  154. this.participants = new Map();
  155. /**
  156. * The signaling layer instance.
  157. * @type {SignalingLayerImpl}
  158. * @private
  159. */
  160. this._signalingLayer = new SignalingLayerImpl();
  161. this._init(options);
  162. this.componentsVersions = new ComponentsVersions(this);
  163. /**
  164. * Jingle session instance for the JVB connection.
  165. * @type {JingleSessionPC}
  166. */
  167. this.jvbJingleSession = null;
  168. this.lastDominantSpeaker = null;
  169. this.dtmfManager = null;
  170. this.somebodySupportsDTMF = false;
  171. this.authEnabled = false;
  172. this.startAudioMuted = false;
  173. this.startVideoMuted = false;
  174. this.startMutedPolicy = {
  175. audio: false,
  176. video: false
  177. };
  178. this.isMutedByFocus = false;
  179. // when muted by focus we receive the jid of the initiator of the mute
  180. this.mutedByFocusActor = null;
  181. this.isVideoMutedByFocus = false;
  182. // when video muted by focus we receive the jid of the initiator of the mute
  183. this.mutedVideoByFocusActor = null;
  184. // Flag indicates if the 'onCallEnded' method was ever called on this
  185. // instance. Used to log extra analytics event for debugging purpose.
  186. // We need to know if the potential issue happened before or after
  187. // the restart.
  188. this.wasStopped = false;
  189. // Conference properties, maintained by jicofo.
  190. this.properties = {};
  191. /**
  192. * The object which monitors local and remote connection statistics (e.g.
  193. * sending bitrate) and calculates a number which represents the connection
  194. * quality.
  195. */
  196. this.connectionQuality
  197. = new ConnectionQuality(this, this.eventEmitter, options);
  198. /**
  199. * Reports average RTP statistics to the analytics module.
  200. * @type {AvgRTPStatsReporter}
  201. */
  202. this.avgRtpStatsReporter
  203. = new AvgRTPStatsReporter(this, options.config.avgRtpStatsN || 15);
  204. /**
  205. * Detects issues with the audio of remote participants.
  206. * @type {AudioOutputProblemDetector}
  207. */
  208. if (!options.config.disableAudioLevels) {
  209. this._audioOutputProblemDetector = new AudioOutputProblemDetector(this);
  210. }
  211. /**
  212. * Indicates whether the connection is interrupted or not.
  213. */
  214. this.isJvbConnectionInterrupted = false;
  215. /**
  216. * The object which tracks active speaker times
  217. */
  218. this.speakerStatsCollector = new SpeakerStatsCollector(this);
  219. /* P2P related fields below: */
  220. /**
  221. * Stores reference to deferred start P2P task. It's created when 3rd
  222. * participant leaves the room in order to avoid ping pong effect (it
  223. * could be just a page reload).
  224. * @type {number|null}
  225. */
  226. this.deferredStartP2PTask = null;
  227. const delay
  228. = parseInt(options.config.p2p && options.config.p2p.backToP2PDelay, 10);
  229. /**
  230. * A delay given in seconds, before the conference switches back to P2P
  231. * after the 3rd participant has left.
  232. * @type {number}
  233. */
  234. this.backToP2PDelay = isNaN(delay) ? 5 : delay;
  235. logger.info(`backToP2PDelay: ${this.backToP2PDelay}`);
  236. /**
  237. * If set to <tt>true</tt> it means the P2P ICE is no longer connected.
  238. * When <tt>false</tt> it means that P2P ICE (media) connection is up
  239. * and running.
  240. * @type {boolean}
  241. */
  242. this.isP2PConnectionInterrupted = false;
  243. /**
  244. * Flag set to <tt>true</tt> when P2P session has been established
  245. * (ICE has been connected) and this conference is currently in the peer to
  246. * peer mode (P2P connection is the active one).
  247. * @type {boolean}
  248. */
  249. this.p2p = false;
  250. /**
  251. * A JingleSession for the direct peer to peer connection.
  252. * @type {JingleSessionPC}
  253. */
  254. this.p2pJingleSession = null;
  255. this.videoSIPGWHandler = new VideoSIPGW(this.room);
  256. this.recordingManager = new RecordingManager(this.room);
  257. /**
  258. * If the conference.joined event has been sent this will store the timestamp when it happened.
  259. *
  260. * @type {undefined|number}
  261. * @private
  262. */
  263. this._conferenceJoinAnalyticsEventSent = undefined;
  264. /**
  265. * End-to-End Encryption. Make it available if supported.
  266. */
  267. if (this.isE2EESupported()) {
  268. logger.info('End-to-End Encryption is supported');
  269. this._e2eEncryption = new E2EEncryption(this);
  270. }
  271. if (FeatureFlags.isRunInLiteModeEnabled()) {
  272. logger.info('Lite mode enabled');
  273. this._liteModeContext = new LiteModeContext(this);
  274. }
  275. /**
  276. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max audio sender limit has
  277. * been reached for the call. Once this is set, unmuting audio will be disabled from the client until it gets reset
  278. * again by Jicofo.
  279. */
  280. this._audioSenderLimitReached = undefined;
  281. /**
  282. * Flag set to <tt>true</tt> when Jicofo sends a presence message indicating that the max video sender limit has
  283. * been reached for the call. Once this is set, unmuting video will be disabled from the client until it gets reset
  284. * again by Jicofo.
  285. */
  286. this._videoSenderLimitReached = undefined;
  287. this._firefoxP2pEnabled = browser.isVersionGreaterThan(109)
  288. && (this.options.config.testing?.enableFirefoxP2p ?? true);
  289. }
  290. // FIXME convert JitsiConference to ES6 - ASAP !
  291. JitsiConference.prototype.constructor = JitsiConference;
  292. /**
  293. * Create a resource for the a jid. We use the room nickname (the resource part
  294. * of the occupant JID, see XEP-0045) as the endpoint ID in colibri. We require
  295. * endpoint IDs to be 8 hex digits because in some cases they get serialized
  296. * into a 32bit field.
  297. *
  298. * @param {string} jid - The id set onto the XMPP connection.
  299. * @param {boolean} isAuthenticatedUser - Whether or not the user has connected
  300. * to the XMPP service with a password.
  301. * @returns {string}
  302. * @static
  303. */
  304. JitsiConference.resourceCreator = function(jid, isAuthenticatedUser) {
  305. let mucNickname;
  306. if (isAuthenticatedUser) {
  307. // For authenticated users generate a random ID.
  308. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  309. } else {
  310. // We try to use the first part of the node (which for anonymous users
  311. // on prosody is a UUID) to match the previous behavior (and maybe make
  312. // debugging easier).
  313. mucNickname = Strophe.getNodeFromJid(jid)?.substr(0, 8)
  314. .toLowerCase();
  315. // But if this doesn't have the required format we just generate a new
  316. // random nickname.
  317. const re = /[0-9a-f]{8}/g;
  318. if (!mucNickname || !re.test(mucNickname)) {
  319. mucNickname = RandomUtil.randomHexString(8).toLowerCase();
  320. }
  321. }
  322. return mucNickname;
  323. };
  324. /**
  325. * Initializes the conference object properties
  326. * @param options {object}
  327. * @param options.connection {JitsiConnection} overrides this.connection
  328. */
  329. JitsiConference.prototype._init = function(options = {}) {
  330. this.eventManager.setupXMPPListeners();
  331. const { config } = this.options;
  332. // Get the codec preference settings from config.js.
  333. const codecSettings = {
  334. jvb: {
  335. preferenceOrder: browser.isMobileDevice() && config.videoQuality?.mobileCodecPreferenceOrder
  336. ? config.videoQuality.mobileCodecPreferenceOrder
  337. : config.videoQuality?.codecPreferenceOrder,
  338. disabledCodec: _getCodecMimeType(config.videoQuality?.disabledCodec),
  339. preferredCodec: _getCodecMimeType(config.videoQuality?.preferredCodec)
  340. },
  341. p2p: {
  342. preferenceOrder: browser.isMobileDevice() && config.p2p?.mobileCodecPreferenceOrder
  343. ? config.p2p.mobileCodecPreferenceOrder
  344. : config.p2p?.codecPreferenceOrder,
  345. disabledCodec: _getCodecMimeType(config.p2p?.disabledCodec),
  346. preferredCodec: _getCodecMimeType(config.p2p?.preferredCodec)
  347. }
  348. };
  349. this.codecSelection = new CodecSelection(this, codecSettings);
  350. this._statsCurrentId = config.statisticsId ? config.statisticsId : Settings.callStatsUserName;
  351. this.room = this.xmpp.createRoom(
  352. this.options.name, {
  353. ...config,
  354. statsId: this._statsCurrentId
  355. },
  356. JitsiConference.resourceCreator
  357. );
  358. this._signalingLayer.setChatRoom(this.room);
  359. this._signalingLayer.on(
  360. SignalingEvents.SOURCE_UPDATED,
  361. (sourceName, endpointId, muted, videoType) => {
  362. const participant = this.participants.get(endpointId);
  363. const mediaType = getMediaTypeFromSourceName(sourceName);
  364. if (participant) {
  365. participant._setSources(mediaType, muted, sourceName, videoType);
  366. this.eventEmitter.emit(JitsiConferenceEvents.PARTICIPANT_SOURCE_UPDATED, participant);
  367. }
  368. });
  369. // Connection interrupted/restored listeners
  370. this._onIceConnectionInterrupted
  371. = this._onIceConnectionInterrupted.bind(this);
  372. this.room.addListener(
  373. XMPPEvents.CONNECTION_INTERRUPTED, this._onIceConnectionInterrupted);
  374. this._onIceConnectionRestored = this._onIceConnectionRestored.bind(this);
  375. this.room.addListener(
  376. XMPPEvents.CONNECTION_RESTORED, this._onIceConnectionRestored);
  377. this._onIceConnectionEstablished
  378. = this._onIceConnectionEstablished.bind(this);
  379. this.room.addListener(
  380. XMPPEvents.CONNECTION_ESTABLISHED, this._onIceConnectionEstablished);
  381. this._updateProperties = this._updateProperties.bind(this);
  382. this.room.addListener(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  383. this._updateProperties);
  384. this._sendConferenceJoinAnalyticsEvent = this._sendConferenceJoinAnalyticsEvent.bind(this);
  385. this.room.addListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  386. this._removeLocalSourceOnReject = this._removeLocalSourceOnReject.bind(this);
  387. this._updateRoomPresence = this._updateRoomPresence.bind(this);
  388. this.room.addListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  389. this.room.addListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  390. this.room.addListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  391. this.room.addListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  392. if (config.e2eping?.enabled) {
  393. this.e2eping = new E2ePing(
  394. this,
  395. config,
  396. (message, to) => {
  397. try {
  398. this.sendMessage(message, to, true /* sendThroughVideobridge */);
  399. } catch (error) {
  400. logger.warn('Failed to send E2E ping request or response.', error && error.msg);
  401. }
  402. });
  403. }
  404. if (!this.rtc) {
  405. this.rtc = new RTC(this, options);
  406. this.eventManager.setupRTCListeners();
  407. this._registerRtcListeners(this.rtc);
  408. }
  409. this.receiveVideoController = new ReceiveVideoController(this, this.rtc);
  410. this.sendVideoController = new SendVideoController(this, this.rtc);
  411. if (!this.statistics) {
  412. this.statistics = new Statistics(this, {
  413. aliasName: this._statsCurrentId,
  414. userName: config.statisticsDisplayName ? config.statisticsDisplayName : this.myUserId(),
  415. confID: config.confID || `${this.connection.options.hosts.domain}/${this.options.name}`,
  416. roomName: this.options.name,
  417. applicationName: config.applicationName
  418. });
  419. Statistics.analytics.addPermanentProperties({
  420. 'callstats_name': this._statsCurrentId
  421. });
  422. // Start performance observer for monitoring long tasks
  423. if (config.longTasksStatsInterval) {
  424. this.statistics.attachLongTasksStats();
  425. }
  426. }
  427. this.eventManager.setupChatRoomListeners();
  428. // Always add listeners because on reload we are executing leave and the
  429. // listeners are removed from statistics module.
  430. this.eventManager.setupStatisticsListeners();
  431. // Disable VAD processing on Safari since it causes audio input to
  432. // fail on some of the mobile devices.
  433. if (config.enableTalkWhileMuted && browser.supportsVADDetection()) {
  434. // If VAD processor factory method is provided uses VAD based detection, otherwise fallback to audio level
  435. // based detection.
  436. if (config.createVADProcessor) {
  437. logger.info('Using VAD detection for generating talk while muted events');
  438. if (!this._audioAnalyser) {
  439. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  440. }
  441. const vadTalkMutedDetection = new VADTalkMutedDetection();
  442. vadTalkMutedDetection.on(DetectionEvents.VAD_TALK_WHILE_MUTED, () =>
  443. this.eventEmitter.emit(JitsiConferenceEvents.TALK_WHILE_MUTED));
  444. this._audioAnalyser.addVADDetectionService(vadTalkMutedDetection);
  445. } else {
  446. logger.warn('No VAD Processor was provided. Talk while muted detection service was not initialized!');
  447. }
  448. }
  449. // Disable noisy mic detection on safari since it causes the audio input to
  450. // fail on Safari on iPadOS.
  451. if (config.enableNoisyMicDetection && browser.supportsVADDetection()) {
  452. if (config.createVADProcessor) {
  453. if (!this._audioAnalyser) {
  454. this._audioAnalyser = new VADAudioAnalyser(this, config.createVADProcessor);
  455. }
  456. const vadNoiseDetection = new VADNoiseDetection();
  457. vadNoiseDetection.on(DetectionEvents.VAD_NOISY_DEVICE, () =>
  458. this.eventEmitter.emit(JitsiConferenceEvents.NOISY_MIC));
  459. this._audioAnalyser.addVADDetectionService(vadNoiseDetection);
  460. } else {
  461. logger.warn('No VAD Processor was provided. Noisy microphone detection service was not initialized!');
  462. }
  463. }
  464. // Generates events based on no audio input detector.
  465. if (config.enableNoAudioDetection && !config.disableAudioLevels && LocalStatsCollector.isLocalStatsSupported()) {
  466. this._noAudioSignalDetection = new NoAudioSignalDetection(this);
  467. this._noAudioSignalDetection.on(DetectionEvents.NO_AUDIO_INPUT, () => {
  468. this.eventEmitter.emit(JitsiConferenceEvents.NO_AUDIO_INPUT);
  469. });
  470. this._noAudioSignalDetection.on(DetectionEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal => {
  471. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_INPUT_STATE_CHANGE, hasAudioSignal);
  472. });
  473. }
  474. if ('channelLastN' in config) {
  475. this.setLastN(config.channelLastN);
  476. }
  477. /**
  478. * Emits {@link JitsiConferenceEvents.JVB121_STATUS}.
  479. * @type {Jvb121EventGenerator}
  480. */
  481. this.jvb121Status = new Jvb121EventGenerator(this);
  482. // creates dominant speaker detection that works only in p2p mode
  483. this.p2pDominantSpeakerDetection = new P2PDominantSpeakerDetection(this);
  484. if (config && config.deploymentInfo && config.deploymentInfo.userRegion) {
  485. this.setLocalParticipantProperty(
  486. 'region', config.deploymentInfo.userRegion);
  487. }
  488. // Publish the codec preference to presence.
  489. this.setLocalParticipantProperty('codecList', this.codecSelection.getCodecPreferenceList('jvb'));
  490. // Set transcription language presence extension.
  491. // In case the language config is undefined or has the default value that the transcriber uses
  492. // (in our case Jigasi uses 'en-US'), don't set the participant property in order to avoid
  493. // needlessly polluting the presence stanza.
  494. if (config && config.transcriptionLanguage && config.transcriptionLanguage !== 'en-US') {
  495. this.setLocalParticipantProperty('transcription_language', config.transcriptionLanguage);
  496. }
  497. };
  498. /**
  499. * Joins the conference.
  500. * @param password {string} the password
  501. * @param replaceParticipant {boolean} whether the current join replaces
  502. * an existing participant with same jwt from the meeting.
  503. */
  504. JitsiConference.prototype.join = function(password, replaceParticipant = false) {
  505. if (this.room) {
  506. this.room.join(password, replaceParticipant).then(() => this._maybeSetSITimeout());
  507. }
  508. };
  509. /**
  510. * Authenticates and upgrades the role of the local participant/user.
  511. *
  512. * @returns {Object} A <tt>thenable</tt> which (1) settles when the process of
  513. * authenticating and upgrading the role of the local participant/user finishes
  514. * and (2) has a <tt>cancel</tt> method that allows the caller to interrupt the
  515. * process.
  516. */
  517. JitsiConference.prototype.authenticateAndUpgradeRole = function(options) {
  518. return authenticateAndUpgradeRole.call(this, {
  519. ...options,
  520. onCreateResource: JitsiConference.resourceCreator
  521. });
  522. };
  523. /**
  524. * Check if joined to the conference.
  525. */
  526. JitsiConference.prototype.isJoined = function() {
  527. return this.room && this.room.joined;
  528. };
  529. /**
  530. * Tells whether or not the P2P mode is enabled in the configuration.
  531. * @return {boolean}
  532. */
  533. JitsiConference.prototype.isP2PEnabled = function() {
  534. return Boolean(this.options.config.p2p && this.options.config.p2p.enabled)
  535. // FIXME: remove once we have a default config template. -saghul
  536. || typeof this.options.config.p2p === 'undefined';
  537. };
  538. /**
  539. * When in P2P test mode, the conference will not automatically switch to P2P
  540. * when there 2 participants.
  541. * @return {boolean}
  542. */
  543. JitsiConference.prototype.isP2PTestModeEnabled = function() {
  544. return Boolean(this.options.config.testing
  545. && this.options.config.testing.p2pTestMode);
  546. };
  547. /**
  548. * Leaves the conference.
  549. * @param reason {string|undefined} The reason for leaving the conference.
  550. * @returns {Promise}
  551. */
  552. JitsiConference.prototype.leave = async function(reason) {
  553. if (this.avgRtpStatsReporter) {
  554. this.avgRtpStatsReporter.dispose();
  555. this.avgRtpStatsReporter = null;
  556. }
  557. if (this._audioOutputProblemDetector) {
  558. this._audioOutputProblemDetector.dispose();
  559. this._audioOutputProblemDetector = null;
  560. }
  561. if (this.e2eping) {
  562. this.e2eping.stop();
  563. this.e2eping = null;
  564. }
  565. this.getLocalTracks().forEach(track => this.onLocalTrackRemoved(track));
  566. this.rtc.closeBridgeChannel();
  567. this._sendConferenceLeftAnalyticsEvent();
  568. if (this.statistics) {
  569. this.statistics.dispose();
  570. }
  571. this._delayedIceFailed && this._delayedIceFailed.cancel();
  572. this._maybeClearSITimeout();
  573. // Close both JVb and P2P JingleSessions
  574. if (this.jvbJingleSession) {
  575. this.jvbJingleSession.close();
  576. this.jvbJingleSession = null;
  577. }
  578. if (this.p2pJingleSession) {
  579. this.p2pJingleSession.close();
  580. this.p2pJingleSession = null;
  581. }
  582. // Leave the conference. If this.room == null we are calling second time leave().
  583. if (!this.room) {
  584. throw new Error('You have already left the conference');
  585. }
  586. const room = this.room;
  587. // Unregister connection state listeners
  588. room.removeListener(
  589. XMPPEvents.CONNECTION_INTERRUPTED,
  590. this._onIceConnectionInterrupted);
  591. room.removeListener(
  592. XMPPEvents.CONNECTION_RESTORED,
  593. this._onIceConnectionRestored);
  594. room.removeListener(
  595. XMPPEvents.CONNECTION_ESTABLISHED,
  596. this._onIceConnectionEstablished);
  597. room.removeListener(
  598. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED,
  599. this._updateProperties);
  600. room.removeListener(XMPPEvents.MEETING_ID_SET, this._sendConferenceJoinAnalyticsEvent);
  601. room.removeListener(XMPPEvents.SESSION_ACCEPT, this._updateRoomPresence);
  602. room.removeListener(XMPPEvents.SOURCE_ADD, this._updateRoomPresence);
  603. room.removeListener(XMPPEvents.SOURCE_ADD_ERROR, this._removeLocalSourceOnReject);
  604. room.removeListener(XMPPEvents.SOURCE_REMOVE, this._updateRoomPresence);
  605. this.eventManager.removeXMPPListeners();
  606. this._signalingLayer.setChatRoom(null);
  607. this.room = null;
  608. let leaveError;
  609. try {
  610. await room.leave(reason);
  611. } catch (err) {
  612. leaveError = err;
  613. // Remove all participants because currently the conference
  614. // won't be usable anyway. This is done on success automatically
  615. // by the ChatRoom instance.
  616. this.getParticipants().forEach(
  617. participant => this.onMemberLeft(participant.getJid()));
  618. }
  619. if (this.rtc) {
  620. this.rtc.destroy();
  621. }
  622. if (leaveError) {
  623. throw leaveError;
  624. }
  625. };
  626. /**
  627. * Returns <tt>true</tt> if end conference support is enabled in the backend.
  628. *
  629. * @returns {boolean} whether end conference is supported in the backend.
  630. */
  631. JitsiConference.prototype.isEndConferenceSupported = function() {
  632. return Boolean(this.room && this.room.xmpp.endConferenceComponentAddress);
  633. };
  634. /**
  635. * Ends the conference.
  636. */
  637. JitsiConference.prototype.end = function() {
  638. if (!this.isEndConferenceSupported()) {
  639. logger.warn('Cannot end conference: is not supported.');
  640. return;
  641. }
  642. if (!this.room) {
  643. throw new Error('You have already left the conference');
  644. }
  645. this.room.end();
  646. };
  647. /**
  648. * Returns the currently active media session if any.
  649. *
  650. * @returns {JingleSessionPC|undefined}
  651. */
  652. JitsiConference.prototype.getActiveMediaSession = function() {
  653. return this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  654. };
  655. /**
  656. * Returns an array containing all media sessions existing in this conference.
  657. *
  658. * @returns {Array<JingleSessionPC>}
  659. */
  660. JitsiConference.prototype.getMediaSessions = function() {
  661. const sessions = [];
  662. this.jvbJingleSession && sessions.push(this.jvbJingleSession);
  663. this.p2pJingleSession && sessions.push(this.p2pJingleSession);
  664. return sessions;
  665. };
  666. /**
  667. * Registers event listeners on the RTC instance.
  668. * @param {RTC} rtc - the RTC module instance used by this conference.
  669. * @private
  670. * @returns {void}
  671. */
  672. JitsiConference.prototype._registerRtcListeners = function(rtc) {
  673. rtc.addListener(RTCEvents.DATA_CHANNEL_OPEN, () => {
  674. for (const localTrack of this.rtc.localTracks) {
  675. localTrack.isVideoTrack() && this._sendBridgeVideoTypeMessage(localTrack);
  676. }
  677. });
  678. };
  679. /**
  680. * Sends the 'VideoTypeMessage' to the bridge on the bridge channel so that the bridge can make bitrate allocation
  681. * decisions based on the video type of the local source.
  682. *
  683. * @param {JitsiLocalTrack} localtrack - The track associated with the local source signaled to the bridge.
  684. * @returns {void}
  685. * @private
  686. */
  687. JitsiConference.prototype._sendBridgeVideoTypeMessage = function(localtrack) {
  688. let videoType = !localtrack || localtrack.isMuted() ? BridgeVideoType.NONE : localtrack.getVideoType();
  689. if (videoType === BridgeVideoType.DESKTOP && this._desktopSharingFrameRate > SS_DEFAULT_FRAME_RATE) {
  690. videoType = BridgeVideoType.DESKTOP_HIGH_FPS;
  691. }
  692. localtrack && this.rtc.sendSourceVideoType(localtrack.getSourceName(), videoType);
  693. };
  694. /**
  695. * Returns name of this conference.
  696. */
  697. JitsiConference.prototype.getName = function() {
  698. return this.options.name.toString();
  699. };
  700. /**
  701. * Returns the {@link JitsiConnection} used by this this conference.
  702. */
  703. JitsiConference.prototype.getConnection = function() {
  704. return this.connection;
  705. };
  706. /**
  707. * Check if authentication is enabled for this conference.
  708. */
  709. JitsiConference.prototype.isAuthEnabled = function() {
  710. return this.authEnabled;
  711. };
  712. /**
  713. * Check if user is logged in.
  714. */
  715. JitsiConference.prototype.isLoggedIn = function() {
  716. return Boolean(this.authIdentity);
  717. };
  718. /**
  719. * Get authorized login.
  720. */
  721. JitsiConference.prototype.getAuthLogin = function() {
  722. return this.authIdentity;
  723. };
  724. /**
  725. * Returns the local tracks of the given media type, or all local tracks if no
  726. * specific type is given.
  727. * @param {MediaType} [mediaType] Optional media type (audio or video).
  728. */
  729. JitsiConference.prototype.getLocalTracks = function(mediaType) {
  730. let tracks = [];
  731. if (this.rtc) {
  732. tracks = this.rtc.getLocalTracks(mediaType);
  733. }
  734. return tracks;
  735. };
  736. /**
  737. * Obtains local audio track.
  738. * @return {JitsiLocalTrack|null}
  739. */
  740. JitsiConference.prototype.getLocalAudioTrack = function() {
  741. return this.rtc ? this.rtc.getLocalAudioTrack() : null;
  742. };
  743. /**
  744. * Obtains local video track.
  745. * @return {JitsiLocalTrack|null}
  746. */
  747. JitsiConference.prototype.getLocalVideoTrack = function() {
  748. return this.rtc ? this.rtc.getLocalVideoTrack() : null;
  749. };
  750. /**
  751. * Returns all the local video tracks.
  752. * @returns {Array<JitsiLocalTrack>}
  753. */
  754. JitsiConference.prototype.getLocalVideoTracks = function() {
  755. return this.rtc ? this.rtc.getLocalVideoTracks() : null;
  756. };
  757. /**
  758. * Obtains the performance statistics.
  759. * @returns {Object|null}
  760. */
  761. JitsiConference.prototype.getPerformanceStats = function() {
  762. return {
  763. longTasksStats: this.statistics.getLongTasksStats()
  764. };
  765. };
  766. /**
  767. * Attaches a handler for events(For example - "participant joined".) in the
  768. * conference. All possible event are defined in JitsiConferenceEvents.
  769. * @param eventId the event ID.
  770. * @param handler handler for the event.
  771. *
  772. * Note: consider adding eventing functionality by extending an EventEmitter
  773. * impl, instead of rolling ourselves
  774. */
  775. JitsiConference.prototype.on = function(eventId, handler) {
  776. if (this.eventEmitter) {
  777. this.eventEmitter.on(eventId, handler);
  778. }
  779. };
  780. /**
  781. * Adds a one-time`listener` function for the event.
  782. * @param eventId the event ID.
  783. * @param handler handler for the event.
  784. *
  785. */
  786. JitsiConference.prototype.once = function(eventId, handler) {
  787. if (this.eventEmitter) {
  788. this.eventEmitter.once(eventId, handler);
  789. }
  790. };
  791. /**
  792. * Removes event listener
  793. * @param eventId the event ID.
  794. * @param [handler] optional, the specific handler to unbind
  795. *
  796. * Note: consider adding eventing functionality by extending an EventEmitter
  797. * impl, instead of rolling ourselves
  798. */
  799. JitsiConference.prototype.off = function(eventId, handler) {
  800. if (this.eventEmitter) {
  801. this.eventEmitter.removeListener(eventId, handler);
  802. }
  803. };
  804. // Common aliases for event emitter
  805. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  806. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  807. /**
  808. * Receives notifications from other participants about commands / custom events
  809. * (sent by sendCommand or sendCommandOnce methods).
  810. * @param command {String} the name of the command
  811. * @param handler {Function} handler for the command
  812. */
  813. JitsiConference.prototype.addCommandListener = function(command, handler) {
  814. if (this.room) {
  815. this.room.addPresenceListener(command, handler);
  816. }
  817. };
  818. /**
  819. * Removes command listener
  820. * @param command {String} the name of the command
  821. * @param handler {Function} handler to remove for the command
  822. */
  823. JitsiConference.prototype.removeCommandListener = function(command, handler) {
  824. if (this.room) {
  825. this.room.removePresenceListener(command, handler);
  826. }
  827. };
  828. /**
  829. * Sends text message to the other participants in the conference
  830. * @param message the text message.
  831. * @param elementName the element name to encapsulate the message.
  832. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  833. */
  834. JitsiConference.prototype.sendTextMessage = function(message, elementName = 'body') {
  835. if (this.room) {
  836. this.room.sendMessage(message, elementName);
  837. }
  838. };
  839. /**
  840. * Send private text message to another participant of the conference
  841. * @param id the id of the participant to send a private message.
  842. * @param message the text message.
  843. * @param elementName the element name to encapsulate the message.
  844. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  845. */
  846. JitsiConference.prototype.sendPrivateTextMessage = function(id, message, elementName = 'body') {
  847. if (this.room) {
  848. this.room.sendPrivateMessage(id, message, elementName);
  849. }
  850. };
  851. /**
  852. * Send presence command.
  853. * @param name {String} the name of the command.
  854. * @param values {Object} with keys and values that will be sent.
  855. **/
  856. JitsiConference.prototype.sendCommand = function(name, values) {
  857. if (this.room) {
  858. this.room.addOrReplaceInPresence(name, values) && this.room.sendPresence();
  859. } else {
  860. logger.warn('Not sending a command, room not initialized.');
  861. }
  862. };
  863. /**
  864. * Send presence command one time.
  865. * @param name {String} the name of the command.
  866. * @param values {Object} with keys and values that will be sent.
  867. **/
  868. JitsiConference.prototype.sendCommandOnce = function(name, values) {
  869. this.sendCommand(name, values);
  870. this.removeCommand(name);
  871. };
  872. /**
  873. * Removes presence command.
  874. * @param name {String} the name of the command.
  875. **/
  876. JitsiConference.prototype.removeCommand = function(name) {
  877. if (this.room) {
  878. this.room.removeFromPresence(name);
  879. }
  880. };
  881. /**
  882. * Sets the display name for this conference.
  883. * @param name the display name to set
  884. */
  885. JitsiConference.prototype.setDisplayName = function(name) {
  886. if (this.room) {
  887. const nickKey = 'nick';
  888. if (name) {
  889. this.room.addOrReplaceInPresence(nickKey, {
  890. attributes: { xmlns: 'http://jabber.org/protocol/nick' },
  891. value: name
  892. }) && this.room.sendPresence();
  893. } else if (this.room.getFromPresence(nickKey)) {
  894. this.room.removeFromPresence(nickKey);
  895. this.room.sendPresence();
  896. }
  897. }
  898. };
  899. /**
  900. * Set new subject for this conference. (available only for moderator)
  901. * @param {string} subject new subject
  902. */
  903. JitsiConference.prototype.setSubject = function(subject) {
  904. if (this.room && this.isModerator()) {
  905. this.room.setSubject(subject);
  906. } else {
  907. logger.warn(`Failed to set subject, ${this.room ? '' : 'not in a room, '}${
  908. this.isModerator() ? '' : 'participant is not a moderator'}`);
  909. }
  910. };
  911. /**
  912. * Returns the transcription status.
  913. *
  914. * @returns {String} "on" or "off".
  915. */
  916. JitsiConference.prototype.getTranscriptionStatus = function() {
  917. return this.room.transcriptionStatus;
  918. };
  919. /**
  920. * Adds JitsiLocalTrack object to the conference.
  921. * @param {JitsiLocalTrack} track the JitsiLocalTrack object.
  922. * @returns {Promise<JitsiLocalTrack>}
  923. * @throws {Error} if the specified track is a video track and there is already
  924. * another video track in the conference.
  925. */
  926. JitsiConference.prototype.addTrack = function(track) {
  927. if (!track) {
  928. throw new Error('addTrack - a track is required');
  929. }
  930. const mediaType = track.getType();
  931. const localTracks = this.rtc.getLocalTracks(mediaType);
  932. // Ensure there's exactly 1 local track of each media type in the conference.
  933. if (localTracks.length > 0) {
  934. // Don't be excessively harsh and severe if the API client happens to attempt to add the same local track twice.
  935. if (track === localTracks[0]) {
  936. return Promise.resolve(track);
  937. }
  938. // Currently, only adding multiple video streams of different video types is supported.
  939. // TODO - remove this limitation once issues with jitsi-meet trying to add multiple camera streams is fixed.
  940. if (mediaType === MediaType.VIDEO
  941. && !localTracks.find(t => t.getVideoType() === track.getVideoType())) {
  942. const sourceName = getSourceNameForJitsiTrack(
  943. this.myUserId(),
  944. mediaType,
  945. this.getLocalTracks(mediaType)?.length);
  946. track.setSourceName(sourceName);
  947. const addTrackPromises = [];
  948. this.p2pJingleSession && addTrackPromises.push(this.p2pJingleSession.addTracks([ track ]));
  949. this.jvbJingleSession && addTrackPromises.push(this.jvbJingleSession.addTracks([ track ]));
  950. return Promise.all(addTrackPromises)
  951. .then(() => {
  952. this._setupNewTrack(track);
  953. this._sendBridgeVideoTypeMessage(track);
  954. this._updateRoomPresence(this.getActiveMediaSession());
  955. if (this.isMutedByFocus || this.isVideoMutedByFocus) {
  956. this._fireMuteChangeEvent(track);
  957. }
  958. });
  959. }
  960. return Promise.reject(new Error(`Cannot add second ${mediaType} track to the conference`));
  961. }
  962. return this.replaceTrack(null, track)
  963. .then(() => {
  964. // Presence needs to be sent here for desktop track since we need the presence to reach the remote peer
  965. // before signaling so that a fake participant tile is created for screenshare. Otherwise, presence will
  966. // only be sent after a session-accept or source-add is ack'ed.
  967. if (track.getVideoType() === VideoType.DESKTOP) {
  968. this._updateRoomPresence(this.getActiveMediaSession());
  969. }
  970. });
  971. };
  972. /**
  973. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event (for local tracks).
  974. * @param {number} audioLevel the audio level
  975. * @param {TraceablePeerConnection} [tpc]
  976. */
  977. JitsiConference.prototype._fireAudioLevelChangeEvent = function(audioLevel, tpc) {
  978. const activeTpc = this.getActivePeerConnection();
  979. // There will be no TraceablePeerConnection if audio levels do not come from
  980. // a peerconnection. LocalStatsCollector.js measures audio levels using Web
  981. // Audio Analyser API and emits local audio levels events through
  982. // JitsiTrack.setAudioLevel, but does not provide TPC instance which is
  983. // optional.
  984. if (!tpc || activeTpc === tpc) {
  985. this.eventEmitter.emit(
  986. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  987. this.myUserId(), audioLevel);
  988. }
  989. };
  990. /**
  991. * Fires TRACK_MUTE_CHANGED change conference event.
  992. * @param track the JitsiTrack object related to the event.
  993. */
  994. JitsiConference.prototype._fireMuteChangeEvent = function(track) {
  995. // check if track was muted by focus and now is unmuted by user
  996. if (this.isMutedByFocus && track.isAudioTrack() && !track.isMuted()) {
  997. this.isMutedByFocus = false;
  998. // unmute local user on server
  999. this.room.muteParticipant(this.room.myroomjid, false, MediaType.AUDIO);
  1000. } else if (this.isVideoMutedByFocus && track.isVideoTrack() && !track.isMuted()) {
  1001. this.isVideoMutedByFocus = false;
  1002. // unmute local user on server
  1003. this.room.muteParticipant(this.room.myroomjid, false, MediaType.VIDEO);
  1004. }
  1005. let actorParticipant;
  1006. if (this.mutedByFocusActor && track.isAudioTrack()) {
  1007. const actorId = Strophe.getResourceFromJid(this.mutedByFocusActor);
  1008. actorParticipant = this.participants.get(actorId);
  1009. } else if (this.mutedVideoByFocusActor && track.isVideoTrack()) {
  1010. const actorId = Strophe.getResourceFromJid(this.mutedVideoByFocusActor);
  1011. actorParticipant = this.participants.get(actorId);
  1012. }
  1013. // Send the video type message to the bridge if the track is not removed/added to the pc as part of
  1014. // the mute/unmute operation.
  1015. // In React Native we mute the camera by setting track.enabled but that doesn't
  1016. // work for screen-share tracks, so do the remove-as-mute for those.
  1017. const doesVideoMuteByStreamRemove
  1018. = browser.isReactNative() ? track.videoType === VideoType.DESKTOP : browser.doesVideoMuteByStreamRemove();
  1019. if (track.isVideoTrack() && !doesVideoMuteByStreamRemove) {
  1020. this._sendBridgeVideoTypeMessage(track);
  1021. }
  1022. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track, actorParticipant);
  1023. };
  1024. /**
  1025. * Returns the list of local tracks that need to be added to the peerconnection on join.
  1026. * This takes the startAudioMuted/startVideoMuted flags into consideration since we do not
  1027. * want to add the tracks if the user joins the call audio/video muted. The tracks will be
  1028. * added when the user unmutes for the first time.
  1029. * @returns {Array<JitsiLocalTrack>} - list of local tracks that are unmuted.
  1030. */
  1031. JitsiConference.prototype._getInitialLocalTracks = function() {
  1032. // Always add the audio track on certain platforms:
  1033. // * Safari / WebKit: because of a known issue where audio playout doesn't happen
  1034. // if the user joins audio and video muted.
  1035. // * React Native: after iOS 15, if a user joins muted they won't be able to unmute.
  1036. return this.getLocalTracks()
  1037. .filter(track => {
  1038. const trackType = track.getType();
  1039. if (trackType === MediaType.AUDIO
  1040. && (!(this.isStartAudioMuted() || this.startMutedPolicy.audio)
  1041. || browser.isWebKitBased()
  1042. || browser.isReactNative())) {
  1043. return true;
  1044. } else if (trackType === MediaType.VIDEO && !this.isStartVideoMuted() && !this.startMutedPolicy.video) {
  1045. return true;
  1046. }
  1047. // Remove the track from the conference.
  1048. this.onLocalTrackRemoved(track);
  1049. return false;
  1050. });
  1051. };
  1052. /**
  1053. * Clear JitsiLocalTrack properties and listeners.
  1054. * @param track the JitsiLocalTrack object.
  1055. */
  1056. JitsiConference.prototype.onLocalTrackRemoved = function(track) {
  1057. track.setConference(null);
  1058. this.rtc.removeLocalTrack(track);
  1059. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  1060. if (track.isAudioTrack()) {
  1061. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  1062. }
  1063. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1064. };
  1065. /**
  1066. * Removes JitsiLocalTrack from the conference and performs
  1067. * a new offer/answer cycle.
  1068. * @param {JitsiLocalTrack} track
  1069. * @returns {Promise}
  1070. */
  1071. JitsiConference.prototype.removeTrack = function(track) {
  1072. return this.replaceTrack(track, null);
  1073. };
  1074. /**
  1075. * Replaces oldTrack with newTrack and performs a single offer/answer
  1076. * cycle after both operations are done. Either oldTrack or newTrack
  1077. * can be null; replacing a valid 'oldTrack' with a null 'newTrack'
  1078. * effectively just removes 'oldTrack'
  1079. * @param {JitsiLocalTrack} oldTrack the current stream in use to be replaced
  1080. * @param {JitsiLocalTrack} newTrack the new stream to use
  1081. * @returns {Promise} resolves when the replacement is finished
  1082. */
  1083. JitsiConference.prototype.replaceTrack = function(oldTrack, newTrack) {
  1084. const oldVideoType = oldTrack?.getVideoType();
  1085. const mediaType = oldTrack?.getType() || newTrack?.getType();
  1086. const newVideoType = newTrack?.getVideoType();
  1087. if (oldTrack && newTrack && oldVideoType !== newVideoType) {
  1088. throw new Error(`Replacing a track of videoType=${oldVideoType} with a track of videoType=${newVideoType} is`
  1089. + ' not supported in this mode.');
  1090. }
  1091. if (newTrack) {
  1092. const sourceName = oldTrack
  1093. ? oldTrack.getSourceName()
  1094. : getSourceNameForJitsiTrack(
  1095. this.myUserId(),
  1096. mediaType,
  1097. this.getLocalTracks(mediaType)?.length);
  1098. newTrack.setSourceName(sourceName);
  1099. }
  1100. const oldTrackBelongsToConference = this === oldTrack?.conference;
  1101. if (oldTrackBelongsToConference && oldTrack.disposed) {
  1102. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1103. }
  1104. if (newTrack?.disposed) {
  1105. return Promise.reject(new JitsiTrackError(JitsiTrackErrors.TRACK_IS_DISPOSED));
  1106. }
  1107. if (oldTrack && !oldTrackBelongsToConference) {
  1108. logger.warn(`JitsiConference.replaceTrack oldTrack (${oldTrack} does not belong to this conference`);
  1109. }
  1110. // Now replace the stream at the lower levels
  1111. return this._doReplaceTrack(oldTrackBelongsToConference ? oldTrack : null, newTrack)
  1112. .then(() => {
  1113. if (oldTrackBelongsToConference && !oldTrack.isMuted() && !newTrack) {
  1114. oldTrack._sendMuteStatus(true);
  1115. }
  1116. oldTrackBelongsToConference && this.onLocalTrackRemoved(oldTrack);
  1117. newTrack && this._setupNewTrack(newTrack);
  1118. // Send 'VideoTypeMessage' on the bridge channel when a video track is added/removed.
  1119. if ((oldTrackBelongsToConference && oldTrack?.isVideoTrack()) || newTrack?.isVideoTrack()) {
  1120. this._sendBridgeVideoTypeMessage(newTrack);
  1121. }
  1122. this._updateRoomPresence(this.getActiveMediaSession());
  1123. if (newTrack !== null && (this.isMutedByFocus || this.isVideoMutedByFocus)) {
  1124. this._fireMuteChangeEvent(newTrack);
  1125. }
  1126. return Promise.resolve();
  1127. })
  1128. .catch(error => {
  1129. logger.error(`replaceTrack failed: ${error?.stack}`);
  1130. return Promise.reject(error);
  1131. });
  1132. };
  1133. /**
  1134. * Replaces the tracks at the lower level by going through the Jingle session
  1135. * and WebRTC peer connection. The method will resolve immediately if there is
  1136. * currently no JingleSession started.
  1137. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  1138. * the process or <tt>null</t> if the method should act as "add track"
  1139. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  1140. * <tt>null</tt> if the method should act as "remove track"
  1141. * @return {Promise} resolved when the process is done or rejected with a string
  1142. * which describes the error.
  1143. * @private
  1144. */
  1145. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  1146. const replaceTrackPromises = [];
  1147. if (this.jvbJingleSession) {
  1148. replaceTrackPromises.push(this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  1149. } else {
  1150. logger.info('_doReplaceTrack - no JVB JingleSession');
  1151. }
  1152. if (this.p2pJingleSession) {
  1153. replaceTrackPromises.push(this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  1154. } else {
  1155. logger.info('_doReplaceTrack - no P2P JingleSession');
  1156. }
  1157. return Promise.all(replaceTrackPromises);
  1158. };
  1159. /**
  1160. * Handler for when a source-add for a local source is rejected by Jicofo.
  1161. *
  1162. * @param {JingleSessionPC} jingleSession - The media session.
  1163. * @param {Error} error - The error message.
  1164. * @param {MediaType} mediaType - The media type of the track associated with the source that was rejected.
  1165. * @returns {void}
  1166. */
  1167. JitsiConference.prototype._removeLocalSourceOnReject = function(jingleSession, error, mediaType) {
  1168. if (!jingleSession) {
  1169. return;
  1170. }
  1171. logger.warn(`Source-add rejected on ${jingleSession}, reason="${error?.reason}", message="${error?.msg}"`);
  1172. const track = this.getLocalTracks(mediaType)[0];
  1173. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_UNMUTE_REJECTED, track);
  1174. };
  1175. /**
  1176. * Operations related to creating a new track
  1177. * @param {JitsiLocalTrack} newTrack the new track being created
  1178. */
  1179. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  1180. const mediaType = newTrack.getType();
  1181. // Create a source name for this track if it doesn't exist.
  1182. if (!newTrack.getSourceName()) {
  1183. const sourceName = getSourceNameForJitsiTrack(
  1184. this.myUserId(),
  1185. mediaType,
  1186. this.getLocalTracks(mediaType)?.length);
  1187. newTrack.setSourceName(sourceName);
  1188. }
  1189. this.rtc.addLocalTrack(newTrack);
  1190. newTrack.setConference(this);
  1191. // Add event handlers.
  1192. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1193. newTrack.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, newTrack.muteHandler);
  1194. if (newTrack.isAudioTrack()) {
  1195. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1196. newTrack.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, newTrack.audioLevelHandler);
  1197. }
  1198. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1199. };
  1200. /**
  1201. * Sets the video type.
  1202. * @param track
  1203. * @return <tt>true</tt> if video type was changed in presence.
  1204. * @private
  1205. */
  1206. JitsiConference.prototype._setNewVideoType = function(track) {
  1207. let videoTypeChanged = false;
  1208. if (track) {
  1209. videoTypeChanged = this._signalingLayer.setTrackVideoType(track.getSourceName(), track.videoType);
  1210. }
  1211. return videoTypeChanged;
  1212. };
  1213. /**
  1214. * Sets mute status.
  1215. * @param mediaType
  1216. * @param localTrack
  1217. * @param isMuted
  1218. * @param <tt>true</tt> when presence was changed, <tt>false</tt> otherwise.
  1219. * @private
  1220. */
  1221. JitsiConference.prototype._setTrackMuteStatus = function(mediaType, localTrack, isMuted) {
  1222. let presenceChanged = false;
  1223. if (localTrack) {
  1224. presenceChanged = this._signalingLayer.setTrackMuteStatus(localTrack.getSourceName(), isMuted);
  1225. presenceChanged && logger.debug(`Mute state of ${localTrack} changed to muted=${isMuted}`);
  1226. }
  1227. return presenceChanged;
  1228. };
  1229. /**
  1230. * Method called by the {@link JitsiLocalTrack} in order to add the underlying MediaStream to the RTCPeerConnection.
  1231. *
  1232. * @param {JitsiLocalTrack} track the local track that will be added to the pc.
  1233. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1234. */
  1235. JitsiConference.prototype._addLocalTrackToPc = function(track) {
  1236. const addPromises = [];
  1237. if (track.conference === this) {
  1238. if (this.jvbJingleSession) {
  1239. addPromises.push(this.jvbJingleSession.addTrackToPc(track));
  1240. } else {
  1241. logger.debug('Add local MediaStream - no JVB Jingle session started yet');
  1242. }
  1243. if (this.p2pJingleSession) {
  1244. addPromises.push(this.p2pJingleSession.addTrackToPc(track));
  1245. } else {
  1246. logger.debug('Add local MediaStream - no P2P Jingle session started yet');
  1247. }
  1248. } else {
  1249. // If the track hasn't been added to the conference yet because of start muted by focus, add it to the
  1250. // conference instead of adding it only to the media sessions.
  1251. addPromises.push(this.addTrack(track));
  1252. }
  1253. return Promise.allSettled(addPromises);
  1254. };
  1255. /**
  1256. * Method called by the {@link JitsiLocalTrack} in order to remove the underlying MediaStream from the
  1257. * RTCPeerConnection.
  1258. *
  1259. * @param {JitsiLocalTrack} track the local track that will be removed.
  1260. * @return {Promise} resolved when the process is done or rejected with a string which describes the error.
  1261. */
  1262. JitsiConference.prototype._removeLocalTrackFromPc = function(track) {
  1263. const removePromises = [];
  1264. if (track.conference === this) {
  1265. if (this.jvbJingleSession) {
  1266. removePromises.push(this.jvbJingleSession.removeTrackFromPc(track));
  1267. } else {
  1268. logger.debug('Remove local MediaStream - no JVB JingleSession started yet');
  1269. }
  1270. if (this.p2pJingleSession) {
  1271. removePromises.push(this.p2pJingleSession.removeTrackFromPc(track));
  1272. } else {
  1273. logger.debug('Remove local MediaStream - no P2P JingleSession started yet');
  1274. }
  1275. }
  1276. return Promise.allSettled(removePromises);
  1277. };
  1278. /**
  1279. * Get role of the local user.
  1280. * @returns {string} user role: 'moderator' or 'none'
  1281. */
  1282. JitsiConference.prototype.getRole = function() {
  1283. return this.room.role;
  1284. };
  1285. /**
  1286. * Returns whether or not the current conference has been joined as a hidden
  1287. * user.
  1288. *
  1289. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1290. * no connection is active.
  1291. */
  1292. JitsiConference.prototype.isHidden = function() {
  1293. if (!this.connection) {
  1294. return null;
  1295. }
  1296. return Strophe.getDomainFromJid(this.connection.getJid())
  1297. === this.options.config.hiddenDomain;
  1298. };
  1299. /**
  1300. * Check if local user is moderator.
  1301. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1302. * we're no longer in the conference room then <tt>null</tt> is returned.
  1303. */
  1304. JitsiConference.prototype.isModerator = function() {
  1305. return this.room ? this.room.isModerator() : null;
  1306. };
  1307. /**
  1308. * Set password for the room.
  1309. * @param {string} password new password for the room.
  1310. * @returns {Promise}
  1311. */
  1312. JitsiConference.prototype.lock = function(password) {
  1313. if (!this.isModerator()) {
  1314. return Promise.reject(new Error('You are not moderator.'));
  1315. }
  1316. return new Promise((resolve, reject) => {
  1317. this.room.lockRoom(
  1318. password || '',
  1319. () => resolve(),
  1320. err => reject(err),
  1321. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1322. });
  1323. };
  1324. /**
  1325. * Remove password from the room.
  1326. * @returns {Promise}
  1327. */
  1328. JitsiConference.prototype.unlock = function() {
  1329. return this.lock();
  1330. };
  1331. /**
  1332. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1333. * @returns {number}
  1334. */
  1335. JitsiConference.prototype.getLastN = function() {
  1336. return this.receiveVideoController.getLastN();
  1337. };
  1338. /**
  1339. * Obtains the forwarded sources list in this conference.
  1340. * @return {Array<string>|null}
  1341. */
  1342. JitsiConference.prototype.getForwardedSources = function() {
  1343. return this.rtc.getForwardedSources();
  1344. };
  1345. /**
  1346. * Selects a new value for "lastN". The requested amount of videos are going
  1347. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1348. * all available videos.
  1349. * @param lastN the new number of videos the user would like to receive.
  1350. * @throws Error or RangeError if the given value is not a number or is smaller
  1351. * than -1.
  1352. */
  1353. JitsiConference.prototype.setLastN = function(lastN) {
  1354. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1355. throw new Error(`Invalid value for lastN: ${lastN}`);
  1356. }
  1357. const n = Number(lastN);
  1358. if (n < -1) {
  1359. throw new RangeError('lastN cannot be smaller than -1');
  1360. }
  1361. this.receiveVideoController.setLastN(n);
  1362. // If the P2P session is not fully established yet, we wait until it gets established.
  1363. if (this.p2pJingleSession) {
  1364. const isVideoActive = n !== 0;
  1365. this.p2pJingleSession
  1366. .setP2pVideoTransferActive(isVideoActive)
  1367. .catch(error => {
  1368. logger.error(`Failed to adjust video transfer status (${isVideoActive})`, error);
  1369. });
  1370. }
  1371. };
  1372. /**
  1373. * @return Array<JitsiParticipant> an array of all participants in this conference.
  1374. */
  1375. JitsiConference.prototype.getParticipants = function() {
  1376. return Array.from(this.participants.values());
  1377. };
  1378. /**
  1379. * Returns the number of participants in the conference, including the local
  1380. * participant.
  1381. * @param countHidden {boolean} Whether or not to include hidden participants
  1382. * in the count. Default: false.
  1383. **/
  1384. JitsiConference.prototype.getParticipantCount = function(countHidden = false) {
  1385. let participants = this.getParticipants();
  1386. if (!countHidden) {
  1387. participants = participants.filter(p => !p.isHidden());
  1388. }
  1389. // Add one for the local participant.
  1390. return participants.length + 1;
  1391. };
  1392. /**
  1393. * @returns {JitsiParticipant} the participant in this conference with the
  1394. * specified id (or undefined if there isn't one).
  1395. * @param id the id of the participant.
  1396. */
  1397. JitsiConference.prototype.getParticipantById = function(id) {
  1398. return this.participants.get(id);
  1399. };
  1400. /**
  1401. * Grant owner rights to the participant.
  1402. * @param {string} id id of the participant to grant owner rights to.
  1403. */
  1404. JitsiConference.prototype.grantOwner = function(id) {
  1405. const participant = this.getParticipantById(id);
  1406. if (!participant) {
  1407. return;
  1408. }
  1409. this.room.setAffiliation(participant.getConnectionJid(), 'owner');
  1410. };
  1411. /**
  1412. * Revoke owner rights to the participant or local Participant as
  1413. * the user might want to refuse to be a moderator.
  1414. * @param {string} id id of the participant to revoke owner rights to.
  1415. */
  1416. JitsiConference.prototype.revokeOwner = function(id) {
  1417. const participant = this.getParticipantById(id);
  1418. const isMyself = this.myUserId() === id;
  1419. const role = this.isMembersOnly() ? 'member' : 'none';
  1420. if (isMyself) {
  1421. this.room.setAffiliation(this.connection.getJid(), role);
  1422. } else if (participant) {
  1423. this.room.setAffiliation(participant.getConnectionJid(), role);
  1424. }
  1425. };
  1426. /**
  1427. * Kick participant from this conference.
  1428. * @param {string} id id of the participant to kick
  1429. * @param {string} reason reason of the participant to kick
  1430. */
  1431. JitsiConference.prototype.kickParticipant = function(id, reason) {
  1432. const participant = this.getParticipantById(id);
  1433. if (!participant) {
  1434. return;
  1435. }
  1436. this.room.kick(participant.getJid(), reason);
  1437. };
  1438. /**
  1439. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1440. * analytics event.
  1441. * @private
  1442. */
  1443. JitsiConference.prototype._maybeClearSITimeout = function() {
  1444. if (this._sessionInitiateTimeout
  1445. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1446. window.clearTimeout(this._sessionInitiateTimeout);
  1447. this._sessionInitiateTimeout = null;
  1448. }
  1449. };
  1450. /**
  1451. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1452. * event.
  1453. * @private
  1454. */
  1455. JitsiConference.prototype._maybeSetSITimeout = function() {
  1456. // Jicofo is supposed to invite if there are at least 2 participants
  1457. if (!this.jvbJingleSession
  1458. && this.getParticipantCount() >= 2
  1459. && !this._sessionInitiateTimeout) {
  1460. this._sessionInitiateTimeout = window.setTimeout(() => {
  1461. this._sessionInitiateTimeout = null;
  1462. Statistics.sendAnalytics(createJingleEvent(
  1463. ACTION_JINGLE_SI_TIMEOUT,
  1464. {
  1465. p2p: false,
  1466. value: JINGLE_SI_TIMEOUT
  1467. }));
  1468. }, JINGLE_SI_TIMEOUT);
  1469. }
  1470. };
  1471. /**
  1472. * Mutes a participant.
  1473. * @param {string} id The id of the participant to mute.
  1474. */
  1475. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1476. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1477. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1478. logger.error(`Unsupported media type: ${muteMediaType}`);
  1479. return;
  1480. }
  1481. const participant = this.getParticipantById(id);
  1482. if (!participant) {
  1483. return;
  1484. }
  1485. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1486. };
  1487. /* eslint-disable max-params */
  1488. /**
  1489. * Notifies this JitsiConference that a new member has joined its chat room.
  1490. *
  1491. * FIXME This should NOT be exposed!
  1492. *
  1493. * @param jid the jid of the participant in the MUC
  1494. * @param nick the display name of the participant
  1495. * @param role the role of the participant in the MUC
  1496. * @param isHidden indicates if this is a hidden participant (system
  1497. * participant for example a recorder).
  1498. * @param statsID the participant statsID (optional)
  1499. * @param status the initial status if any
  1500. * @param identity the member identity, if any
  1501. * @param botType the member botType, if any
  1502. * @param fullJid the member full jid, if any
  1503. * @param features the member botType, if any
  1504. * @param isReplaceParticipant whether this join replaces a participant with
  1505. * the same jwt.
  1506. */
  1507. JitsiConference.prototype.onMemberJoined = function(
  1508. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features, isReplaceParticipant) {
  1509. const id = Strophe.getResourceFromJid(jid);
  1510. if (id === 'focus' || this.myUserId() === id) {
  1511. return;
  1512. }
  1513. const participant = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1514. participant.setConnectionJid(fullJid);
  1515. participant.setRole(role);
  1516. participant.setBotType(botType);
  1517. participant.setFeatures(features);
  1518. participant.setIsReplacing(isReplaceParticipant);
  1519. // Set remote tracks on the participant if source signaling was received before presence.
  1520. const remoteTracks = this.isP2PActive()
  1521. ? this.p2pJingleSession?.peerconnection.getRemoteTracks(id) ?? []
  1522. : this.jvbJingleSession?.peerconnection.getRemoteTracks(id) ?? [];
  1523. for (const track of remoteTracks) {
  1524. participant._tracks.push(track);
  1525. }
  1526. this.participants.set(id, participant);
  1527. this.eventEmitter.emit(
  1528. JitsiConferenceEvents.USER_JOINED,
  1529. id,
  1530. participant);
  1531. this._updateFeatures(participant);
  1532. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1533. if (this.isJoined()) {
  1534. this._maybeStartOrStopP2P();
  1535. }
  1536. this._maybeSetSITimeout();
  1537. };
  1538. /* eslint-enable max-params */
  1539. /**
  1540. * Get notified when we joined the room.
  1541. *
  1542. * @private
  1543. */
  1544. JitsiConference.prototype._onMucJoined = function() {
  1545. this._numberOfParticipantsOnJoin = this.getParticipantCount();
  1546. this._maybeStartOrStopP2P();
  1547. };
  1548. /**
  1549. * Updates features for a participant.
  1550. * @param {JitsiParticipant} participant - The participant to query for features.
  1551. * @returns {void}
  1552. * @private
  1553. */
  1554. JitsiConference.prototype._updateFeatures = function(participant) {
  1555. participant.getFeatures()
  1556. .then(features => {
  1557. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1558. this.updateDTMFSupport();
  1559. if (features.has(FEATURE_JIGASI)) {
  1560. participant.setProperty('features_jigasi', true);
  1561. }
  1562. if (features.has(FEATURE_E2EE)) {
  1563. participant.setProperty('features_e2ee', true);
  1564. }
  1565. })
  1566. .catch(() => false);
  1567. };
  1568. /**
  1569. * Get notified when member bot type had changed.
  1570. * @param jid the member jid
  1571. * @param botType the new botType value
  1572. * @private
  1573. */
  1574. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1575. // find the participant and mark it as non bot, as the real one will join
  1576. // in a moment
  1577. const peers = this.getParticipants();
  1578. const botParticipant = peers.find(p => p.getJid() === jid);
  1579. if (botParticipant) {
  1580. botParticipant.setBotType(botType);
  1581. const id = Strophe.getResourceFromJid(jid);
  1582. this.eventEmitter.emit(
  1583. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1584. id,
  1585. botType);
  1586. }
  1587. // if botType changed to undefined, botType was removed, in case of
  1588. // poltergeist mode this is the moment when the poltergeist had exited and
  1589. // the real participant had already replaced it.
  1590. // In this case we can check and try p2p
  1591. if (!botParticipant.getBotType()) {
  1592. this._maybeStartOrStopP2P();
  1593. }
  1594. };
  1595. JitsiConference.prototype.onMemberLeft = function(jid, reason) {
  1596. const id = Strophe.getResourceFromJid(jid);
  1597. if (id === 'focus' || this.myUserId() === id) {
  1598. return;
  1599. }
  1600. const mediaSessions = this.getMediaSessions();
  1601. let tracksToBeRemoved = [];
  1602. for (const session of mediaSessions) {
  1603. const remoteTracks = session.peerconnection.getRemoteTracks(id);
  1604. remoteTracks && (tracksToBeRemoved = [ ...tracksToBeRemoved, ...remoteTracks ]);
  1605. // Update the SSRC owners list.
  1606. session._signalingLayer.updateSsrcOwnersOnLeave(id);
  1607. if (!FeatureFlags.isSsrcRewritingSupported()) {
  1608. // Remove the ssrcs from the remote description and renegotiate.
  1609. session.removeRemoteStreamsOnLeave(id);
  1610. }
  1611. }
  1612. tracksToBeRemoved.forEach(track => {
  1613. if (FeatureFlags.isSsrcRewritingSupported()) {
  1614. track.setSourceName(null);
  1615. track.setOwner(null);
  1616. } else {
  1617. // Fire the event before renegotiation is done so that the thumbnails can be removed immediately.
  1618. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  1619. }
  1620. });
  1621. const participant = this.participants.get(id);
  1622. if (participant) {
  1623. this.participants.delete(id);
  1624. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant, reason);
  1625. }
  1626. if (this.room !== null) { // Skip if we have left the room already.
  1627. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1628. this._maybeClearSITimeout();
  1629. }
  1630. };
  1631. /* eslint-disable max-params */
  1632. /**
  1633. * Designates an event indicating that we were kicked from the XMPP MUC.
  1634. * @param {boolean} isSelfPresence - whether it is for local participant
  1635. * or another participant.
  1636. * @param {string} actorId - the id of the participant who was initiator
  1637. * of the kick.
  1638. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1639. * this is the id of the participant which was kicked.
  1640. * @param {string} reason - reason of the participant to kick
  1641. * @param {boolean?} isReplaceParticipant - whether this is a server initiated kick in order
  1642. * to replace it with a participant with same jwt.
  1643. */
  1644. JitsiConference.prototype.onMemberKicked = function(
  1645. isSelfPresence,
  1646. actorId,
  1647. kickedParticipantId,
  1648. reason,
  1649. isReplaceParticipant) {
  1650. // This check which be true when we kick someone else. With the introduction of lobby
  1651. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1652. // avoid emitting an event where `undefined` kicked someone.
  1653. if (actorId === this.myUserId()) {
  1654. return;
  1655. }
  1656. const actorParticipant = this.participants.get(actorId);
  1657. if (isSelfPresence) {
  1658. this.leave().finally(() => this.xmpp.disconnect());
  1659. this.eventEmitter.emit(
  1660. JitsiConferenceEvents.KICKED, actorParticipant, reason, isReplaceParticipant);
  1661. return;
  1662. }
  1663. const kickedParticipant = this.participants.get(kickedParticipantId);
  1664. kickedParticipant.setIsReplaced(isReplaceParticipant);
  1665. this.eventEmitter.emit(
  1666. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant, reason);
  1667. };
  1668. /**
  1669. * Method called on local MUC role change.
  1670. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1671. */
  1672. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1673. // Emit role changed for local JID
  1674. this.eventEmitter.emit(
  1675. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1676. };
  1677. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1678. const id = Strophe.getResourceFromJid(jid);
  1679. const participant = this.getParticipantById(id);
  1680. if (!participant) {
  1681. return;
  1682. }
  1683. participant.setRole(role);
  1684. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1685. };
  1686. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1687. const id = Strophe.getResourceFromJid(jid);
  1688. const participant = this.getParticipantById(id);
  1689. if (!participant) {
  1690. return;
  1691. }
  1692. if (participant._displayName === displayName) {
  1693. return;
  1694. }
  1695. participant._displayName = displayName;
  1696. this.eventEmitter.emit(
  1697. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1698. id,
  1699. displayName);
  1700. };
  1701. /**
  1702. * Notifies this JitsiConference that a JitsiRemoteTrack was added to the conference.
  1703. *
  1704. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this JitsiConference.
  1705. */
  1706. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1707. if (track.isP2P && !this.isP2PActive()) {
  1708. logger.info('Trying to add remote P2P track, when not in P2P - IGNORED');
  1709. return;
  1710. } else if (!track.isP2P && this.isP2PActive()) {
  1711. logger.info('Trying to add remote JVB track, when in P2P - IGNORED');
  1712. return;
  1713. }
  1714. const id = track.getParticipantId();
  1715. const participant = this.getParticipantById(id);
  1716. // Add track to JitsiParticipant.
  1717. if (participant) {
  1718. participant._tracks.push(track);
  1719. } else {
  1720. logger.info(`Source signaling received before presence for ${id}`);
  1721. }
  1722. const emitter = this.eventEmitter;
  1723. track.addEventListener(
  1724. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1725. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1726. track.isAudioTrack() && track.addEventListener(
  1727. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1728. (audioLevel, tpc) => {
  1729. const activeTPC = this.getActivePeerConnection();
  1730. if (activeTPC === tpc) {
  1731. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  1732. }
  1733. }
  1734. );
  1735. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1736. };
  1737. /**
  1738. * Callback called by the Jingle plugin when 'session-answer' is received.
  1739. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1740. * received.
  1741. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1742. */
  1743. // eslint-disable-next-line no-unused-vars
  1744. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1745. if (this.p2pJingleSession === session) {
  1746. logger.info('P2P setAnswer');
  1747. this.p2pJingleSession.setAnswer(answer);
  1748. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1749. }
  1750. };
  1751. /**
  1752. * Callback called by the Jingle plugin when 'transport-info' is received.
  1753. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1754. * received
  1755. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1756. * element
  1757. */
  1758. // eslint-disable-next-line no-unused-vars
  1759. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1760. if (this.p2pJingleSession === session) {
  1761. logger.info('P2P addIceCandidates');
  1762. this.p2pJingleSession.addIceCandidates(transportInfo);
  1763. }
  1764. };
  1765. /**
  1766. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1767. * the conference.
  1768. *
  1769. * @param {JitsiRemoteTrack} removedTrack
  1770. */
  1771. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1772. this.getParticipants().forEach(participant => {
  1773. const tracks = participant.getTracks();
  1774. for (let i = 0; i < tracks.length; i++) {
  1775. if (tracks[i] === removedTrack) {
  1776. // Since the tracks have been compared and are
  1777. // considered equal the result of splice can be ignored.
  1778. participant._tracks.splice(i, 1);
  1779. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1780. break;
  1781. }
  1782. }
  1783. }, this);
  1784. };
  1785. /**
  1786. * Handles an incoming call event for the P2P jingle session.
  1787. */
  1788. JitsiConference.prototype._onIncomingCallP2P = function(jingleSession, jingleOffer) {
  1789. let rejectReason;
  1790. const contentName = jingleOffer.find('>content').attr('name');
  1791. const peerUsesUnifiedPlan = contentName === '0' || contentName === '1';
  1792. // Reject P2P between endpoints that are not running in the same mode w.r.t to SDPs (plan-b and unified plan).
  1793. if (!peerUsesUnifiedPlan) {
  1794. rejectReason = {
  1795. reason: 'decline',
  1796. reasonDescription: 'P2P disabled',
  1797. errorMsg: 'P2P across two endpoints in different SDP modes is disabled'
  1798. };
  1799. } else if ((!this.isP2PEnabled() && !this.isP2PTestModeEnabled())
  1800. || (browser.isFirefox() && !this._firefoxP2pEnabled)) {
  1801. rejectReason = {
  1802. reason: 'decline',
  1803. reasonDescription: 'P2P disabled',
  1804. errorMsg: 'P2P mode disabled in the configuration or browser unsupported'
  1805. };
  1806. } else if (this.p2pJingleSession) {
  1807. // Reject incoming P2P call (already in progress)
  1808. rejectReason = {
  1809. reason: 'busy',
  1810. reasonDescription: 'P2P already in progress',
  1811. errorMsg: 'Duplicated P2P "session-initiate"'
  1812. };
  1813. } else if (!this._shouldBeInP2PMode()) {
  1814. rejectReason = {
  1815. reason: 'decline',
  1816. reasonDescription: 'P2P requirements not met',
  1817. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1818. };
  1819. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1820. }
  1821. if (rejectReason) {
  1822. this._rejectIncomingCall(jingleSession, rejectReason);
  1823. } else {
  1824. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1825. }
  1826. };
  1827. /**
  1828. * Handles an incoming call event.
  1829. */
  1830. JitsiConference.prototype.onIncomingCall = function(jingleSession, jingleOffer, now) {
  1831. // Handle incoming P2P call
  1832. if (jingleSession.isP2P) {
  1833. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1834. } else {
  1835. if (!this.isFocus(jingleSession.remoteJid)) {
  1836. const description = 'Rejecting session-initiate from non-focus.';
  1837. this._rejectIncomingCall(
  1838. jingleSession, {
  1839. reason: 'security-error',
  1840. reasonDescription: description,
  1841. errorMsg: description
  1842. });
  1843. return;
  1844. }
  1845. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1846. }
  1847. };
  1848. /**
  1849. * Accepts an incoming call event for the JVB jingle session.
  1850. */
  1851. JitsiConference.prototype._acceptJvbIncomingCall = function(jingleSession, jingleOffer, now) {
  1852. // Accept incoming call
  1853. this.jvbJingleSession = jingleSession;
  1854. this.room.connectionTimes['session.initiate'] = now;
  1855. this._sendConferenceJoinAnalyticsEvent();
  1856. if (this.wasStopped) {
  1857. Statistics.sendAnalyticsAndLog(createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1858. }
  1859. const serverRegion
  1860. = $(jingleOffer)
  1861. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1862. .attr('region');
  1863. this.eventEmitter.emit(JitsiConferenceEvents.SERVER_REGION_CHANGED, serverRegion);
  1864. this._maybeClearSITimeout();
  1865. Statistics.sendAnalytics(createJingleEvent(
  1866. ACTION_JINGLE_SI_RECEIVED,
  1867. {
  1868. p2p: false,
  1869. value: now
  1870. }));
  1871. try {
  1872. jingleSession.initialize(
  1873. this.room,
  1874. this.rtc,
  1875. this._signalingLayer,
  1876. {
  1877. ...this.options.config,
  1878. codecSettings: {
  1879. mediaType: MediaType.VIDEO,
  1880. codecList: this.codecSelection.getCodecPreferenceList('jvb')
  1881. },
  1882. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  1883. });
  1884. } catch (error) {
  1885. logger.error(error);
  1886. return;
  1887. }
  1888. // Open a channel with the videobridge.
  1889. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1890. const localTracks = this._getInitialLocalTracks();
  1891. try {
  1892. jingleSession.acceptOffer(
  1893. jingleOffer,
  1894. () => {
  1895. // If for any reason invite for the JVB session arrived after
  1896. // the P2P has been established already the media transfer needs
  1897. // to be turned off here.
  1898. if (this.isP2PActive() && this.jvbJingleSession) {
  1899. this._suspendMediaTransferForJvbConnection();
  1900. }
  1901. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, jingleSession);
  1902. if (!this.isP2PActive()) {
  1903. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, jingleSession);
  1904. }
  1905. },
  1906. error => {
  1907. logger.error('Failed to accept incoming Jingle session', error);
  1908. },
  1909. localTracks
  1910. );
  1911. // Set the capture fps for screenshare if it is set through the UI.
  1912. this._desktopSharingFrameRate
  1913. && jingleSession.peerconnection.setDesktopSharingFrameRate(this._desktopSharingFrameRate);
  1914. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1915. } catch (e) {
  1916. logger.error(e);
  1917. }
  1918. };
  1919. /**
  1920. * Sets the BridgeChannel.
  1921. *
  1922. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1923. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1924. * BridgeChannel mode.
  1925. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1926. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1927. */
  1928. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1929. const ignoreDomain = this.connection?.options?.bridgeChannel?.ignoreDomain;
  1930. const preferSctp = this.connection?.options?.bridgeChannel?.preferSctp ?? false;
  1931. const sctpOffered = $(offerIq).find('>content[name="data"]')
  1932. .first().length === 1;
  1933. let wsUrl = null;
  1934. logger.info(`SCTP: offered=${sctpOffered}, prefered=${preferSctp}`);
  1935. if (!(sctpOffered && preferSctp)) {
  1936. $(offerIq).find('>content>transport>web-socket')
  1937. .toArray()
  1938. .map(e => e.getAttribute('url'))
  1939. .forEach(url => {
  1940. if (!wsUrl && (!ignoreDomain || ignoreDomain !== new URL(url).hostname)) {
  1941. wsUrl = url;
  1942. logger.info(`Using colibri-ws url ${url}`);
  1943. } else if (!wsUrl) {
  1944. logger.info(`Ignoring colibri-ws url with domain ${ignoreDomain}`);
  1945. }
  1946. });
  1947. if (!wsUrl) {
  1948. const firstWsUrl = $(offerIq).find('>content>transport>web-socket')
  1949. .first();
  1950. if (firstWsUrl.length === 1) {
  1951. wsUrl = firstWsUrl[0].getAttribute('url');
  1952. logger.info(`Falling back to ${wsUrl}`);
  1953. }
  1954. }
  1955. }
  1956. if (wsUrl && !(sctpOffered && preferSctp)) {
  1957. // If the offer contains a websocket and we don't prefer SCTP use it.
  1958. this.rtc.initializeBridgeChannel(null, wsUrl);
  1959. } else if (sctpOffered) {
  1960. // Otherwise, fall back to an attempt to use SCTP.
  1961. this.rtc.initializeBridgeChannel(pc, null);
  1962. } else {
  1963. logger.warn('Neither SCTP nor a websocket is available. Will not initialize bridge channel.');
  1964. }
  1965. };
  1966. /**
  1967. * Rejects incoming Jingle call.
  1968. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1969. * @param {object} [options]
  1970. * @param {string} options.reason the name of the reason element as defined
  1971. * by Jingle
  1972. * @param {string} options.reasonDescription the reason description which will
  1973. * be included in Jingle 'session-terminate' message.
  1974. * @param {string} options.errorMsg an error message to be logged on global
  1975. * error handler
  1976. * @private
  1977. */
  1978. JitsiConference.prototype._rejectIncomingCall = function(jingleSession, options) {
  1979. if (options?.errorMsg) {
  1980. logger.warn(options.errorMsg);
  1981. }
  1982. // Terminate the jingle session with a reason
  1983. jingleSession.terminate(
  1984. null /* success callback => we don't care */,
  1985. error => {
  1986. logger.warn(
  1987. 'An error occurred while trying to terminate'
  1988. + ' invalid Jingle session', error);
  1989. }, {
  1990. reason: options && options.reason,
  1991. reasonDescription: options && options.reasonDescription,
  1992. sendSessionTerminate: true
  1993. });
  1994. };
  1995. /**
  1996. * Handles the call ended event.
  1997. * XXX is this due to the remote side terminating the Jingle session?
  1998. *
  1999. * @param {JingleSessionPC} jingleSession the jingle session which has been
  2000. * terminated.
  2001. * @param {String} reasonCondition the Jingle reason condition.
  2002. * @param {String|null} reasonText human readable reason text which may provide
  2003. * more details about why the call has been terminated.
  2004. */
  2005. JitsiConference.prototype.onCallEnded = function(jingleSession, reasonCondition, reasonText) {
  2006. logger.info(
  2007. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  2008. jingleSession.isP2P}`);
  2009. if (jingleSession === this.jvbJingleSession) {
  2010. this.wasStopped = true;
  2011. Statistics.sendAnalytics(
  2012. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  2013. // Stop the stats
  2014. if (this.statistics) {
  2015. this.statistics.stopRemoteStats(this.jvbJingleSession.peerconnection);
  2016. }
  2017. // Current JVB JingleSession is no longer valid, so set it to null
  2018. this.jvbJingleSession = null;
  2019. // Let the RTC service do any cleanups
  2020. this.rtc.onCallEnded();
  2021. } else if (jingleSession === this.p2pJingleSession) {
  2022. const stopOptions = {};
  2023. if (reasonCondition === 'connectivity-error' && reasonText === 'ICE FAILED') {
  2024. // It can happen that the other peer detects ICE failed and terminates the session, before we get the event
  2025. // on our side. But we are able to parse the reason and mark it here.
  2026. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2027. } else if (reasonCondition === 'success' && reasonText === 'restart') {
  2028. // When we are restarting media sessions we don't want to switch the tracks to the JVB just yet.
  2029. stopOptions.requestRestart = true;
  2030. }
  2031. this._stopP2PSession(stopOptions);
  2032. } else {
  2033. logger.error(
  2034. 'Received onCallEnded for invalid session',
  2035. jingleSession.sid,
  2036. jingleSession.remoteJid,
  2037. reasonCondition,
  2038. reasonText);
  2039. }
  2040. };
  2041. /**
  2042. * Handles the suspend detected event. Leaves the room and fires suspended.
  2043. * @param {JingleSessionPC} jingleSession
  2044. */
  2045. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  2046. if (!jingleSession.isP2P) {
  2047. this.leave();
  2048. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  2049. }
  2050. };
  2051. JitsiConference.prototype.updateDTMFSupport = function() {
  2052. let somebodySupportsDTMF = false;
  2053. const participants = this.getParticipants();
  2054. // check if at least 1 participant supports DTMF
  2055. for (let i = 0; i < participants.length; i += 1) {
  2056. if (participants[i].supportsDTMF()) {
  2057. somebodySupportsDTMF = true;
  2058. break;
  2059. }
  2060. }
  2061. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  2062. this.somebodySupportsDTMF = somebodySupportsDTMF;
  2063. this.eventEmitter.emit(
  2064. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  2065. somebodySupportsDTMF);
  2066. }
  2067. };
  2068. /**
  2069. * Allows to check if there is at least one user in the conference
  2070. * that supports DTMF.
  2071. * @returns {boolean} true if somebody supports DTMF, false otherwise
  2072. */
  2073. JitsiConference.prototype.isDTMFSupported = function() {
  2074. return this.somebodySupportsDTMF;
  2075. };
  2076. /**
  2077. * Returns the local user's ID
  2078. * @return {string} local user's ID
  2079. */
  2080. JitsiConference.prototype.myUserId = function() {
  2081. return (
  2082. this.room && this.room.myroomjid
  2083. ? Strophe.getResourceFromJid(this.room.myroomjid)
  2084. : null);
  2085. };
  2086. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  2087. const peerConnection = this.getActivePeerConnection();
  2088. if (peerConnection) {
  2089. peerConnection.sendTones(tones, duration, pause);
  2090. } else {
  2091. logger.warn('cannot sendTones: no peer connection');
  2092. }
  2093. };
  2094. /**
  2095. * Starts recording the current conference.
  2096. *
  2097. * @param {Object} options - Configuration for the recording. See
  2098. * {@link Chatroom#startRecording} for more info.
  2099. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  2100. */
  2101. JitsiConference.prototype.startRecording = function(options) {
  2102. if (this.room) {
  2103. return this.recordingManager.startRecording(options);
  2104. }
  2105. return Promise.reject(new Error('The conference is not created yet!'));
  2106. };
  2107. /**
  2108. * Stop a recording session.
  2109. *
  2110. * @param {string} sessionID - The ID of the recording session that
  2111. * should be stopped.
  2112. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  2113. */
  2114. JitsiConference.prototype.stopRecording = function(sessionID) {
  2115. if (this.room) {
  2116. return this.recordingManager.stopRecording(sessionID);
  2117. }
  2118. return Promise.reject(new Error('The conference is not created yet!'));
  2119. };
  2120. /**
  2121. * Returns true if the SIP calls are supported and false otherwise
  2122. */
  2123. JitsiConference.prototype.isSIPCallingSupported = function() {
  2124. return this.room?.xmpp?.moderator?.isSipGatewayEnabled() ?? false;
  2125. };
  2126. /**
  2127. * Dials a number.
  2128. * @param number the number
  2129. */
  2130. JitsiConference.prototype.dial = function(number) {
  2131. if (this.room) {
  2132. return this.room.dial(number);
  2133. }
  2134. return Promise.reject(new Error('The conference is not created yet!'));
  2135. };
  2136. /**
  2137. * Hangup an existing call
  2138. */
  2139. JitsiConference.prototype.hangup = function() {
  2140. if (this.room) {
  2141. return this.room.hangup();
  2142. }
  2143. return Promise.resolve();
  2144. };
  2145. /**
  2146. * Returns the phone number for joining the conference.
  2147. */
  2148. JitsiConference.prototype.getPhoneNumber = function() {
  2149. if (this.room) {
  2150. return this.room.getPhoneNumber();
  2151. }
  2152. return null;
  2153. };
  2154. /**
  2155. * Returns the pin for joining the conference with phone.
  2156. */
  2157. JitsiConference.prototype.getPhonePin = function() {
  2158. if (this.room) {
  2159. return this.room.getPhonePin();
  2160. }
  2161. return null;
  2162. };
  2163. /**
  2164. * Returns the meeting unique ID if any.
  2165. *
  2166. * @returns {string|undefined}
  2167. */
  2168. JitsiConference.prototype.getMeetingUniqueId = function() {
  2169. if (this.room) {
  2170. return this.room.getMeetingId();
  2171. }
  2172. };
  2173. /**
  2174. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2175. * which connection is currently active.
  2176. *
  2177. * @return {TraceablePeerConnection|null} null if there isn't any active
  2178. * <tt>TraceablePeerConnection</tt> currently available.
  2179. * @public (FIXME how to make package local ?)
  2180. */
  2181. JitsiConference.prototype.getActivePeerConnection = function() {
  2182. const session = this.isP2PActive() ? this.p2pJingleSession : this.jvbJingleSession;
  2183. return session ? session.peerconnection : null;
  2184. };
  2185. /**
  2186. * Returns the connection state for the current room. Its ice connection state
  2187. * for its session.
  2188. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2189. * be converted to "connected".
  2190. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2191. * peer connection at this time.
  2192. */
  2193. JitsiConference.prototype.getConnectionState = function() {
  2194. const peerConnection = this.getActivePeerConnection();
  2195. return peerConnection ? peerConnection.getConnectionState() : null;
  2196. };
  2197. /**
  2198. * Make all new participants mute their audio/video on join.
  2199. * @param policy {Object} object with 2 boolean properties for video and audio:
  2200. * @param {boolean} audio if audio should be muted.
  2201. * @param {boolean} video if video should be muted.
  2202. */
  2203. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2204. if (!this.isModerator()) {
  2205. logger.warn(`Failed to set start muted policy, ${this.room ? '' : 'not in a room, '}${
  2206. this.isModerator() ? '' : 'participant is not a moderator'}`);
  2207. return;
  2208. }
  2209. // Do not apply the startMutedPolicy locally on the moderator, the moderator should join with available local
  2210. // sources and the policy needs to be applied only on users that join the call after.
  2211. // this.startMutedPolicy = policy;
  2212. this.room.addOrReplaceInPresence('startmuted', {
  2213. attributes: {
  2214. audio: policy.audio,
  2215. video: policy.video,
  2216. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2217. }
  2218. }) && this.room.sendPresence();
  2219. };
  2220. /**
  2221. * Returns current start muted policy
  2222. * @returns {Object} with 2 properties - audio and video.
  2223. */
  2224. JitsiConference.prototype.getStartMutedPolicy = function() {
  2225. return this.startMutedPolicy;
  2226. };
  2227. /**
  2228. * Check if audio is muted on join.
  2229. */
  2230. JitsiConference.prototype.isStartAudioMuted = function() {
  2231. return this.startAudioMuted;
  2232. };
  2233. /**
  2234. * Check if video is muted on join.
  2235. */
  2236. JitsiConference.prototype.isStartVideoMuted = function() {
  2237. return this.startVideoMuted;
  2238. };
  2239. /**
  2240. * Returns measured connectionTimes.
  2241. */
  2242. JitsiConference.prototype.getConnectionTimes = function() {
  2243. return this.room.connectionTimes;
  2244. };
  2245. /**
  2246. * Sets a property for the local participant.
  2247. */
  2248. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2249. this.sendCommand(`jitsi_participant_${name}`, { value });
  2250. };
  2251. /**
  2252. * Removes a property for the local participant and sends the updated presence.
  2253. */
  2254. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2255. this.removeCommand(`jitsi_participant_${name}`);
  2256. this.room.sendPresence();
  2257. };
  2258. /**
  2259. * Gets a local participant property.
  2260. *
  2261. * @return value of the local participant property if the tagName exists in the
  2262. * list of properties, otherwise returns undefined.
  2263. */
  2264. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2265. const property = this.room.presMap.nodes.find(prop =>
  2266. prop.tagName === `jitsi_participant_${name}`
  2267. );
  2268. return property ? property.value : undefined;
  2269. };
  2270. /**
  2271. * Sends the given feedback if enabled.
  2272. *
  2273. * @param overallFeedback an integer between 1 and 5 indicating the
  2274. * user feedback
  2275. * @param detailedFeedback detailed feedback from the user. Not yet used
  2276. * @returns {Promise} Resolves if feedback is submitted successfully.
  2277. */
  2278. JitsiConference.prototype.sendFeedback = function(overallFeedback, detailedFeedback) {
  2279. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2280. };
  2281. /**
  2282. * @returns false, since callstats in not supported anymore.
  2283. * @deprecated
  2284. */
  2285. JitsiConference.prototype.isCallstatsEnabled = function() {
  2286. logger.warn('Callstats is no longer supported');
  2287. return false;
  2288. };
  2289. /**
  2290. * Finds the SSRC of a given track
  2291. *
  2292. * @param track
  2293. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2294. */
  2295. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2296. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2297. };
  2298. /**
  2299. * This is a no-op since callstats is no longer supported.
  2300. */
  2301. // eslint-disable-next-line no-empty-function
  2302. JitsiConference.prototype.sendApplicationLog = function() { };
  2303. /**
  2304. * Checks if the user identified by given <tt>mucJid</tt> is the conference focus.
  2305. * @param mucJid the full MUC address of the user to be checked.
  2306. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2307. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2308. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2309. */
  2310. JitsiConference.prototype.isFocus = function(mucJid) {
  2311. return this.room ? this.room.isFocus(mucJid) : null;
  2312. };
  2313. /**
  2314. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2315. */
  2316. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2317. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2318. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2319. };
  2320. /**
  2321. * Sends a message via the data channel.
  2322. * @param to {string} the id of the endpoint that should receive the message.
  2323. * If "" the message will be sent to all participants.
  2324. * @param payload {object} the payload of the message.
  2325. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2326. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2327. */
  2328. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2329. this.rtc.sendChannelMessage(to, payload);
  2330. };
  2331. /**
  2332. * Sends local stats via the bridge channel which then forwards to other endpoints selectively.
  2333. * @param {Object} payload The payload of the message.
  2334. * @throws NetworkError/InvalidStateError/Error if the operation fails or if there is no data channel created.
  2335. */
  2336. JitsiConference.prototype.sendEndpointStatsMessage = function(payload) {
  2337. this.rtc.sendEndpointStatsMessage(payload);
  2338. };
  2339. /**
  2340. * Sends a broadcast message via the data channel.
  2341. * @param payload {object} the payload of the message.
  2342. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2343. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2344. */
  2345. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2346. this.sendEndpointMessage('', payload);
  2347. };
  2348. /**
  2349. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2350. * broadcasts it to all endpoints in the conference.
  2351. * @param {string} to The ID of the endpoint/participant which is to receive
  2352. * the message, or '' to broadcast the message to all endpoints in the
  2353. * conference.
  2354. * @param {string|object} message the message to send. If this is of type
  2355. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2356. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2357. * JSON before being sent.
  2358. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2359. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2360. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2361. */
  2362. JitsiConference.prototype.sendMessage = function(message, to = '', sendThroughVideobridge = false) {
  2363. const messageType = typeof message;
  2364. // Through videobridge we support only objects. Through XMPP we support
  2365. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2366. // regular chat messages).
  2367. if (messageType !== 'object'
  2368. && (sendThroughVideobridge || messageType !== 'string')) {
  2369. logger.error(`Can not send a message of type ${messageType}`);
  2370. return;
  2371. }
  2372. if (sendThroughVideobridge) {
  2373. this.sendEndpointMessage(to, message);
  2374. } else {
  2375. let messageToSend = message;
  2376. // Name of packet extension of message stanza to send the required
  2377. // message in.
  2378. let elementName = 'body';
  2379. if (messageType === 'object') {
  2380. elementName = 'json-message';
  2381. // Mark as valid JSON message if not already
  2382. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2383. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2384. }
  2385. try {
  2386. messageToSend = JSON.stringify(messageToSend);
  2387. } catch (e) {
  2388. logger.error('Can not send a message, stringify failed: ', e);
  2389. return;
  2390. }
  2391. }
  2392. if (to) {
  2393. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2394. } else {
  2395. // Broadcast
  2396. this.sendTextMessage(messageToSend, elementName);
  2397. }
  2398. }
  2399. };
  2400. JitsiConference.prototype.isConnectionInterrupted = function() {
  2401. return this.isP2PActive()
  2402. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2403. };
  2404. /**
  2405. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2406. * and Jicofo moves conferences away to a different bridge.
  2407. * @param {JingleSessionPC} session
  2408. * @private
  2409. */
  2410. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2411. if (!session.isP2P && this.options.config.enableForcedReload) {
  2412. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2413. }
  2414. };
  2415. /**
  2416. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2417. * @param {JingleSessionPC} session
  2418. * @private
  2419. */
  2420. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2421. if (session.isP2P) {
  2422. this.isP2PConnectionInterrupted = true;
  2423. } else {
  2424. this.isJvbConnectionInterrupted = true;
  2425. }
  2426. if (session.isP2P === this.isP2PActive()) {
  2427. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2428. }
  2429. };
  2430. /**
  2431. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2432. * @param {JingleSessionPC} session
  2433. * @private
  2434. */
  2435. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2436. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2437. // eventually come up with the new offer (at least for the time being).
  2438. if (session.isP2P) {
  2439. // Add p2pFailed property to analytics to distinguish, between "good"
  2440. // and "bad" connection
  2441. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2442. if (this.p2pJingleSession) {
  2443. Statistics.sendAnalyticsAndLog(
  2444. createP2PEvent(
  2445. ACTION_P2P_FAILED,
  2446. {
  2447. initiator: this.p2pJingleSession.isInitiator
  2448. }));
  2449. }
  2450. this._stopP2PSession({
  2451. reason: 'connectivity-error',
  2452. reasonDescription: 'ICE FAILED'
  2453. });
  2454. } else if (session && this.jvbJingleSession === session) {
  2455. this._delayedIceFailed = new IceFailedHandling(this);
  2456. this._delayedIceFailed.start(session);
  2457. }
  2458. };
  2459. /**
  2460. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2461. * @param {JingleSessionPC} session
  2462. * @private
  2463. */
  2464. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2465. if (session.isP2P) {
  2466. this.isP2PConnectionInterrupted = false;
  2467. } else {
  2468. this.isJvbConnectionInterrupted = false;
  2469. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2470. }
  2471. if (session.isP2P === this.isP2PActive()) {
  2472. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2473. }
  2474. };
  2475. /**
  2476. * Accept incoming P2P Jingle call.
  2477. * @param {JingleSessionPC} jingleSession the session instance
  2478. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2479. * @private
  2480. */
  2481. JitsiConference.prototype._acceptP2PIncomingCall = function(jingleSession, jingleOffer) {
  2482. this.isP2PConnectionInterrupted = false;
  2483. // Accept the offer
  2484. this.p2pJingleSession = jingleSession;
  2485. this._sendConferenceJoinAnalyticsEvent();
  2486. this.p2pJingleSession.initialize(
  2487. this.room,
  2488. this.rtc,
  2489. this._signalingLayer,
  2490. {
  2491. ...this.options.config,
  2492. codecSettings: {
  2493. mediaType: MediaType.VIDEO,
  2494. codecList: this.codecSelection.getCodecPreferenceList('p2p')
  2495. },
  2496. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2497. });
  2498. const localTracks = this.getLocalTracks();
  2499. this.p2pJingleSession.acceptOffer(
  2500. jingleOffer,
  2501. () => {
  2502. logger.debug('Got RESULT for P2P "session-accept"');
  2503. this.eventEmitter.emit(
  2504. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2505. jingleSession);
  2506. },
  2507. error => {
  2508. logger.error(
  2509. 'Failed to accept incoming P2P Jingle session', error);
  2510. },
  2511. localTracks);
  2512. };
  2513. /**
  2514. * Adds remote tracks to the conference associated with the JVB session.
  2515. * @private
  2516. */
  2517. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2518. this._addRemoteTracks('JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2519. };
  2520. /**
  2521. * Adds remote tracks to the conference associated with the P2P session.
  2522. * @private
  2523. */
  2524. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2525. this._addRemoteTracks('P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2526. };
  2527. /**
  2528. * Generates fake "remote track added" events for given Jingle session.
  2529. * @param {string} logName the session's nickname which will appear in log messages.
  2530. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2531. * @private
  2532. */
  2533. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2534. for (const track of remoteTracks) {
  2535. // There will be orphan (with no owner) tracks when ssrc-rewriting is enabled and all of them need to be addded
  2536. // back to the conference.
  2537. if (FeatureFlags.isSsrcRewritingSupported() || this.participants.has(track.ownerEndpointId)) {
  2538. logger.info(`Adding remote ${logName} track: ${track}`);
  2539. this.onRemoteTrackAdded(track);
  2540. }
  2541. }
  2542. };
  2543. /**
  2544. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2545. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2546. * the P2P connection if the event comes from the P2P session.
  2547. * @param {JingleSessionPC} jingleSession the session instance.
  2548. * @private
  2549. */
  2550. JitsiConference.prototype._onIceConnectionEstablished = function(jingleSession) {
  2551. if (this.p2pJingleSession !== null) {
  2552. // store the establishment time of the p2p session as a field of the
  2553. // JitsiConference because the p2pJingleSession might get disposed (thus
  2554. // the value is lost).
  2555. this.p2pEstablishmentDuration
  2556. = this.p2pJingleSession.establishmentDuration;
  2557. }
  2558. if (this.jvbJingleSession !== null) {
  2559. this.jvbEstablishmentDuration
  2560. = this.jvbJingleSession.establishmentDuration;
  2561. }
  2562. let done = false;
  2563. // We don't care about the JVB case, there's nothing to be done
  2564. if (!jingleSession.isP2P) {
  2565. done = true;
  2566. } else if (this.p2pJingleSession !== jingleSession) {
  2567. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2568. done = true;
  2569. }
  2570. if (!isNaN(this.p2pEstablishmentDuration)
  2571. && !isNaN(this.jvbEstablishmentDuration)) {
  2572. const establishmentDurationDiff
  2573. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2574. Statistics.sendAnalytics(
  2575. ICE_ESTABLISHMENT_DURATION_DIFF,
  2576. { value: establishmentDurationDiff });
  2577. }
  2578. if (jingleSession.isP2P === this.isP2PActive()) {
  2579. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2580. }
  2581. if (done) {
  2582. return;
  2583. }
  2584. // Update P2P status and emit events
  2585. this._setP2PStatus(true);
  2586. // Remove remote tracks
  2587. if (this.jvbJingleSession) {
  2588. this._removeRemoteJVBTracks();
  2589. } else {
  2590. logger.info('Not removing remote JVB tracks - no session yet');
  2591. }
  2592. this._addRemoteP2PTracks();
  2593. // Stop media transfer over the JVB connection
  2594. if (this.jvbJingleSession) {
  2595. this._suspendMediaTransferForJvbConnection();
  2596. }
  2597. logger.info('Starting remote stats with p2p connection');
  2598. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2599. Statistics.sendAnalyticsAndLog(
  2600. createP2PEvent(
  2601. ACTION_P2P_ESTABLISHED,
  2602. {
  2603. initiator: this.p2pJingleSession.isInitiator
  2604. }));
  2605. };
  2606. /**
  2607. * Called when the chat room reads a new list of properties from jicofo's
  2608. * presence. The properties may have changed, but they don't have to.
  2609. *
  2610. * @param {Object} properties - The properties keyed by the property name
  2611. * ('key').
  2612. * @private
  2613. */
  2614. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2615. const changed = !isEqual(properties, this.properties);
  2616. this.properties = properties;
  2617. if (changed) {
  2618. this.eventEmitter.emit(JitsiConferenceEvents.PROPERTIES_CHANGED, this.properties);
  2619. const audioLimitReached = this.properties['audio-limit-reached'] === 'true';
  2620. const videoLimitReached = this.properties['video-limit-reached'] === 'true';
  2621. if (this._audioSenderLimitReached !== audioLimitReached) {
  2622. this._audioSenderLimitReached = audioLimitReached;
  2623. this.eventEmitter.emit(JitsiConferenceEvents.AUDIO_UNMUTE_PERMISSIONS_CHANGED, audioLimitReached);
  2624. logger.info(`Audio unmute permissions set by Jicofo to ${audioLimitReached}`);
  2625. }
  2626. if (this._videoSenderLimitReached !== videoLimitReached) {
  2627. this._videoSenderLimitReached = videoLimitReached;
  2628. this.eventEmitter.emit(JitsiConferenceEvents.VIDEO_UNMUTE_PERMISSIONS_CHANGED, videoLimitReached);
  2629. logger.info(`Video unmute permissions set by Jicofo to ${videoLimitReached}`);
  2630. }
  2631. // Some of the properties need to be added to analytics events.
  2632. const analyticsKeys = [
  2633. // The number of jitsi-videobridge instances currently used for the
  2634. // conference.
  2635. 'bridge-count'
  2636. ];
  2637. analyticsKeys.forEach(key => {
  2638. if (properties[key] !== undefined) {
  2639. Statistics.analytics.addPermanentProperties({
  2640. [key.replace('-', '_')]: properties[key]
  2641. });
  2642. }
  2643. });
  2644. // Handle changes to aggregate list of visitor codecs.
  2645. let publishedCodecs = this.properties['visitor-codecs']?.split(',');
  2646. if (publishedCodecs?.length) {
  2647. publishedCodecs = publishedCodecs.filter(codec => typeof codec === 'string'
  2648. && codec.trim().length
  2649. && Object.values(CodecMimeType).find(val => val === codec));
  2650. }
  2651. if (this._visitorCodecs !== publishedCodecs) {
  2652. this._visitorCodecs = publishedCodecs;
  2653. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_VISITOR_CODECS_CHANGED, this._visitorCodecs);
  2654. }
  2655. const oldValue = this._hasVisitors;
  2656. this._hasVisitors = this.properties['visitor-count'] > 0;
  2657. oldValue !== this._hasVisitors && this._maybeStartOrStopP2P(true);
  2658. }
  2659. };
  2660. /**
  2661. * Gets a conference property with a given key.
  2662. *
  2663. * @param {string} key - The key.
  2664. * @returns {*} The value
  2665. */
  2666. JitsiConference.prototype.getProperty = function(key) {
  2667. return this.properties[key];
  2668. };
  2669. /**
  2670. * Clears the deferred start P2P task if it has been scheduled.
  2671. * @private
  2672. */
  2673. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2674. if (this.deferredStartP2PTask) {
  2675. logger.info('Cleared deferred start P2P task');
  2676. clearTimeout(this.deferredStartP2PTask);
  2677. this.deferredStartP2PTask = null;
  2678. }
  2679. };
  2680. /**
  2681. * Removes from the conference remote tracks associated with the JVB
  2682. * connection.
  2683. * @private
  2684. */
  2685. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2686. this._removeRemoteTracks(
  2687. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2688. };
  2689. /**
  2690. * Removes from the conference remote tracks associated with the P2P
  2691. * connection.
  2692. * @private
  2693. */
  2694. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2695. this._removeRemoteTracks(
  2696. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2697. };
  2698. /**
  2699. * Generates fake "remote track removed" events for given Jingle session.
  2700. * @param {string} sessionNickname the session's nickname which will appear in
  2701. * log messages.
  2702. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2703. * @private
  2704. */
  2705. JitsiConference.prototype._removeRemoteTracks = function(sessionNickname, remoteTracks) {
  2706. for (const track of remoteTracks) {
  2707. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2708. this.onRemoteTrackRemoved(track);
  2709. }
  2710. };
  2711. /**
  2712. * Resumes media transfer over the JVB connection.
  2713. * @private
  2714. */
  2715. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2716. logger.info('Resuming media transfer over the JVB connection...');
  2717. this.jvbJingleSession.setMediaTransferActive(true)
  2718. .then(() => {
  2719. logger.info('Resumed media transfer over the JVB connection!');
  2720. })
  2721. .catch(error => {
  2722. logger.error('Failed to resume media transfer over the JVB connection:', error);
  2723. });
  2724. };
  2725. /**
  2726. * Sets new P2P status and updates some events/states hijacked from
  2727. * the <tt>JitsiConference</tt>.
  2728. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2729. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2730. * @private
  2731. */
  2732. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2733. if (this.p2p === newStatus) {
  2734. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2735. return;
  2736. }
  2737. this.p2p = newStatus;
  2738. if (newStatus) {
  2739. logger.info('Peer to peer connection established!');
  2740. // When we end up in a valid P2P session need to reset the properties
  2741. // in case they have persisted, after session with another peer.
  2742. Statistics.analytics.addPermanentProperties({
  2743. p2pFailed: false
  2744. });
  2745. // Sync up video transfer active in case p2pJingleSession not existed
  2746. // when the lastN value was being adjusted.
  2747. const isVideoActive = this.getLastN() !== 0;
  2748. this.p2pJingleSession.setP2pVideoTransferActive(isVideoActive)
  2749. .catch(error => {
  2750. logger.error(`Failed to sync up P2P video transfer status (${isVideoActive}), ${error}`);
  2751. });
  2752. } else {
  2753. logger.info('Peer to peer connection closed!');
  2754. }
  2755. // Clear dtmfManager, so that it can be recreated with new connection
  2756. this.dtmfManager = null;
  2757. // Update P2P status
  2758. this.eventEmitter.emit(
  2759. JitsiConferenceEvents.P2P_STATUS,
  2760. this,
  2761. this.p2p);
  2762. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED, this.getActiveMediaSession());
  2763. // Refresh connection interrupted/restored
  2764. this.eventEmitter.emit(
  2765. this.isConnectionInterrupted()
  2766. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2767. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2768. };
  2769. /**
  2770. * Starts new P2P session.
  2771. * @param {string} remoteJid the JID of the remote participant
  2772. * @private
  2773. */
  2774. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2775. this._maybeClearDeferredStartP2P();
  2776. if (this.p2pJingleSession) {
  2777. logger.error('P2P session already started!');
  2778. return;
  2779. }
  2780. this.isP2PConnectionInterrupted = false;
  2781. this.p2pJingleSession
  2782. = this.xmpp.connection.jingle.newP2PJingleSession(
  2783. this.room.myroomjid,
  2784. remoteJid);
  2785. logger.info(
  2786. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2787. this._sendConferenceJoinAnalyticsEvent();
  2788. this.p2pJingleSession.initialize(
  2789. this.room,
  2790. this.rtc,
  2791. this._signalingLayer,
  2792. {
  2793. ...this.options.config,
  2794. codecSettings: {
  2795. mediaType: MediaType.VIDEO,
  2796. codecList: this.codecSelection.getCodecPreferenceList('p2p')
  2797. },
  2798. enableInsertableStreams: this.isE2EEEnabled() || FeatureFlags.isRunInLiteModeEnabled()
  2799. });
  2800. const localTracks = this.getLocalTracks();
  2801. this.p2pJingleSession.invite(localTracks);
  2802. };
  2803. /**
  2804. * Suspends media transfer over the JVB connection.
  2805. * @private
  2806. */
  2807. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2808. logger.info('Suspending media transfer over the JVB connection...');
  2809. this.jvbJingleSession.setMediaTransferActive(false)
  2810. .then(() => {
  2811. logger.info('Suspended media transfer over the JVB connection !');
  2812. })
  2813. .catch(error => {
  2814. logger.error('Failed to suspend media transfer over the JVB connection:', error);
  2815. });
  2816. };
  2817. /**
  2818. * Method when called will decide whether it's the time to start or stop
  2819. * the P2P session.
  2820. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2821. * originates from the user left event.
  2822. * @private
  2823. */
  2824. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2825. if (!this.isP2PEnabled()
  2826. || this.isP2PTestModeEnabled()
  2827. || (browser.isFirefox() && !this._firefoxP2pEnabled)
  2828. || this.isE2EEEnabled()) {
  2829. logger.info('Auto P2P disabled');
  2830. return;
  2831. }
  2832. const peers = this.getParticipants();
  2833. const peerCount = peers.length;
  2834. // FIXME 1 peer and it must *support* P2P switching
  2835. const shouldBeInP2P = this._shouldBeInP2PMode();
  2836. // Clear deferred "start P2P" task
  2837. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2838. this._maybeClearDeferredStartP2P();
  2839. }
  2840. // Start peer to peer session
  2841. if (!this.p2pJingleSession && shouldBeInP2P) {
  2842. const peer = peerCount && peers[0];
  2843. const myId = this.myUserId();
  2844. const peersId = peer.getId();
  2845. if (myId > peersId) {
  2846. logger.debug(
  2847. 'I\'m the bigger peersId - '
  2848. + 'the other peer should start P2P', myId, peersId);
  2849. return;
  2850. } else if (myId === peersId) {
  2851. logger.error('The same IDs ? ', myId, peersId);
  2852. return;
  2853. }
  2854. const jid = peer.getJid();
  2855. if (userLeftEvent) {
  2856. if (this.deferredStartP2PTask) {
  2857. logger.error('Deferred start P2P task\'s been set already!');
  2858. return;
  2859. }
  2860. logger.info(
  2861. `Will start P2P with: ${jid} after ${
  2862. this.backToP2PDelay} seconds...`);
  2863. this.deferredStartP2PTask = setTimeout(
  2864. this._startP2PSession.bind(this, jid),
  2865. this.backToP2PDelay * 1000);
  2866. } else {
  2867. logger.info(`Will start P2P with: ${jid}`);
  2868. this._startP2PSession(jid);
  2869. }
  2870. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2871. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2872. // Log that there will be a switch back to the JVB connection
  2873. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2874. Statistics.sendAnalyticsAndLog(
  2875. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2876. }
  2877. this._stopP2PSession();
  2878. }
  2879. };
  2880. /**
  2881. * Tells whether or not this conference should be currently in the P2P mode.
  2882. *
  2883. * @private
  2884. * @returns {boolean}
  2885. */
  2886. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2887. const peers = this.getParticipants();
  2888. const peerCount = peers.length;
  2889. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  2890. const shouldBeInP2P = peerCount === 1 && !hasBotPeer && !this._hasVisitors;
  2891. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2892. return shouldBeInP2P;
  2893. };
  2894. /**
  2895. * Stops the current JVB jingle session.
  2896. *
  2897. * @param {Object} options - options for stopping JVB session.
  2898. * @param {string} options.reason - One of the Jingle "reason" element
  2899. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2900. * @param {string} options.reasonDescription - Text description that will be included in the session terminate message.
  2901. * @param {boolean} options.requestRestart - Whether this is due to a session restart, in which case, session will be
  2902. * set to null.
  2903. * @param {boolean} options.sendSessionTerminate - Whether session-terminate needs to be sent to Jicofo.
  2904. */
  2905. JitsiConference.prototype._stopJvbSession = function(options = {}) {
  2906. const {
  2907. requestRestart = false,
  2908. sendSessionTerminate = false
  2909. } = options;
  2910. if (!this.jvbJingleSession) {
  2911. logger.error('No JVB session to be stopped');
  2912. return;
  2913. }
  2914. // Remove remote JVB tracks.
  2915. !this.isP2PActive() && this._removeRemoteJVBTracks();
  2916. logger.info('Stopping stats for jvb connection');
  2917. this.statistics.stopRemoteStats(this.jvbJingleSession.peerconnection);
  2918. this.jvbJingleSession.terminate(
  2919. () => {
  2920. if (requestRestart && sendSessionTerminate) {
  2921. logger.info('session-terminate for ice restart - done');
  2922. }
  2923. this.jvbJingleSession = null;
  2924. },
  2925. error => {
  2926. if (requestRestart && sendSessionTerminate) {
  2927. logger.error('session-terminate for ice restart failed: reloading the client');
  2928. // Initiate a client reload if Jicofo responds to the session-terminate with an error.
  2929. this.eventEmitter.emit(
  2930. JitsiConferenceEvents.CONFERENCE_FAILED,
  2931. JitsiConferenceErrors.ICE_FAILED);
  2932. }
  2933. logger.error(`An error occurred while trying to terminate the JVB session', reason=${error.reason},`
  2934. + `msg=${error.msg}`);
  2935. },
  2936. options);
  2937. };
  2938. /**
  2939. * Stops the current P2P session.
  2940. * @param {Object} options - Options for stopping P2P.
  2941. * @param {string} options.reason - One of the Jingle "reason" element
  2942. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2943. * @param {string} options.reasonDescription - Text description that will be included in the session terminate message.
  2944. * @param {boolean} requestRestart - Whether this is due to a session restart, in which case
  2945. * media will not be resumed on the JVB.
  2946. * @private
  2947. */
  2948. JitsiConference.prototype._stopP2PSession = function(options = {}) {
  2949. const {
  2950. reason = 'success',
  2951. reasonDescription = 'Turning off P2P session',
  2952. requestRestart = false
  2953. } = options;
  2954. if (!this.p2pJingleSession) {
  2955. logger.error('No P2P session to be stopped!');
  2956. return;
  2957. }
  2958. const wasP2PEstablished = this.isP2PActive();
  2959. // Swap remote tracks, but only if the P2P has been fully established
  2960. if (wasP2PEstablished) {
  2961. if (this.jvbJingleSession && !requestRestart) {
  2962. this._resumeMediaTransferForJvbConnection();
  2963. }
  2964. // Remove remote P2P tracks
  2965. this._removeRemoteP2PTracks();
  2966. }
  2967. // Stop P2P stats
  2968. logger.info('Stopping remote stats for P2P connection');
  2969. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2970. this.p2pJingleSession.terminate(
  2971. () => {
  2972. logger.info('P2P session terminate RESULT');
  2973. this.p2pJingleSession = null;
  2974. },
  2975. error => {
  2976. // Because both initiator and responder are simultaneously
  2977. // terminating their JingleSessions in case of the 'to JVB switch'
  2978. // when 3rd participant joins, both will dispose their sessions and
  2979. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2980. // want to log this as an error since it's expected behaviour.
  2981. //
  2982. // We want them both to terminate, because in case of initiator's
  2983. // crash the responder would stay in P2P mode until ICE fails which
  2984. // could take up to 20 seconds.
  2985. //
  2986. // NOTE: whilst this is an error callback, 'success' as a reason is
  2987. // considered as graceful session terminate
  2988. // where both initiator and responder terminate their sessions
  2989. // simultaneously.
  2990. if (reason !== 'success') {
  2991. logger.error('An error occurred while trying to terminate P2P Jingle session', error);
  2992. }
  2993. }, {
  2994. reason,
  2995. reasonDescription,
  2996. sendSessionTerminate: this.room
  2997. && this.getParticipantById(
  2998. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2999. });
  3000. this.p2pJingleSession = null;
  3001. // Update P2P status and other affected events/states
  3002. this._setP2PStatus(false);
  3003. if (wasP2PEstablished) {
  3004. // Add back remote JVB tracks
  3005. if (this.jvbJingleSession && !requestRestart) {
  3006. this._addRemoteJVBTracks();
  3007. } else {
  3008. logger.info('Not adding remote JVB tracks - no session yet');
  3009. }
  3010. }
  3011. };
  3012. /**
  3013. * Updates room presence if needed and send the packet in case of a modification.
  3014. * @param {JingleSessionPC} jingleSession the session firing the event, contains the peer connection which
  3015. * tracks we will check.
  3016. * @param {Object|null} ctx a context object we can distinguish multiple calls of the same pass of updating tracks.
  3017. */
  3018. JitsiConference.prototype._updateRoomPresence = function(jingleSession, ctx) {
  3019. if (!jingleSession) {
  3020. return;
  3021. }
  3022. // skips sending presence twice for the same pass of updating ssrcs
  3023. if (ctx) {
  3024. if (ctx.skip) {
  3025. return;
  3026. }
  3027. ctx.skip = true;
  3028. }
  3029. let presenceChanged = false;
  3030. let muteStatusChanged, videoTypeChanged;
  3031. const localTracks = jingleSession.peerconnection.getLocalTracks();
  3032. // Set presence for all the available local tracks.
  3033. for (const track of localTracks) {
  3034. const muted = track.isMuted();
  3035. muteStatusChanged = this._setTrackMuteStatus(track.getType(), track, muted);
  3036. muteStatusChanged && logger.debug(`Updating mute state of ${track} in presence to muted=${muted}`);
  3037. if (track.getType() === MediaType.VIDEO) {
  3038. videoTypeChanged = this._setNewVideoType(track);
  3039. videoTypeChanged && logger.debug(`Updating videoType in presence to ${track.getVideoType()}`);
  3040. }
  3041. presenceChanged = presenceChanged || muteStatusChanged || videoTypeChanged;
  3042. }
  3043. presenceChanged && this.room.sendPresence();
  3044. };
  3045. /**
  3046. * Checks whether or not the conference is currently in the peer to peer mode.
  3047. * Being in peer to peer mode means that the direct connection has been
  3048. * established and the P2P connection is being used for media transmission.
  3049. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  3050. */
  3051. JitsiConference.prototype.isP2PActive = function() {
  3052. return this.p2p;
  3053. };
  3054. /**
  3055. * Returns the current ICE state of the P2P connection.
  3056. * NOTE: method is used by the jitsi-meet-torture tests.
  3057. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  3058. * no P2P connection.
  3059. */
  3060. JitsiConference.prototype.getP2PConnectionState = function() {
  3061. if (this.isP2PActive()) {
  3062. return this.p2pJingleSession.peerconnection.getConnectionState();
  3063. }
  3064. return null;
  3065. };
  3066. /**
  3067. * Configures the peerconnection so that a given framre rate can be achieved for desktop share.
  3068. *
  3069. * @param {number} maxFps The capture framerate to be used for desktop tracks.
  3070. * @returns {boolean} true if the operation is successful, false otherwise.
  3071. */
  3072. JitsiConference.prototype.setDesktopSharingFrameRate = function(maxFps) {
  3073. if (typeof maxFps !== 'number' || isNaN(maxFps)) {
  3074. logger.error(`Invalid value ${maxFps} specified for desktop capture frame rate`);
  3075. return false;
  3076. }
  3077. this._desktopSharingFrameRate = maxFps;
  3078. // Set capture fps for screenshare.
  3079. this.jvbJingleSession && this.jvbJingleSession.peerconnection.setDesktopSharingFrameRate(maxFps);
  3080. // Set the capture rate for desktop sharing.
  3081. this.rtc.setDesktopSharingFrameRate(maxFps);
  3082. return true;
  3083. };
  3084. /**
  3085. * Manually starts new P2P session (should be used only in the tests).
  3086. */
  3087. JitsiConference.prototype.startP2PSession = function() {
  3088. const peers = this.getParticipants();
  3089. // Start peer to peer session
  3090. if (peers.length === 1) {
  3091. const peerJid = peers[0].getJid();
  3092. this._startP2PSession(peerJid);
  3093. } else {
  3094. throw new Error(
  3095. 'There must be exactly 1 participant to start the P2P session !');
  3096. }
  3097. };
  3098. /**
  3099. * Manually stops the current P2P session (should be used only in the tests).
  3100. */
  3101. JitsiConference.prototype.stopP2PSession = function(options) {
  3102. this._stopP2PSession(options);
  3103. };
  3104. /**
  3105. * Get a summary of how long current participants have been the dominant speaker
  3106. * @returns {object}
  3107. */
  3108. JitsiConference.prototype.getSpeakerStats = function() {
  3109. return this.speakerStatsCollector.getStats();
  3110. };
  3111. /**
  3112. * Sends a face landmarks object to the xmpp server.
  3113. * @param {Object} payload
  3114. */
  3115. JitsiConference.prototype.sendFaceLandmarks = function(payload) {
  3116. if (payload.faceExpression) {
  3117. this.xmpp.sendFaceLandmarksEvent(this.room.roomjid, payload);
  3118. }
  3119. };
  3120. /**
  3121. * Sets the constraints for the video that is requested from the bridge.
  3122. *
  3123. * @param {Object} videoConstraints The constraints which are specified in the following format. The message updates
  3124. * the fields that are present and leaves the rest unchanged on the bridge. Therefore, any field that is not applicable
  3125. * anymore should be cleared by passing an empty object or list (whatever is applicable).
  3126. * {
  3127. * 'lastN': 20,
  3128. * 'selectedSources': ['A', 'B', 'C'],
  3129. * 'onStageSources': ['A'],
  3130. * 'defaultConstraints': { 'maxHeight': 180 },
  3131. * 'constraints': {
  3132. * 'A': { 'maxHeight': 720 }
  3133. * }
  3134. * }
  3135. * Where A, B and C are source-names of the remote tracks that are being requested from the bridge.
  3136. */
  3137. JitsiConference.prototype.setReceiverConstraints = function(videoConstraints) {
  3138. this.receiveVideoController.setReceiverConstraints(videoConstraints);
  3139. };
  3140. /**
  3141. * Sets the assumed bandwidth bps for the video that is requested from the bridge.
  3142. *
  3143. * @param {Number} assumedBandwidthBps - The bandwidth value expressed in bits per second.
  3144. */
  3145. JitsiConference.prototype.setAssumedBandwidthBps = function(assumedBandwidthBps) {
  3146. this.receiveVideoController.setAssumedBandwidthBps(assumedBandwidthBps);
  3147. };
  3148. /**
  3149. * Sets the maximum video size the local participant should receive from remote
  3150. * participants.
  3151. *
  3152. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  3153. * this receiver is willing to receive.
  3154. * @returns {void}
  3155. */
  3156. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  3157. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  3158. };
  3159. /**
  3160. * Sets the maximum video size the local participant should send to remote
  3161. * participants.
  3162. * @param {number} maxFrameHeight - The user preferred max frame height.
  3163. * @returns {Promise} promise that will be resolved when the operation is
  3164. * successful and rejected otherwise.
  3165. */
  3166. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  3167. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  3168. };
  3169. /**
  3170. * Creates a video SIP GW session and returns it if service is enabled. Before
  3171. * creating a session one need to check whether video SIP GW service is
  3172. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  3173. * if there are available nodes to serve this request, after creating the
  3174. * session those nodes can be taken and the request about using the
  3175. * created session can fail.
  3176. *
  3177. * @param {string} sipAddress - The sip address to be used.
  3178. * @param {string} displayName - The display name to be used for this session.
  3179. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  3180. * initialised and there is no room.
  3181. */
  3182. JitsiConference.prototype.createVideoSIPGWSession = function(sipAddress, displayName) {
  3183. if (!this.room) {
  3184. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  3185. }
  3186. return this.videoSIPGWHandler
  3187. .createVideoSIPGWSession(sipAddress, displayName);
  3188. };
  3189. /**
  3190. * Sends a conference.join analytics event.
  3191. *
  3192. * @returns {void}
  3193. */
  3194. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  3195. const meetingId = this.getMeetingUniqueId();
  3196. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  3197. return;
  3198. }
  3199. const conferenceConnectionTimes = this.getConnectionTimes();
  3200. const xmppConnectionTimes = this.connection.getConnectionTimes();
  3201. const gumStart = window.connectionTimes['firstObtainPermissions.start'];
  3202. const gumEnd = window.connectionTimes['firstObtainPermissions.end'];
  3203. const globalNSConnectionTimes = window.JitsiMeetJS?.app?.connectionTimes ?? {};
  3204. const connectionTimes = {
  3205. ...conferenceConnectionTimes,
  3206. ...xmppConnectionTimes,
  3207. ...globalNSConnectionTimes,
  3208. gumDuration: safeSubtract(gumEnd, gumStart),
  3209. xmppConnectingTime: safeSubtract(xmppConnectionTimes.connected, xmppConnectionTimes.connecting),
  3210. connectedToMUCJoinedTime: safeSubtract(
  3211. conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connected),
  3212. connectingToMUCJoinedTime: safeSubtract(
  3213. conferenceConnectionTimes['muc.joined'], xmppConnectionTimes.connecting),
  3214. numberOfParticipantsOnJoin: this._numberOfParticipantsOnJoin
  3215. };
  3216. Statistics.sendAnalytics(createConferenceEvent('joined', {
  3217. ...connectionTimes,
  3218. meetingId,
  3219. participantId: `${meetingId}.${this._statsCurrentId}`
  3220. }));
  3221. this._conferenceJoinAnalyticsEventSent = Date.now();
  3222. };
  3223. /**
  3224. * Sends conference.left analytics event.
  3225. * @private
  3226. */
  3227. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  3228. const meetingId = this.getMeetingUniqueId();
  3229. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  3230. return;
  3231. }
  3232. Statistics.sendAnalytics(createConferenceEvent('left', {
  3233. meetingId,
  3234. participantId: `${meetingId}.${this._statsCurrentId}`,
  3235. stats: {
  3236. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  3237. perf: this.getPerformanceStats()
  3238. }
  3239. }));
  3240. };
  3241. /**
  3242. * Restarts all active media sessions.
  3243. *
  3244. * @returns {void}
  3245. */
  3246. JitsiConference.prototype._restartMediaSessions = function() {
  3247. if (this.p2pJingleSession) {
  3248. this._stopP2PSession({
  3249. reasonDescription: 'restart',
  3250. requestRestart: true
  3251. });
  3252. }
  3253. if (this.jvbJingleSession) {
  3254. this._stopJvbSession({
  3255. reason: 'success',
  3256. reasonDescription: 'restart required',
  3257. requestRestart: true,
  3258. sendSessionTerminate: true
  3259. });
  3260. }
  3261. this._maybeStartOrStopP2P(false);
  3262. };
  3263. /**
  3264. * Returns whether End-To-End encryption is enabled.
  3265. *
  3266. * @returns {boolean}
  3267. */
  3268. JitsiConference.prototype.isE2EEEnabled = function() {
  3269. return Boolean(this._e2eEncryption && this._e2eEncryption.isEnabled());
  3270. };
  3271. /**
  3272. * Returns whether End-To-End encryption is supported. Note that not all participants
  3273. * in the conference may support it.
  3274. *
  3275. * @returns {boolean}
  3276. */
  3277. JitsiConference.prototype.isE2EESupported = function() {
  3278. return E2EEncryption.isSupported(this.options.config);
  3279. };
  3280. /**
  3281. * Enables / disables End-to-End encryption.
  3282. *
  3283. * @param {boolean} enabled whether to enable E2EE or not.
  3284. * @returns {void}
  3285. */
  3286. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3287. if (!this.isE2EESupported()) {
  3288. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3289. return;
  3290. }
  3291. this._e2eEncryption.setEnabled(enabled);
  3292. };
  3293. /**
  3294. * Sets the key and index for End-to-End encryption.
  3295. *
  3296. * @param {CryptoKey} [keyInfo.encryptionKey] - encryption key.
  3297. * @param {Number} [keyInfo.index] - the index of the encryption key.
  3298. * @returns {void}
  3299. */
  3300. JitsiConference.prototype.setMediaEncryptionKey = function(keyInfo) {
  3301. this._e2eEncryption.setEncryptionKey(keyInfo);
  3302. };
  3303. /**
  3304. * Starts the participant verification process.
  3305. *
  3306. * @param {string} participantId The participant which will be marked as verified.
  3307. * @returns {void}
  3308. */
  3309. JitsiConference.prototype.startVerification = function(participantId) {
  3310. const participant = this.getParticipantById(participantId);
  3311. if (!participant) {
  3312. return;
  3313. }
  3314. this._e2eEncryption.startVerification(participant);
  3315. };
  3316. /**
  3317. * Marks the given participant as verified. After this is done, MAC verification will
  3318. * be performed and an event will be emitted with the result.
  3319. *
  3320. * @param {string} participantId The participant which will be marked as verified.
  3321. * @param {boolean} isVerified - whether the verification was succesfull.
  3322. * @returns {void}
  3323. */
  3324. JitsiConference.prototype.markParticipantVerified = function(participantId, isVerified) {
  3325. const participant = this.getParticipantById(participantId);
  3326. if (!participant) {
  3327. return;
  3328. }
  3329. this._e2eEncryption.markParticipantVerified(participant, isVerified);
  3330. };
  3331. /**
  3332. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3333. *
  3334. * @returns {boolean} whether lobby is supported in the backend.
  3335. */
  3336. JitsiConference.prototype.isLobbySupported = function() {
  3337. return Boolean(this.room && this.room.getLobby().isSupported());
  3338. };
  3339. /**
  3340. * Returns <tt>true</tt> if the room has members only enabled.
  3341. *
  3342. * @returns {boolean} whether conference room is members only.
  3343. */
  3344. JitsiConference.prototype.isMembersOnly = function() {
  3345. return Boolean(this.room && this.room.membersOnlyEnabled);
  3346. };
  3347. /**
  3348. * Returns <tt>true</tt> if the room supports visitors feature.
  3349. *
  3350. * @returns {boolean} whether conference room has visitors support.
  3351. */
  3352. JitsiConference.prototype.isVisitorsSupported = function() {
  3353. return Boolean(this.room && this.room.visitorsSupported);
  3354. };
  3355. /**
  3356. * Enables lobby by moderators
  3357. *
  3358. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3359. */
  3360. JitsiConference.prototype.enableLobby = function() {
  3361. if (this.room && this.isModerator()) {
  3362. return this.room.getLobby().enable();
  3363. }
  3364. return Promise.reject(
  3365. new Error('The conference not started or user is not moderator'));
  3366. };
  3367. /**
  3368. * Disabled lobby by moderators
  3369. *
  3370. * @returns {void}
  3371. */
  3372. JitsiConference.prototype.disableLobby = function() {
  3373. if (this.room && this.isModerator()) {
  3374. this.room.getLobby().disable();
  3375. } else {
  3376. logger.warn(`Failed to disable lobby, ${this.room ? '' : 'not in a room, '}${
  3377. this.isModerator() ? '' : 'participant is not a moderator'}`);
  3378. }
  3379. };
  3380. /**
  3381. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3382. *
  3383. * @param {string} displayName Display name should be set to show it to moderators.
  3384. * @param {string} email Optional email is used to present avatar to the moderator.
  3385. * @returns {Promise<never>}
  3386. */
  3387. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3388. if (this.room) {
  3389. return this.room.getLobby().join(displayName, email);
  3390. }
  3391. return Promise.reject(new Error('The conference not started'));
  3392. };
  3393. /**
  3394. * Gets the local id for a participant in a lobby room.
  3395. * Returns undefined when current participant is not in the lobby room.
  3396. * This is used for lobby room private chat messages.
  3397. *
  3398. * @returns {string}
  3399. */
  3400. JitsiConference.prototype.myLobbyUserId = function() {
  3401. if (this.room) {
  3402. return this.room.getLobby().getLocalId();
  3403. }
  3404. };
  3405. /**
  3406. * Sends a message to a lobby room.
  3407. * When id is specified it sends a private message.
  3408. * Otherwise it sends the message to all moderators.
  3409. * @param {message} Object The message to send
  3410. * @param {string} id The participant id.
  3411. *
  3412. * @returns {void}
  3413. */
  3414. JitsiConference.prototype.sendLobbyMessage = function(message, id) {
  3415. if (this.room) {
  3416. if (id) {
  3417. return this.room.getLobby().sendPrivateMessage(id, message);
  3418. }
  3419. return this.room.getLobby().sendMessage(message);
  3420. }
  3421. };
  3422. /**
  3423. * Adds a message listener to the lobby room
  3424. * @param {Function} listener The listener function,
  3425. * called when a new message is received in the lobby room.
  3426. *
  3427. * @returns {Function} Handler returned to be able to remove it later.
  3428. */
  3429. JitsiConference.prototype.addLobbyMessageListener = function(listener) {
  3430. if (this.room) {
  3431. return this.room.getLobby().addMessageListener(listener);
  3432. }
  3433. };
  3434. /**
  3435. * Removes a message handler from the lobby room
  3436. * @param {Function} handler The handler function to remove.
  3437. *
  3438. * @returns {void}
  3439. */
  3440. JitsiConference.prototype.removeLobbyMessageHandler = function(handler) {
  3441. if (this.room) {
  3442. return this.room.getLobby().removeMessageHandler(handler);
  3443. }
  3444. };
  3445. /**
  3446. * Denies an occupant in the lobby room access to the conference.
  3447. * @param {string} id The participant id.
  3448. */
  3449. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3450. if (this.room) {
  3451. this.room.getLobby().denyAccess(id);
  3452. }
  3453. };
  3454. /**
  3455. * Approves the request to join the conference to a participant waiting in the lobby.
  3456. *
  3457. * @param {string|Array<string>} param The participant id or an array of ids.
  3458. */
  3459. JitsiConference.prototype.lobbyApproveAccess = function(param) {
  3460. if (this.room) {
  3461. this.room.getLobby().approveAccess(param);
  3462. }
  3463. };
  3464. /**
  3465. * Returns <tt>true</tt> if AV Moderation support is enabled in the backend.
  3466. *
  3467. * @returns {boolean} whether AV Moderation is supported in the backend.
  3468. */
  3469. JitsiConference.prototype.isAVModerationSupported = function() {
  3470. return Boolean(this.room && this.room.getAVModeration().isSupported());
  3471. };
  3472. /**
  3473. * Enables AV Moderation.
  3474. * @param {MediaType} mediaType "audio" or "video"
  3475. */
  3476. JitsiConference.prototype.enableAVModeration = function(mediaType) {
  3477. if (this.room && this.isModerator()
  3478. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3479. this.room.getAVModeration().enable(true, mediaType);
  3480. } else {
  3481. logger.warn(`Failed to enable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3482. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3483. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3484. }
  3485. };
  3486. /**
  3487. * Disables AV Moderation.
  3488. * @param {MediaType} mediaType "audio" or "video"
  3489. */
  3490. JitsiConference.prototype.disableAVModeration = function(mediaType) {
  3491. if (this.room && this.isModerator()
  3492. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3493. this.room.getAVModeration().enable(false, mediaType);
  3494. } else {
  3495. logger.warn(`Failed to disable AV moderation, ${this.room ? '' : 'not in a room, '}${
  3496. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3497. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3498. }
  3499. };
  3500. /**
  3501. * Approve participant access to certain media, allows unmuting audio or video.
  3502. *
  3503. * @param {MediaType} mediaType "audio" or "video"
  3504. * @param id the id of the participant.
  3505. */
  3506. JitsiConference.prototype.avModerationApprove = function(mediaType, id) {
  3507. if (this.room && this.isModerator()
  3508. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3509. const participant = this.getParticipantById(id);
  3510. if (!participant) {
  3511. return;
  3512. }
  3513. this.room.getAVModeration().approve(mediaType, participant.getJid());
  3514. } else {
  3515. logger.warn(`AV moderation approve skipped , ${this.room ? '' : 'not in a room, '}${
  3516. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3517. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3518. }
  3519. };
  3520. /**
  3521. * Reject participant access to certain media, blocks unmuting audio or video.
  3522. *
  3523. * @param {MediaType} mediaType "audio" or "video"
  3524. * @param id the id of the participant.
  3525. */
  3526. JitsiConference.prototype.avModerationReject = function(mediaType, id) {
  3527. if (this.room && this.isModerator()
  3528. && (mediaType === MediaType.AUDIO || mediaType === MediaType.VIDEO)) {
  3529. const participant = this.getParticipantById(id);
  3530. if (!participant) {
  3531. return;
  3532. }
  3533. this.room.getAVModeration().reject(mediaType, participant.getJid());
  3534. } else {
  3535. logger.warn(`AV moderation reject skipped , ${this.room ? '' : 'not in a room, '}${
  3536. this.isModerator() ? '' : 'participant is not a moderator, '}${
  3537. this.room && this.isModerator() ? 'wrong media type passed' : ''}`);
  3538. }
  3539. };
  3540. /**
  3541. * Returns the breakout rooms manager object.
  3542. *
  3543. * @returns {Object} the breakout rooms manager.
  3544. */
  3545. JitsiConference.prototype.getBreakoutRooms = function() {
  3546. return this.room?.getBreakoutRooms();
  3547. };
  3548. /**
  3549. * Returns the metadata handler object.
  3550. *
  3551. * @returns {Object} the room metadata handler.
  3552. */
  3553. JitsiConference.prototype.getMetadataHandler = function() {
  3554. return this.room?.getMetadataHandler();
  3555. };