您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 77KB

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