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

JitsiConference.js 112KB

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