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

JitsiConference.js 126KB

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