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

JitsiConference.js 126KB

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