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

JitsiConference.js 112KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536
  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. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1328. if (this.isJoined()) {
  1329. this._maybeStartOrStopP2P();
  1330. }
  1331. this._maybeSetSITimeout();
  1332. };
  1333. /* eslint-enable max-params */
  1334. /**
  1335. * Get notified when we joined the room.
  1336. *
  1337. * FIXME This should NOT be exposed!
  1338. *
  1339. * @private
  1340. */
  1341. JitsiConference.prototype._onMucJoined = function() {
  1342. this._maybeStartOrStopP2P();
  1343. };
  1344. /**
  1345. * Updates features for a participant.
  1346. * @param {JitsiParticipant} participant - The participant to query for features.
  1347. * @returns {void}
  1348. * @private
  1349. */
  1350. JitsiConference.prototype._updateFeatures = function(participant) {
  1351. participant.getFeatures()
  1352. .then(features => {
  1353. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1354. this.updateDTMFSupport();
  1355. if (features.has('http://jitsi.org/protocol/jigasi')) {
  1356. participant.setProperty('features_jigasi', true);
  1357. }
  1358. if (features.has('https://jitsi.org/meet/e2ee')) {
  1359. participant.setProperty('features_e2ee', true);
  1360. }
  1361. })
  1362. .catch(() => false);
  1363. };
  1364. /**
  1365. * Get notified when member bot type had changed.
  1366. * @param jid the member jid
  1367. * @param botType the new botType value
  1368. * @private
  1369. */
  1370. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1371. // find the participant and mark it as non bot, as the real one will join
  1372. // in a moment
  1373. const peers = this.getParticipants();
  1374. const botParticipant = peers.find(p => p.getJid() === jid);
  1375. if (botParticipant) {
  1376. botParticipant._botType = botType;
  1377. const id = Strophe.getResourceFromJid(jid);
  1378. this.eventEmitter.emit(
  1379. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1380. id,
  1381. botType);
  1382. }
  1383. // if botType changed to undefined, botType was removed, in case of
  1384. // poltergeist mode this is the moment when the poltergeist had exited and
  1385. // the real participant had already replaced it.
  1386. // In this case we can check and try p2p
  1387. if (!botParticipant._botType) {
  1388. this._maybeStartOrStopP2P();
  1389. }
  1390. };
  1391. JitsiConference.prototype.onMemberLeft = function(jid) {
  1392. const id = Strophe.getResourceFromJid(jid);
  1393. if (id === 'focus' || this.myUserId() === id) {
  1394. return;
  1395. }
  1396. const participant = this.participants[id];
  1397. delete this.participants[id];
  1398. const removedTracks = this.rtc.removeRemoteTracks(id);
  1399. removedTracks.forEach(
  1400. track =>
  1401. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  1402. // there can be no participant in case the member that left is focus
  1403. if (participant) {
  1404. this.eventEmitter.emit(
  1405. JitsiConferenceEvents.USER_LEFT, id, participant);
  1406. }
  1407. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1408. this._maybeClearSITimeout();
  1409. };
  1410. /**
  1411. * Designates an event indicating that we were kicked from the XMPP MUC.
  1412. * @param {boolean} isSelfPresence - whether it is for local participant
  1413. * or another participant.
  1414. * @param {string} actorId - the id of the participant who was initiator
  1415. * of the kick.
  1416. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1417. * this is the id of the participant which was kicked.
  1418. */
  1419. JitsiConference.prototype.onMemberKicked = function(isSelfPresence, actorId, kickedParticipantId) {
  1420. // This check which be true when we kick someone else. With the introduction of lobby
  1421. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1422. // avoid emitting an event where `undefined` kicked someone.
  1423. if (actorId === this.myUserId()) {
  1424. return;
  1425. }
  1426. const actorParticipant = this.participants[actorId];
  1427. if (isSelfPresence) {
  1428. this.eventEmitter.emit(
  1429. JitsiConferenceEvents.KICKED, actorParticipant);
  1430. this.leave();
  1431. return;
  1432. }
  1433. const kickedParticipant = this.participants[kickedParticipantId];
  1434. this.eventEmitter.emit(
  1435. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant);
  1436. };
  1437. /**
  1438. * Method called on local MUC role change.
  1439. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1440. */
  1441. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1442. // Emit role changed for local JID
  1443. this.eventEmitter.emit(
  1444. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1445. };
  1446. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1447. const id = Strophe.getResourceFromJid(jid);
  1448. const participant = this.getParticipantById(id);
  1449. if (!participant) {
  1450. return;
  1451. }
  1452. participant._role = role;
  1453. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1454. };
  1455. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1456. const id = Strophe.getResourceFromJid(jid);
  1457. const participant = this.getParticipantById(id);
  1458. if (!participant) {
  1459. return;
  1460. }
  1461. if (participant._displayName === displayName) {
  1462. return;
  1463. }
  1464. participant._displayName = displayName;
  1465. this.eventEmitter.emit(
  1466. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1467. id,
  1468. displayName);
  1469. };
  1470. /**
  1471. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  1472. * the conference.
  1473. *
  1474. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  1475. * JitsiConference
  1476. */
  1477. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1478. if (track.isP2P && !this.isP2PActive()) {
  1479. logger.info(
  1480. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1481. return;
  1482. } else if (!track.isP2P && this.isP2PActive()) {
  1483. logger.info(
  1484. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1485. return;
  1486. }
  1487. const id = track.getParticipantId();
  1488. const participant = this.getParticipantById(id);
  1489. if (!participant) {
  1490. logger.error(`No participant found for id: ${id}`);
  1491. return;
  1492. }
  1493. // Add track to JitsiParticipant.
  1494. participant._tracks.push(track);
  1495. if (this.transcriber) {
  1496. this.transcriber.addTrack(track);
  1497. }
  1498. const emitter = this.eventEmitter;
  1499. track.addEventListener(
  1500. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1501. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1502. track.addEventListener(
  1503. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1504. (audioLevel, tpc) => {
  1505. const activeTPC = this.getActivePeerConnection();
  1506. if (activeTPC === tpc) {
  1507. emitter.emit(
  1508. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1509. id,
  1510. audioLevel);
  1511. }
  1512. }
  1513. );
  1514. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1515. };
  1516. /**
  1517. * Callback called by the Jingle plugin when 'session-answer' is received.
  1518. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1519. * received.
  1520. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1521. */
  1522. // eslint-disable-next-line no-unused-vars
  1523. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1524. if (this.p2pJingleSession === session) {
  1525. logger.info('P2P setAnswer');
  1526. this.p2pJingleSession.setAnswer(answer);
  1527. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1528. }
  1529. };
  1530. /**
  1531. * Callback called by the Jingle plugin when 'transport-info' is received.
  1532. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1533. * received
  1534. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1535. * element
  1536. */
  1537. // eslint-disable-next-line no-unused-vars
  1538. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1539. if (this.p2pJingleSession === session) {
  1540. logger.info('P2P addIceCandidates');
  1541. this.p2pJingleSession.addIceCandidates(transportInfo);
  1542. }
  1543. };
  1544. /**
  1545. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1546. * the conference.
  1547. *
  1548. * @param {JitsiRemoteTrack} removedTrack
  1549. */
  1550. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1551. this.getParticipants().forEach(participant => {
  1552. const tracks = participant.getTracks();
  1553. for (let i = 0; i < tracks.length; i++) {
  1554. if (tracks[i] === removedTrack) {
  1555. // Since the tracks have been compared and are
  1556. // considered equal the result of splice can be ignored.
  1557. participant._tracks.splice(i, 1);
  1558. this.eventEmitter.emit(
  1559. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1560. if (this.transcriber) {
  1561. this.transcriber.removeTrack(removedTrack);
  1562. }
  1563. break;
  1564. }
  1565. }
  1566. }, this);
  1567. };
  1568. /**
  1569. * Handles an incoming call event for the P2P jingle session.
  1570. */
  1571. JitsiConference.prototype._onIncomingCallP2P = function(
  1572. jingleSession,
  1573. jingleOffer) {
  1574. let rejectReason;
  1575. if (!browser.supportsP2P()) {
  1576. rejectReason = {
  1577. reason: 'unsupported-applications',
  1578. reasonDescription: 'P2P not supported',
  1579. errorMsg: 'This client does not support P2P connections'
  1580. };
  1581. } else if (!this.isP2PEnabled() && !this.isP2PTestModeEnabled()) {
  1582. rejectReason = {
  1583. reason: 'decline',
  1584. reasonDescription: 'P2P disabled',
  1585. errorMsg: 'P2P mode disabled in the configuration'
  1586. };
  1587. } else if (this.p2pJingleSession) {
  1588. // Reject incoming P2P call (already in progress)
  1589. rejectReason = {
  1590. reason: 'busy',
  1591. reasonDescription: 'P2P already in progress',
  1592. errorMsg: 'Duplicated P2P "session-initiate"'
  1593. };
  1594. } else if (!this._shouldBeInP2PMode()) {
  1595. rejectReason = {
  1596. reason: 'decline',
  1597. reasonDescription: 'P2P requirements not met',
  1598. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1599. };
  1600. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1601. }
  1602. if (rejectReason) {
  1603. this._rejectIncomingCall(jingleSession, rejectReason);
  1604. } else {
  1605. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1606. }
  1607. };
  1608. /**
  1609. * Handles an incoming call event.
  1610. */
  1611. JitsiConference.prototype.onIncomingCall = function(
  1612. jingleSession,
  1613. jingleOffer,
  1614. now) {
  1615. // Handle incoming P2P call
  1616. if (jingleSession.isP2P) {
  1617. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1618. } else {
  1619. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1620. const description = 'Rejecting session-initiate from non-focus.';
  1621. this._rejectIncomingCall(
  1622. jingleSession, {
  1623. reason: 'security-error',
  1624. reasonDescription: description,
  1625. errorMsg: description
  1626. });
  1627. return;
  1628. }
  1629. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1630. }
  1631. };
  1632. /**
  1633. * Accepts an incoming call event for the JVB jingle session.
  1634. */
  1635. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1636. jingleSession,
  1637. jingleOffer,
  1638. now) {
  1639. // Accept incoming call
  1640. this.jvbJingleSession = jingleSession;
  1641. this.room.connectionTimes['session.initiate'] = now;
  1642. this._sendConferenceJoinAnalyticsEvent();
  1643. if (this.wasStopped) {
  1644. Statistics.sendAnalyticsAndLog(
  1645. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1646. }
  1647. const serverRegion
  1648. = $(jingleOffer)
  1649. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1650. .attr('region');
  1651. this.eventEmitter.emit(
  1652. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1653. serverRegion);
  1654. this._maybeClearSITimeout();
  1655. Statistics.sendAnalytics(createJingleEvent(
  1656. ACTION_JINGLE_SI_RECEIVED,
  1657. {
  1658. p2p: false,
  1659. value: now
  1660. }));
  1661. try {
  1662. jingleSession.initialize(this.room, this.rtc, {
  1663. ...this.options.config,
  1664. enableInsertableStreams: this._isE2EEEnabled()
  1665. });
  1666. } catch (error) {
  1667. GlobalOnErrorHandler.callErrorHandler(error);
  1668. logger.error(error);
  1669. return;
  1670. }
  1671. // Open a channel with the videobridge.
  1672. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1673. // Add local tracks to the session
  1674. const localTracks = this.getLocalTracks();
  1675. try {
  1676. jingleSession.acceptOffer(
  1677. jingleOffer,
  1678. () => {
  1679. // If for any reason invite for the JVB session arrived after
  1680. // the P2P has been established already the media transfer needs
  1681. // to be turned off here.
  1682. if (this.isP2PActive() && this.jvbJingleSession) {
  1683. this._suspendMediaTransferForJvbConnection();
  1684. }
  1685. this.eventEmitter.emit(
  1686. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  1687. jingleSession);
  1688. if (!this.isP2PActive()) {
  1689. this.eventEmitter.emit(
  1690. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  1691. jingleSession);
  1692. }
  1693. },
  1694. error => {
  1695. GlobalOnErrorHandler.callErrorHandler(error);
  1696. logger.error(
  1697. 'Failed to accept incoming Jingle session', error);
  1698. },
  1699. localTracks
  1700. );
  1701. // Start callstats as soon as peerconnection is initialized,
  1702. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1703. // happen in case if user doesn't have or denied permission to
  1704. // both camera and microphone.
  1705. logger.info('Starting CallStats for JVB connection...');
  1706. this.statistics.startCallStats(
  1707. this.jvbJingleSession.peerconnection,
  1708. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1709. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1710. } catch (e) {
  1711. GlobalOnErrorHandler.callErrorHandler(e);
  1712. logger.error(e);
  1713. }
  1714. };
  1715. /**
  1716. * Sets the BridgeChannel.
  1717. *
  1718. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1719. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1720. * BridgeChannel mode.
  1721. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1722. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1723. */
  1724. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1725. let wsUrl = null;
  1726. const webSocket
  1727. = $(offerIq)
  1728. .find('>content>transport>web-socket')
  1729. .first();
  1730. if (webSocket.length === 1) {
  1731. wsUrl = webSocket[0].getAttribute('url');
  1732. }
  1733. if (wsUrl) {
  1734. // If the offer contains a websocket use it.
  1735. this.rtc.initializeBridgeChannel(null, wsUrl);
  1736. } else {
  1737. // Otherwise, fall back to an attempt to use SCTP.
  1738. this.rtc.initializeBridgeChannel(pc, null);
  1739. }
  1740. };
  1741. /**
  1742. * Rejects incoming Jingle call.
  1743. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1744. * @param {object} [options]
  1745. * @param {string} options.reason the name of the reason element as defined
  1746. * by Jingle
  1747. * @param {string} options.reasonDescription the reason description which will
  1748. * be included in Jingle 'session-terminate' message.
  1749. * @param {string} options.errorMsg an error message to be logged on global
  1750. * error handler
  1751. * @private
  1752. */
  1753. JitsiConference.prototype._rejectIncomingCall = function(
  1754. jingleSession,
  1755. options) {
  1756. if (options && options.errorMsg) {
  1757. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1758. }
  1759. // Terminate the jingle session with a reason
  1760. jingleSession.terminate(
  1761. null /* success callback => we don't care */,
  1762. error => {
  1763. logger.warn(
  1764. 'An error occurred while trying to terminate'
  1765. + ' invalid Jingle session', error);
  1766. }, {
  1767. reason: options && options.reason,
  1768. reasonDescription: options && options.reasonDescription,
  1769. sendSessionTerminate: true
  1770. });
  1771. };
  1772. /**
  1773. * Handles the call ended event.
  1774. * XXX is this due to the remote side terminating the Jingle session?
  1775. *
  1776. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1777. * terminated.
  1778. * @param {String} reasonCondition the Jingle reason condition.
  1779. * @param {String|null} reasonText human readable reason text which may provide
  1780. * more details about why the call has been terminated.
  1781. */
  1782. JitsiConference.prototype.onCallEnded = function(
  1783. jingleSession,
  1784. reasonCondition,
  1785. reasonText) {
  1786. logger.info(
  1787. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1788. jingleSession.isP2P}`);
  1789. if (jingleSession === this.jvbJingleSession) {
  1790. this.wasStopped = true;
  1791. Statistics.sendAnalytics(
  1792. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1793. // Stop the stats
  1794. if (this.statistics) {
  1795. this.statistics.stopRemoteStats(
  1796. this.jvbJingleSession.peerconnection);
  1797. logger.info('Stopping JVB CallStats');
  1798. this.statistics.stopCallStats(
  1799. this.jvbJingleSession.peerconnection);
  1800. }
  1801. // Current JVB JingleSession is no longer valid, so set it to null
  1802. this.jvbJingleSession = null;
  1803. // Let the RTC service do any cleanups
  1804. this.rtc.onCallEnded();
  1805. } else if (jingleSession === this.p2pJingleSession) {
  1806. // It's the responder who decides to enforce JVB mode, so that both
  1807. // initiator and responder are aware if it was intentional.
  1808. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1809. logger.info('In forced JVB 121 mode...');
  1810. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1811. } else if (reasonCondition === 'connectivity-error'
  1812. && reasonText === 'ICE FAILED') {
  1813. // It can happen that the other peer detects ICE failed and
  1814. // terminates the session, before we get the event on our side.
  1815. // But we are able to parse the reason and mark it here.
  1816. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1817. }
  1818. this._stopP2PSession();
  1819. } else {
  1820. logger.error(
  1821. 'Received onCallEnded for invalid session',
  1822. jingleSession.sid,
  1823. jingleSession.remoteJid,
  1824. reasonCondition,
  1825. reasonText);
  1826. }
  1827. };
  1828. /**
  1829. * Handles the suspend detected event. Leaves the room and fires suspended.
  1830. * @param {JingleSessionPC} jingleSession
  1831. */
  1832. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1833. if (!jingleSession.isP2P) {
  1834. this.leave();
  1835. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1836. }
  1837. };
  1838. JitsiConference.prototype.updateDTMFSupport = function() {
  1839. let somebodySupportsDTMF = false;
  1840. const participants = this.getParticipants();
  1841. // check if at least 1 participant supports DTMF
  1842. for (let i = 0; i < participants.length; i += 1) {
  1843. if (participants[i].supportsDTMF()) {
  1844. somebodySupportsDTMF = true;
  1845. break;
  1846. }
  1847. }
  1848. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1849. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1850. this.eventEmitter.emit(
  1851. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1852. somebodySupportsDTMF);
  1853. }
  1854. };
  1855. /**
  1856. * Allows to check if there is at least one user in the conference
  1857. * that supports DTMF.
  1858. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1859. */
  1860. JitsiConference.prototype.isDTMFSupported = function() {
  1861. return this.somebodySupportsDTMF;
  1862. };
  1863. /**
  1864. * Returns the local user's ID
  1865. * @return {string} local user's ID
  1866. */
  1867. JitsiConference.prototype.myUserId = function() {
  1868. return (
  1869. this.room && this.room.myroomjid
  1870. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1871. : null);
  1872. };
  1873. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1874. const peerConnection = this.getActivePeerConnection();
  1875. if (peerConnection) {
  1876. peerConnection.sendTones(tones, duration, pause);
  1877. } else {
  1878. logger.warn('cannot sendTones: no peer connection');
  1879. }
  1880. };
  1881. /**
  1882. * Starts recording the current conference.
  1883. *
  1884. * @param {Object} options - Configuration for the recording. See
  1885. * {@link Chatroom#startRecording} for more info.
  1886. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1887. */
  1888. JitsiConference.prototype.startRecording = function(options) {
  1889. if (this.room) {
  1890. return this.recordingManager.startRecording(options);
  1891. }
  1892. return Promise.reject(new Error('The conference is not created yet!'));
  1893. };
  1894. /**
  1895. * Stop a recording session.
  1896. *
  1897. * @param {string} sessionID - The ID of the recording session that
  1898. * should be stopped.
  1899. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1900. */
  1901. JitsiConference.prototype.stopRecording = function(sessionID) {
  1902. if (this.room) {
  1903. return this.recordingManager.stopRecording(sessionID);
  1904. }
  1905. return Promise.reject(new Error('The conference is not created yet!'));
  1906. };
  1907. /**
  1908. * Returns true if the SIP calls are supported and false otherwise
  1909. */
  1910. JitsiConference.prototype.isSIPCallingSupported = function() {
  1911. if (this.room) {
  1912. return this.room.isSIPCallingSupported();
  1913. }
  1914. return false;
  1915. };
  1916. /**
  1917. * Dials a number.
  1918. * @param number the number
  1919. */
  1920. JitsiConference.prototype.dial = function(number) {
  1921. if (this.room) {
  1922. return this.room.dial(number);
  1923. }
  1924. return new Promise((resolve, reject) => {
  1925. reject(new Error('The conference is not created yet!'));
  1926. });
  1927. };
  1928. /**
  1929. * Hangup an existing call
  1930. */
  1931. JitsiConference.prototype.hangup = function() {
  1932. if (this.room) {
  1933. return this.room.hangup();
  1934. }
  1935. return new Promise((resolve, reject) => {
  1936. reject(new Error('The conference is not created yet!'));
  1937. });
  1938. };
  1939. /**
  1940. * Starts the transcription service.
  1941. */
  1942. JitsiConference.prototype.startTranscriber = function() {
  1943. return this.dial('jitsi_meet_transcribe');
  1944. };
  1945. /**
  1946. * Stops the transcription service.
  1947. */
  1948. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  1949. /**
  1950. * Returns the phone number for joining the conference.
  1951. */
  1952. JitsiConference.prototype.getPhoneNumber = function() {
  1953. if (this.room) {
  1954. return this.room.getPhoneNumber();
  1955. }
  1956. return null;
  1957. };
  1958. /**
  1959. * Returns the pin for joining the conference with phone.
  1960. */
  1961. JitsiConference.prototype.getPhonePin = function() {
  1962. if (this.room) {
  1963. return this.room.getPhonePin();
  1964. }
  1965. return null;
  1966. };
  1967. /**
  1968. * Returns the meeting unique ID if any.
  1969. *
  1970. * @returns {string|undefined}
  1971. */
  1972. JitsiConference.prototype.getMeetingUniqueId = function() {
  1973. if (this.room) {
  1974. return this.room.getMeetingId();
  1975. }
  1976. };
  1977. /**
  1978. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  1979. * which connection is currently active.
  1980. *
  1981. * @return {TraceablePeerConnection|null} null if there isn't any active
  1982. * <tt>TraceablePeerConnection</tt> currently available.
  1983. * @public (FIXME how to make package local ?)
  1984. */
  1985. JitsiConference.prototype.getActivePeerConnection = function() {
  1986. if (this.isP2PActive()) {
  1987. return this.p2pJingleSession.peerconnection;
  1988. }
  1989. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  1990. };
  1991. /**
  1992. * Returns the connection state for the current room. Its ice connection state
  1993. * for its session.
  1994. * NOTE that "completed" ICE state which can appear on the P2P connection will
  1995. * be converted to "connected".
  1996. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  1997. * peer connection at this time.
  1998. */
  1999. JitsiConference.prototype.getConnectionState = function() {
  2000. const peerConnection = this.getActivePeerConnection();
  2001. return peerConnection ? peerConnection.getConnectionState() : null;
  2002. };
  2003. /**
  2004. * Make all new participants mute their audio/video on join.
  2005. * @param policy {Object} object with 2 boolean properties for video and audio:
  2006. * @param {boolean} audio if audio should be muted.
  2007. * @param {boolean} video if video should be muted.
  2008. */
  2009. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2010. if (!this.isModerator()) {
  2011. return;
  2012. }
  2013. this.startMutedPolicy = policy;
  2014. this.room.addToPresence('startmuted', {
  2015. attributes: {
  2016. audio: policy.audio,
  2017. video: policy.video,
  2018. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2019. }
  2020. });
  2021. this.room.sendPresence();
  2022. };
  2023. /**
  2024. * Returns current start muted policy
  2025. * @returns {Object} with 2 properties - audio and video.
  2026. */
  2027. JitsiConference.prototype.getStartMutedPolicy = function() {
  2028. return this.startMutedPolicy;
  2029. };
  2030. /**
  2031. * Check if audio is muted on join.
  2032. */
  2033. JitsiConference.prototype.isStartAudioMuted = function() {
  2034. return this.startAudioMuted;
  2035. };
  2036. /**
  2037. * Check if video is muted on join.
  2038. */
  2039. JitsiConference.prototype.isStartVideoMuted = function() {
  2040. return this.startVideoMuted;
  2041. };
  2042. /**
  2043. * Returns measured connectionTimes.
  2044. */
  2045. JitsiConference.prototype.getConnectionTimes = function() {
  2046. return this.room.connectionTimes;
  2047. };
  2048. /**
  2049. * Sets a property for the local participant.
  2050. */
  2051. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2052. this.sendCommand(`jitsi_participant_${name}`, { value });
  2053. };
  2054. /**
  2055. * Removes a property for the local participant and sends the updated presence.
  2056. */
  2057. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2058. this.removeCommand(`jitsi_participant_${name}`);
  2059. this.room.sendPresence();
  2060. };
  2061. /**
  2062. * Gets a local participant property.
  2063. *
  2064. * @return value of the local participant property if the tagName exists in the
  2065. * list of properties, otherwise returns undefined.
  2066. */
  2067. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2068. const property = this.room.presMap.nodes.find(prop =>
  2069. prop.tagName === `jitsi_participant_${name}`
  2070. );
  2071. return property ? property.value : undefined;
  2072. };
  2073. /**
  2074. * Sends the given feedback through CallStats if enabled.
  2075. *
  2076. * @param overallFeedback an integer between 1 and 5 indicating the
  2077. * user feedback
  2078. * @param detailedFeedback detailed feedback from the user. Not yet used
  2079. * @returns {Promise} Resolves if feedback is submitted successfully.
  2080. */
  2081. JitsiConference.prototype.sendFeedback = function(
  2082. overallFeedback,
  2083. detailedFeedback) {
  2084. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2085. };
  2086. /**
  2087. * Returns true if the callstats integration is enabled, otherwise returns
  2088. * false.
  2089. *
  2090. * @returns true if the callstats integration is enabled, otherwise returns
  2091. * false.
  2092. */
  2093. JitsiConference.prototype.isCallstatsEnabled = function() {
  2094. return this.statistics.isCallstatsEnabled();
  2095. };
  2096. /**
  2097. * Finds the SSRC of a given track
  2098. *
  2099. * @param track
  2100. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2101. */
  2102. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2103. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2104. };
  2105. /**
  2106. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2107. * from statistics module)
  2108. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2109. * @param container the container
  2110. */
  2111. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2112. const isLocal = track.isLocal();
  2113. let ssrc = null;
  2114. const isP2P = track.isP2P;
  2115. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2116. const peerConnection
  2117. = isP2P
  2118. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2119. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2120. if (isLocal) {
  2121. // Local tracks have SSRC stored on per peer connection basis.
  2122. if (peerConnection) {
  2123. ssrc = peerConnection.getLocalSSRC(track);
  2124. }
  2125. } else {
  2126. ssrc = track.getSSRC();
  2127. }
  2128. if (!container.id || !ssrc || !peerConnection) {
  2129. return;
  2130. }
  2131. this.statistics.associateStreamWithVideoTag(
  2132. peerConnection,
  2133. ssrc,
  2134. isLocal,
  2135. remoteUserId,
  2136. track.getUsageLabel(),
  2137. container.id);
  2138. };
  2139. /**
  2140. * Logs an "application log" message.
  2141. * @param message {string} The message to log. Note that while this can be a
  2142. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2143. * log valid JSON strings, with an "id" field used for distinguishing between
  2144. * message types. E.g.: {id: "recorder_status", status: "off"}
  2145. */
  2146. JitsiConference.prototype.sendApplicationLog = function(message) {
  2147. Statistics.sendLog(message);
  2148. };
  2149. /**
  2150. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2151. * focus.
  2152. * @param mucJid the full MUC address of the user to be checked.
  2153. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2154. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2155. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2156. */
  2157. JitsiConference.prototype._isFocus = function(mucJid) {
  2158. return this.room ? this.room.isFocus(mucJid) : null;
  2159. };
  2160. /**
  2161. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2162. */
  2163. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2164. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2165. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2166. };
  2167. /**
  2168. * Sends a message via the data channel.
  2169. * @param to {string} the id of the endpoint that should receive the message.
  2170. * If "" the message will be sent to all participants.
  2171. * @param payload {object} the payload of the message.
  2172. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2173. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2174. */
  2175. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2176. this.rtc.sendChannelMessage(to, payload);
  2177. };
  2178. /**
  2179. * Sends a broadcast message via the data channel.
  2180. * @param payload {object} the payload of the message.
  2181. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2182. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2183. */
  2184. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2185. this.sendEndpointMessage('', payload);
  2186. };
  2187. /**
  2188. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2189. * broadcasts it to all endpoints in the conference.
  2190. * @param {string} to The ID of the endpoint/participant which is to receive
  2191. * the message, or '' to broadcast the message to all endpoints in the
  2192. * conference.
  2193. * @param {string|object} message the message to send. If this is of type
  2194. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2195. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2196. * JSON before being sent.
  2197. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2198. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2199. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2200. */
  2201. JitsiConference.prototype.sendMessage = function(
  2202. message,
  2203. to = '',
  2204. sendThroughVideobridge = false) {
  2205. const messageType = typeof message;
  2206. // Through videobridge we support only objects. Through XMPP we support
  2207. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2208. // regular chat messages).
  2209. if (messageType !== 'object'
  2210. && (sendThroughVideobridge || messageType !== 'string')) {
  2211. logger.error(`Can not send a message of type ${messageType}`);
  2212. return;
  2213. }
  2214. if (sendThroughVideobridge) {
  2215. this.sendEndpointMessage(to, message);
  2216. } else {
  2217. let messageToSend = message;
  2218. // Name of packet extension of message stanza to send the required
  2219. // message in.
  2220. let elementName = 'body';
  2221. if (messageType === 'object') {
  2222. elementName = 'json-message';
  2223. // Mark as valid JSON message if not already
  2224. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2225. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2226. }
  2227. try {
  2228. messageToSend = JSON.stringify(messageToSend);
  2229. } catch (e) {
  2230. logger.error('Can not send a message, stringify failed: ', e);
  2231. return;
  2232. }
  2233. }
  2234. if (to) {
  2235. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2236. } else {
  2237. // Broadcast
  2238. this.sendTextMessage(messageToSend, elementName);
  2239. }
  2240. }
  2241. };
  2242. JitsiConference.prototype.isConnectionInterrupted = function() {
  2243. return this.isP2PActive()
  2244. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2245. };
  2246. /**
  2247. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2248. * @param {JingleSessionPC} session
  2249. * @private
  2250. */
  2251. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2252. if (session.isP2P) {
  2253. this.isP2PConnectionInterrupted = true;
  2254. } else {
  2255. this.isJvbConnectionInterrupted = true;
  2256. }
  2257. if (session.isP2P === this.isP2PActive()) {
  2258. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2259. }
  2260. };
  2261. /**
  2262. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2263. * @param {JingleSessionPC} session
  2264. * @private
  2265. */
  2266. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2267. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2268. // eventually come up with the new offer (at least for the time being).
  2269. if (session.isP2P) {
  2270. // Add p2pFailed property to analytics to distinguish, between "good"
  2271. // and "bad" connection
  2272. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2273. if (this.p2pJingleSession) {
  2274. Statistics.sendAnalyticsAndLog(
  2275. createP2PEvent(
  2276. ACTION_P2P_FAILED,
  2277. {
  2278. initiator: this.p2pJingleSession.isInitiator
  2279. }));
  2280. }
  2281. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2282. } else if (session && this.jvbJingleSession === session) {
  2283. this._delayedIceFailed = new IceFailedHandling(this);
  2284. this._delayedIceFailed.start(session);
  2285. }
  2286. };
  2287. /**
  2288. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2289. * @param {JingleSessionPC} session
  2290. * @private
  2291. */
  2292. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2293. if (session.isP2P) {
  2294. this.isP2PConnectionInterrupted = false;
  2295. } else {
  2296. this.isJvbConnectionInterrupted = false;
  2297. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2298. }
  2299. if (session.isP2P === this.isP2PActive()) {
  2300. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2301. }
  2302. };
  2303. /**
  2304. * Accept incoming P2P Jingle call.
  2305. * @param {JingleSessionPC} jingleSession the session instance
  2306. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2307. * @private
  2308. */
  2309. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2310. jingleSession,
  2311. jingleOffer) {
  2312. this.isP2PConnectionInterrupted = false;
  2313. // Accept the offer
  2314. this.p2pJingleSession = jingleSession;
  2315. this._sendConferenceJoinAnalyticsEvent();
  2316. this.p2pJingleSession.initialize(
  2317. this.room,
  2318. this.rtc, {
  2319. ...this.options.config,
  2320. enableInsertableStreams: this._isE2EEEnabled()
  2321. });
  2322. logger.info('Starting CallStats for P2P connection...');
  2323. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2324. const participant = this.participants[remoteID];
  2325. if (participant) {
  2326. remoteID = participant.getStatsID() || remoteID;
  2327. }
  2328. this.statistics.startCallStats(
  2329. this.p2pJingleSession.peerconnection,
  2330. remoteID);
  2331. const localTracks = this.getLocalTracks();
  2332. this.p2pJingleSession.acceptOffer(
  2333. jingleOffer,
  2334. () => {
  2335. logger.debug('Got RESULT for P2P "session-accept"');
  2336. this.eventEmitter.emit(
  2337. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2338. this.p2pJingleSession);
  2339. },
  2340. error => {
  2341. logger.error(
  2342. 'Failed to accept incoming P2P Jingle session', error);
  2343. },
  2344. localTracks);
  2345. };
  2346. /**
  2347. * Adds remote tracks to the conference associated with the JVB session.
  2348. * @private
  2349. */
  2350. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2351. this._addRemoteTracks(
  2352. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2353. };
  2354. /**
  2355. * Adds remote tracks to the conference associated with the P2P session.
  2356. * @private
  2357. */
  2358. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2359. this._addRemoteTracks(
  2360. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2361. };
  2362. /**
  2363. * Generates fake "remote track added" events for given Jingle session.
  2364. * @param {string} logName the session's nickname which will appear in log
  2365. * messages.
  2366. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2367. * @private
  2368. */
  2369. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2370. for (const track of remoteTracks) {
  2371. logger.info(`Adding remote ${logName} track: ${track}`);
  2372. this.onRemoteTrackAdded(track);
  2373. }
  2374. };
  2375. /**
  2376. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2377. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2378. * the P2P connection if the event comes from the P2P session.
  2379. * @param {JingleSessionPC} jingleSession the session instance.
  2380. * @private
  2381. */
  2382. JitsiConference.prototype._onIceConnectionEstablished = function(
  2383. jingleSession) {
  2384. if (this.p2pJingleSession !== null) {
  2385. // store the establishment time of the p2p session as a field of the
  2386. // JitsiConference because the p2pJingleSession might get disposed (thus
  2387. // the value is lost).
  2388. this.p2pEstablishmentDuration
  2389. = this.p2pJingleSession.establishmentDuration;
  2390. }
  2391. if (this.jvbJingleSession !== null) {
  2392. this.jvbEstablishmentDuration
  2393. = this.jvbJingleSession.establishmentDuration;
  2394. }
  2395. let done = false;
  2396. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2397. // We don't care about the JVB case, there's nothing to be done
  2398. if (!jingleSession.isP2P) {
  2399. done = true;
  2400. } else if (this.p2pJingleSession !== jingleSession) {
  2401. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2402. done = true;
  2403. } else if (!jingleSession.isInitiator
  2404. && typeof forceJVB121Ratio === 'number'
  2405. && Math.random() < forceJVB121Ratio) {
  2406. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2407. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2408. this._stopP2PSession('decline', 'force JVB121');
  2409. done = true;
  2410. }
  2411. if (!isNaN(this.p2pEstablishmentDuration)
  2412. && !isNaN(this.jvbEstablishmentDuration)) {
  2413. const establishmentDurationDiff
  2414. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2415. Statistics.sendAnalytics(
  2416. ICE_ESTABLISHMENT_DURATION_DIFF,
  2417. { value: establishmentDurationDiff });
  2418. }
  2419. if (jingleSession.isP2P === this.isP2PActive()) {
  2420. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2421. }
  2422. if (done) {
  2423. return;
  2424. }
  2425. // Update P2P status and emit events
  2426. this._setP2PStatus(true);
  2427. // Remove remote tracks
  2428. if (this.jvbJingleSession) {
  2429. this._removeRemoteJVBTracks();
  2430. } else {
  2431. logger.info('Not removing remote JVB tracks - no session yet');
  2432. }
  2433. this._addRemoteP2PTracks();
  2434. // Stop media transfer over the JVB connection
  2435. if (this.jvbJingleSession) {
  2436. this._suspendMediaTransferForJvbConnection();
  2437. }
  2438. logger.info('Starting remote stats with p2p connection');
  2439. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2440. Statistics.sendAnalyticsAndLog(
  2441. createP2PEvent(
  2442. ACTION_P2P_ESTABLISHED,
  2443. {
  2444. initiator: this.p2pJingleSession.isInitiator
  2445. }));
  2446. };
  2447. /**
  2448. * Called when the chat room reads a new list of properties from jicofo's
  2449. * presence. The properties may have changed, but they don't have to.
  2450. *
  2451. * @param {Object} properties - The properties keyed by the property name
  2452. * ('key').
  2453. * @private
  2454. */
  2455. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2456. const changed = !isEqual(properties, this.properties);
  2457. this.properties = properties;
  2458. if (changed) {
  2459. this.eventEmitter.emit(
  2460. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2461. this.properties);
  2462. // Some of the properties need to be added to analytics events.
  2463. const analyticsKeys = [
  2464. // The number of jitsi-videobridge instances currently used for the
  2465. // conference.
  2466. 'bridge-count',
  2467. // The conference creation time (set by jicofo).
  2468. 'created-ms'
  2469. ];
  2470. analyticsKeys.forEach(key => {
  2471. if (properties[key] !== undefined) {
  2472. Statistics.analytics.addPermanentProperties({
  2473. [key.replace('-', '_')]: properties[key]
  2474. });
  2475. }
  2476. });
  2477. }
  2478. };
  2479. /**
  2480. * Gets a conference property with a given key.
  2481. *
  2482. * @param {string} key - The key.
  2483. * @returns {*} The value
  2484. */
  2485. JitsiConference.prototype.getProperty = function(key) {
  2486. return this.properties[key];
  2487. };
  2488. /**
  2489. * Clears the deferred start P2P task if it has been scheduled.
  2490. * @private
  2491. */
  2492. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2493. if (this.deferredStartP2PTask) {
  2494. logger.info('Cleared deferred start P2P task');
  2495. clearTimeout(this.deferredStartP2PTask);
  2496. this.deferredStartP2PTask = null;
  2497. }
  2498. };
  2499. /**
  2500. * Removes from the conference remote tracks associated with the JVB
  2501. * connection.
  2502. * @private
  2503. */
  2504. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2505. this._removeRemoteTracks(
  2506. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2507. };
  2508. /**
  2509. * Removes from the conference remote tracks associated with the P2P
  2510. * connection.
  2511. * @private
  2512. */
  2513. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2514. this._removeRemoteTracks(
  2515. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2516. };
  2517. /**
  2518. * Generates fake "remote track removed" events for given Jingle session.
  2519. * @param {string} sessionNickname the session's nickname which will appear in
  2520. * log messages.
  2521. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2522. * @private
  2523. */
  2524. JitsiConference.prototype._removeRemoteTracks = function(
  2525. sessionNickname,
  2526. remoteTracks) {
  2527. for (const track of remoteTracks) {
  2528. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2529. this.onRemoteTrackRemoved(track);
  2530. }
  2531. };
  2532. /**
  2533. * Resumes media transfer over the JVB connection.
  2534. * @private
  2535. */
  2536. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2537. logger.info('Resuming media transfer over the JVB connection...');
  2538. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2539. () => {
  2540. logger.info('Resumed media transfer over the JVB connection!');
  2541. },
  2542. error => {
  2543. logger.error(
  2544. 'Failed to resume media transfer over the JVB connection:',
  2545. error);
  2546. });
  2547. };
  2548. /**
  2549. * Sets new P2P status and updates some events/states hijacked from
  2550. * the <tt>JitsiConference</tt>.
  2551. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2552. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2553. * @private
  2554. */
  2555. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2556. if (this.p2p === newStatus) {
  2557. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2558. return;
  2559. }
  2560. this.p2p = newStatus;
  2561. if (newStatus) {
  2562. logger.info('Peer to peer connection established!');
  2563. // When we end up in a valid P2P session need to reset the properties
  2564. // in case they have persisted, after session with another peer.
  2565. Statistics.analytics.addPermanentProperties({
  2566. p2pFailed: false,
  2567. forceJvb121: false
  2568. });
  2569. // Sync up video transfer active in case p2pJingleSession not existed
  2570. // when the lastN value was being adjusted.
  2571. const isVideoActive = this.rtc.getLastN() !== 0;
  2572. this.p2pJingleSession
  2573. .setMediaTransferActive(true, isVideoActive)
  2574. .catch(error => {
  2575. logger.error(
  2576. 'Failed to sync up P2P video transfer status'
  2577. + `(${isVideoActive})`, error);
  2578. });
  2579. } else {
  2580. logger.info('Peer to peer connection closed!');
  2581. }
  2582. // Put the JVB connection on hold/resume
  2583. if (this.jvbJingleSession) {
  2584. this.statistics.sendConnectionResumeOrHoldEvent(
  2585. this.jvbJingleSession.peerconnection, !newStatus);
  2586. }
  2587. // Clear dtmfManager, so that it can be recreated with new connection
  2588. this.dtmfManager = null;
  2589. // Update P2P status
  2590. this.eventEmitter.emit(
  2591. JitsiConferenceEvents.P2P_STATUS,
  2592. this,
  2593. this.p2p);
  2594. this.eventEmitter.emit(
  2595. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2596. this._getActiveMediaSession());
  2597. // Refresh connection interrupted/restored
  2598. this.eventEmitter.emit(
  2599. this.isConnectionInterrupted()
  2600. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2601. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2602. };
  2603. /**
  2604. * Starts new P2P session.
  2605. * @param {string} remoteJid the JID of the remote participant
  2606. * @private
  2607. */
  2608. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2609. this._maybeClearDeferredStartP2P();
  2610. if (this.p2pJingleSession) {
  2611. logger.error('P2P session already started!');
  2612. return;
  2613. }
  2614. this.isP2PConnectionInterrupted = false;
  2615. this.p2pJingleSession
  2616. = this.xmpp.connection.jingle.newP2PJingleSession(
  2617. this.room.myroomjid,
  2618. remoteJid);
  2619. logger.info(
  2620. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2621. this._sendConferenceJoinAnalyticsEvent();
  2622. this.p2pJingleSession.initialize(
  2623. this.room,
  2624. this.rtc, {
  2625. ...this.options.config,
  2626. enableInsertableStreams: this._isE2EEEnabled()
  2627. });
  2628. logger.info('Starting CallStats for P2P connection...');
  2629. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2630. const participant = this.participants[remoteID];
  2631. if (participant) {
  2632. remoteID = participant.getStatsID() || remoteID;
  2633. }
  2634. this.statistics.startCallStats(
  2635. this.p2pJingleSession.peerconnection,
  2636. remoteID);
  2637. // NOTE one may consider to start P2P with the local tracks detached,
  2638. // but no data will be sent until ICE succeeds anyway. And we switch
  2639. // immediately once the P2P ICE connects.
  2640. const localTracks = this.getLocalTracks();
  2641. this.p2pJingleSession.invite(localTracks);
  2642. };
  2643. /**
  2644. * Suspends media transfer over the JVB connection.
  2645. * @private
  2646. */
  2647. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2648. logger.info('Suspending media transfer over the JVB connection...');
  2649. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2650. () => {
  2651. logger.info('Suspended media transfer over the JVB connection !');
  2652. },
  2653. error => {
  2654. logger.error(
  2655. 'Failed to suspend media transfer over the JVB connection:',
  2656. error);
  2657. });
  2658. };
  2659. /**
  2660. * Method when called will decide whether it's the time to start or stop
  2661. * the P2P session.
  2662. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2663. * originates from the user left event.
  2664. * @private
  2665. */
  2666. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2667. if (!browser.supportsP2P()
  2668. || !this.isP2PEnabled()
  2669. || this.isP2PTestModeEnabled()) {
  2670. logger.info('Auto P2P disabled');
  2671. return;
  2672. }
  2673. const peers = this.getParticipants();
  2674. const peerCount = peers.length;
  2675. // FIXME 1 peer and it must *support* P2P switching
  2676. const shouldBeInP2P = this._shouldBeInP2PMode();
  2677. // Clear deferred "start P2P" task
  2678. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2679. this._maybeClearDeferredStartP2P();
  2680. }
  2681. // Start peer to peer session
  2682. if (!this.p2pJingleSession && shouldBeInP2P) {
  2683. const peer = peerCount && peers[0];
  2684. const myId = this.myUserId();
  2685. const peersId = peer.getId();
  2686. if (myId > peersId) {
  2687. logger.debug(
  2688. 'I\'m the bigger peersId - '
  2689. + 'the other peer should start P2P', myId, peersId);
  2690. return;
  2691. } else if (myId === peersId) {
  2692. logger.error('The same IDs ? ', myId, peersId);
  2693. return;
  2694. }
  2695. const jid = peer.getJid();
  2696. if (userLeftEvent) {
  2697. if (this.deferredStartP2PTask) {
  2698. logger.error('Deferred start P2P task\'s been set already!');
  2699. return;
  2700. }
  2701. logger.info(
  2702. `Will start P2P with: ${jid} after ${
  2703. this.backToP2PDelay} seconds...`);
  2704. this.deferredStartP2PTask = setTimeout(
  2705. this._startP2PSession.bind(this, jid),
  2706. this.backToP2PDelay * 1000);
  2707. } else {
  2708. logger.info(`Will start P2P with: ${jid}`);
  2709. this._startP2PSession(jid);
  2710. }
  2711. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2712. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2713. // Log that there will be a switch back to the JVB connection
  2714. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2715. Statistics.sendAnalyticsAndLog(
  2716. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2717. }
  2718. this._stopP2PSession();
  2719. }
  2720. };
  2721. /**
  2722. * Tells whether or not this conference should be currently in the P2P mode.
  2723. *
  2724. * @private
  2725. * @returns {boolean}
  2726. */
  2727. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2728. const peers = this.getParticipants();
  2729. const peerCount = peers.length;
  2730. const hasBotPeer = peers.find(p => p._botType === 'poltergeist') !== undefined;
  2731. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2732. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2733. return shouldBeInP2P;
  2734. };
  2735. /**
  2736. * Stops the current P2P session.
  2737. * @param {string} [reason="success"] one of the Jingle "reason" element
  2738. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2739. * @param {string} [reasonDescription="Turing off P2P session"] text
  2740. * description that will be included in the session terminate message
  2741. * @private
  2742. */
  2743. JitsiConference.prototype._stopP2PSession = function(
  2744. reason,
  2745. reasonDescription) {
  2746. if (!this.p2pJingleSession) {
  2747. logger.error('No P2P session to be stopped!');
  2748. return;
  2749. }
  2750. const wasP2PEstablished = this.isP2PActive();
  2751. // Swap remote tracks, but only if the P2P has been fully established
  2752. if (wasP2PEstablished) {
  2753. if (this.jvbJingleSession) {
  2754. this._resumeMediaTransferForJvbConnection();
  2755. }
  2756. // Remove remote P2P tracks
  2757. this._removeRemoteP2PTracks();
  2758. }
  2759. // Stop P2P stats
  2760. logger.info('Stopping remote stats for P2P connection');
  2761. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2762. logger.info('Stopping CallStats for P2P connection');
  2763. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2764. this.p2pJingleSession.terminate(
  2765. () => {
  2766. logger.info('P2P session terminate RESULT');
  2767. },
  2768. error => {
  2769. // Because both initiator and responder are simultaneously
  2770. // terminating their JingleSessions in case of the 'to JVB switch'
  2771. // when 3rd participant joins, both will dispose their sessions and
  2772. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2773. // want to log this as an error since it's expected behaviour.
  2774. //
  2775. // We want them both to terminate, because in case of initiator's
  2776. // crash the responder would stay in P2P mode until ICE fails which
  2777. // could take up to 20 seconds.
  2778. //
  2779. // NOTE lack of 'reason' is considered as graceful session terminate
  2780. // where both initiator and responder terminate their sessions
  2781. // simultaneously.
  2782. if (reason) {
  2783. logger.error(
  2784. 'An error occurred while trying to terminate'
  2785. + ' P2P Jingle session', error);
  2786. }
  2787. }, {
  2788. reason: reason ? reason : 'success',
  2789. reasonDescription: reasonDescription
  2790. ? reasonDescription : 'Turing off P2P session',
  2791. sendSessionTerminate: this.room
  2792. && this.getParticipantById(
  2793. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2794. });
  2795. this.p2pJingleSession = null;
  2796. // Update P2P status and other affected events/states
  2797. this._setP2PStatus(false);
  2798. if (wasP2PEstablished) {
  2799. // Add back remote JVB tracks
  2800. if (this.jvbJingleSession) {
  2801. this._addRemoteJVBTracks();
  2802. } else {
  2803. logger.info('Not adding remote JVB tracks - no session yet');
  2804. }
  2805. }
  2806. };
  2807. /**
  2808. * Checks whether or not the conference is currently in the peer to peer mode.
  2809. * Being in peer to peer mode means that the direct connection has been
  2810. * established and the P2P connection is being used for media transmission.
  2811. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2812. */
  2813. JitsiConference.prototype.isP2PActive = function() {
  2814. return this.p2p;
  2815. };
  2816. /**
  2817. * Returns the current ICE state of the P2P connection.
  2818. * NOTE: method is used by the jitsi-meet-torture tests.
  2819. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2820. * no P2P connection.
  2821. */
  2822. JitsiConference.prototype.getP2PConnectionState = function() {
  2823. if (this.isP2PActive()) {
  2824. return this.p2pJingleSession.peerconnection.getConnectionState();
  2825. }
  2826. return null;
  2827. };
  2828. /**
  2829. * Manually starts new P2P session (should be used only in the tests).
  2830. */
  2831. JitsiConference.prototype.startP2PSession = function() {
  2832. const peers = this.getParticipants();
  2833. // Start peer to peer session
  2834. if (peers.length === 1) {
  2835. const peerJid = peers[0].getJid();
  2836. this._startP2PSession(peerJid);
  2837. } else {
  2838. throw new Error(
  2839. 'There must be exactly 1 participant to start the P2P session !');
  2840. }
  2841. };
  2842. /**
  2843. * Manually stops the current P2P session (should be used only in the tests)
  2844. */
  2845. JitsiConference.prototype.stopP2PSession = function() {
  2846. this._stopP2PSession();
  2847. };
  2848. /**
  2849. * Get a summary of how long current participants have been the dominant speaker
  2850. * @returns {object}
  2851. */
  2852. JitsiConference.prototype.getSpeakerStats = function() {
  2853. return this.speakerStatsCollector.getStats();
  2854. };
  2855. /**
  2856. * Sets the maximum video size the local participant should receive from remote
  2857. * participants.
  2858. *
  2859. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2860. * this receiver is willing to receive.
  2861. * @returns {void}
  2862. */
  2863. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2864. this.qualityController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2865. };
  2866. /**
  2867. * Sets the maximum video size the local participant should send to remote
  2868. * participants.
  2869. * @param {number} maxFrameHeight - The user preferred max frame height.
  2870. * @returns {Promise} promise that will be resolved when the operation is
  2871. * successful and rejected otherwise.
  2872. */
  2873. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2874. return this.qualityController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2875. };
  2876. /**
  2877. * Creates a video SIP GW session and returns it if service is enabled. Before
  2878. * creating a session one need to check whether video SIP GW service is
  2879. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2880. * if there are available nodes to serve this request, after creating the
  2881. * session those nodes can be taken and the request about using the
  2882. * created session can fail.
  2883. *
  2884. * @param {string} sipAddress - The sip address to be used.
  2885. * @param {string} displayName - The display name to be used for this session.
  2886. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2887. * initialised and there is no room.
  2888. */
  2889. JitsiConference.prototype.createVideoSIPGWSession
  2890. = function(sipAddress, displayName) {
  2891. if (!this.room) {
  2892. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2893. }
  2894. return this.videoSIPGWHandler
  2895. .createVideoSIPGWSession(sipAddress, displayName);
  2896. };
  2897. /**
  2898. * Sends a conference.join analytics event.
  2899. *
  2900. * @returns {void}
  2901. */
  2902. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  2903. const meetingId = this.getMeetingUniqueId();
  2904. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  2905. return;
  2906. }
  2907. Statistics.sendAnalytics(createConferenceEvent('joined', {
  2908. meetingId,
  2909. participantId: `${meetingId}.${this._statsCurrentId}`
  2910. }));
  2911. this._conferenceJoinAnalyticsEventSent = Date.now();
  2912. };
  2913. /**
  2914. * Sends conference.left analytics event.
  2915. * @private
  2916. */
  2917. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  2918. const meetingId = this.getMeetingUniqueId();
  2919. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  2920. return;
  2921. }
  2922. Statistics.sendAnalytics(createConferenceEvent('left', {
  2923. meetingId,
  2924. participantId: `${meetingId}.${this._statsCurrentId}`,
  2925. stats: {
  2926. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  2927. perf: this.getPerformanceStats()
  2928. }
  2929. }));
  2930. };
  2931. /**
  2932. * Restarts all active media sessions.
  2933. *
  2934. * @returns {void}
  2935. */
  2936. JitsiConference.prototype._restartMediaSessions = function() {
  2937. if (this.p2pJingleSession) {
  2938. this.stopP2PSession();
  2939. }
  2940. if (this.jvbJingleSession) {
  2941. this.jvbJingleSession.terminate(
  2942. null /* success callback => we don't care */,
  2943. error => {
  2944. logger.warn('An error occurred while trying to terminate the JVB session', error);
  2945. }, {
  2946. reason: 'success',
  2947. reasonDescription: 'restart required',
  2948. requestRestart: true,
  2949. sendSessionTerminate: true
  2950. });
  2951. }
  2952. this._maybeStartOrStopP2P(false);
  2953. };
  2954. /**
  2955. * Returns whether End-To-End encryption is enabled.
  2956. *
  2957. * @returns {boolean}
  2958. */
  2959. JitsiConference.prototype._isE2EEEnabled = function() {
  2960. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  2961. };
  2962. /**
  2963. * Returns whether End-To-End encryption is supported. Note that not all participants
  2964. * in the conference may support it.
  2965. *
  2966. * @returns {boolean}
  2967. */
  2968. JitsiConference.prototype.isE2EESupported = function() {
  2969. return E2EEncryption.isSupported(this.options.config);
  2970. };
  2971. /**
  2972. * Enables / disables End-to-End encryption.
  2973. *
  2974. * @param {boolean} enabled whether to enable E2EE or not.
  2975. * @returns {void}
  2976. */
  2977. JitsiConference.prototype.toggleE2EE = function(enabled) {
  2978. if (!this.isE2EESupported()) {
  2979. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  2980. return;
  2981. }
  2982. this._e2eEncryption.setEnabled(enabled);
  2983. };
  2984. /**
  2985. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  2986. *
  2987. * @returns {boolean} whether lobby is supported in the backend.
  2988. */
  2989. JitsiConference.prototype.isLobbySupported = function() {
  2990. return Boolean(this.room && this.room.getLobby().isSupported());
  2991. };
  2992. /**
  2993. * Returns <tt>true</tt> if the room has members only enabled.
  2994. *
  2995. * @returns {boolean} whether conference room is members only.
  2996. */
  2997. JitsiConference.prototype.isMembersOnly = function() {
  2998. return Boolean(this.room && this.room.membersOnlyEnabled);
  2999. };
  3000. /**
  3001. * Enables lobby by moderators
  3002. *
  3003. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3004. */
  3005. JitsiConference.prototype.enableLobby = function() {
  3006. if (this.room && this.isModerator()) {
  3007. return this.room.getLobby().enable();
  3008. }
  3009. return Promise.reject(
  3010. new Error('The conference not started or user is not moderator'));
  3011. };
  3012. /**
  3013. * Disabled lobby by moderators
  3014. *
  3015. * @returns {void}
  3016. */
  3017. JitsiConference.prototype.disableLobby = function() {
  3018. if (this.room && this.isModerator()) {
  3019. this.room.getLobby().disable();
  3020. }
  3021. };
  3022. /**
  3023. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3024. *
  3025. * @param {string} displayName Display name should be set to show it to moderators.
  3026. * @param {string} email Optional email is used to present avatar to the moderator.
  3027. * @returns {Promise<never>}
  3028. */
  3029. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3030. if (this.room) {
  3031. return this.room.getLobby().join(displayName, email);
  3032. }
  3033. return Promise.reject(new Error('The conference not started'));
  3034. };
  3035. /**
  3036. * Denies an occupant in the lobby room access to the conference.
  3037. * @param {string} id The participant id.
  3038. */
  3039. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3040. if (this.room) {
  3041. this.room.getLobby().denyAccess(id);
  3042. }
  3043. };
  3044. /**
  3045. * Approves the request to join the conference to a participant waiting in the lobby.
  3046. *
  3047. * @param {string} id The participant id.
  3048. */
  3049. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3050. if (this.room) {
  3051. this.room.getLobby().approveAccess(id);
  3052. }
  3053. };