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

JitsiConference.js 137KB

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