Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

JitsiConference.js 107KB

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