選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

JitsiConference.js 113KB

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