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

JitsiConference.js 137KB

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