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

JitsiConference.js 112KB

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