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

JitsiConference.js 139KB

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