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

JitsiConference.js 97KB

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