You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 90KB

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