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

JitsiConference.js 111KB

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