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

JitsiConference.js 138KB

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