Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 126KB

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