Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 109KB

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