Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

JitsiConference.js 104KB

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