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 94KB

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