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

JitsiConference.js 121KB

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