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

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