You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JitsiConference.js 114KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578
  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_RESTARTED} event. This happens when the bridge goes down
  2274. * and Jicofo moves conferences away to a different bridge.
  2275. * @param {JingleSessionPC} session
  2276. * @private
  2277. */
  2278. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2279. if (!session.isP2P && this.options.config.enableForcedReload) {
  2280. this.restartInProgress = true;
  2281. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2282. }
  2283. };
  2284. /**
  2285. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2286. * @param {JingleSessionPC} session
  2287. * @private
  2288. */
  2289. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2290. if (session.isP2P) {
  2291. this.isP2PConnectionInterrupted = true;
  2292. } else {
  2293. this.isJvbConnectionInterrupted = true;
  2294. }
  2295. if (session.isP2P === this.isP2PActive()) {
  2296. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2297. }
  2298. };
  2299. /**
  2300. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2301. * @param {JingleSessionPC} session
  2302. * @private
  2303. */
  2304. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2305. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2306. // eventually come up with the new offer (at least for the time being).
  2307. if (session.isP2P) {
  2308. // Add p2pFailed property to analytics to distinguish, between "good"
  2309. // and "bad" connection
  2310. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2311. if (this.p2pJingleSession) {
  2312. Statistics.sendAnalyticsAndLog(
  2313. createP2PEvent(
  2314. ACTION_P2P_FAILED,
  2315. {
  2316. initiator: this.p2pJingleSession.isInitiator
  2317. }));
  2318. }
  2319. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2320. } else if (session && this.jvbJingleSession === session) {
  2321. this._delayedIceFailed = new IceFailedHandling(this);
  2322. this._delayedIceFailed.start(session);
  2323. }
  2324. };
  2325. /**
  2326. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2327. * @param {JingleSessionPC} session
  2328. * @private
  2329. */
  2330. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2331. if (session.isP2P) {
  2332. this.isP2PConnectionInterrupted = false;
  2333. } else {
  2334. this.isJvbConnectionInterrupted = false;
  2335. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2336. }
  2337. if (session.isP2P === this.isP2PActive()) {
  2338. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2339. }
  2340. };
  2341. /**
  2342. * Accept incoming P2P Jingle call.
  2343. * @param {JingleSessionPC} jingleSession the session instance
  2344. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2345. * @private
  2346. */
  2347. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2348. jingleSession,
  2349. jingleOffer) {
  2350. this.isP2PConnectionInterrupted = false;
  2351. // Accept the offer
  2352. this.p2pJingleSession = jingleSession;
  2353. this._sendConferenceJoinAnalyticsEvent();
  2354. this.p2pJingleSession.initialize(
  2355. this.room,
  2356. this.rtc, {
  2357. ...this.options.config,
  2358. enableInsertableStreams: this._isE2EEEnabled()
  2359. });
  2360. logger.info('Starting CallStats for P2P connection...');
  2361. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2362. const participant = this.participants[remoteID];
  2363. if (participant) {
  2364. remoteID = participant.getStatsID() || remoteID;
  2365. }
  2366. this.statistics.startCallStats(
  2367. this.p2pJingleSession.peerconnection,
  2368. remoteID);
  2369. const localTracks = this.getLocalTracks();
  2370. this.p2pJingleSession.acceptOffer(
  2371. jingleOffer,
  2372. () => {
  2373. logger.debug('Got RESULT for P2P "session-accept"');
  2374. this.eventEmitter.emit(
  2375. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2376. this.p2pJingleSession);
  2377. },
  2378. error => {
  2379. logger.error(
  2380. 'Failed to accept incoming P2P Jingle session', error);
  2381. },
  2382. localTracks);
  2383. };
  2384. /**
  2385. * Adds remote tracks to the conference associated with the JVB session.
  2386. * @private
  2387. */
  2388. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2389. this._addRemoteTracks(
  2390. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2391. };
  2392. /**
  2393. * Adds remote tracks to the conference associated with the P2P session.
  2394. * @private
  2395. */
  2396. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2397. this._addRemoteTracks(
  2398. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2399. };
  2400. /**
  2401. * Generates fake "remote track added" events for given Jingle session.
  2402. * @param {string} logName the session's nickname which will appear in log
  2403. * messages.
  2404. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2405. * @private
  2406. */
  2407. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2408. for (const track of remoteTracks) {
  2409. logger.info(`Adding remote ${logName} track: ${track}`);
  2410. this.onRemoteTrackAdded(track);
  2411. }
  2412. };
  2413. /**
  2414. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2415. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2416. * the P2P connection if the event comes from the P2P session.
  2417. * @param {JingleSessionPC} jingleSession the session instance.
  2418. * @private
  2419. */
  2420. JitsiConference.prototype._onIceConnectionEstablished = function(
  2421. jingleSession) {
  2422. if (this.p2pJingleSession !== null) {
  2423. // store the establishment time of the p2p session as a field of the
  2424. // JitsiConference because the p2pJingleSession might get disposed (thus
  2425. // the value is lost).
  2426. this.p2pEstablishmentDuration
  2427. = this.p2pJingleSession.establishmentDuration;
  2428. }
  2429. if (this.jvbJingleSession !== null) {
  2430. this.jvbEstablishmentDuration
  2431. = this.jvbJingleSession.establishmentDuration;
  2432. }
  2433. let done = false;
  2434. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2435. // We don't care about the JVB case, there's nothing to be done
  2436. if (!jingleSession.isP2P) {
  2437. done = true;
  2438. } else if (this.p2pJingleSession !== jingleSession) {
  2439. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2440. done = true;
  2441. } else if (!jingleSession.isInitiator
  2442. && typeof forceJVB121Ratio === 'number'
  2443. && Math.random() < forceJVB121Ratio) {
  2444. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2445. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2446. this._stopP2PSession('decline', 'force JVB121');
  2447. done = true;
  2448. }
  2449. if (!isNaN(this.p2pEstablishmentDuration)
  2450. && !isNaN(this.jvbEstablishmentDuration)) {
  2451. const establishmentDurationDiff
  2452. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2453. Statistics.sendAnalytics(
  2454. ICE_ESTABLISHMENT_DURATION_DIFF,
  2455. { value: establishmentDurationDiff });
  2456. }
  2457. if (jingleSession.isP2P === this.isP2PActive()) {
  2458. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2459. }
  2460. if (done) {
  2461. return;
  2462. }
  2463. // Update P2P status and emit events
  2464. this._setP2PStatus(true);
  2465. // Remove remote tracks
  2466. if (this.jvbJingleSession) {
  2467. this._removeRemoteJVBTracks();
  2468. } else {
  2469. logger.info('Not removing remote JVB tracks - no session yet');
  2470. }
  2471. this._addRemoteP2PTracks();
  2472. // Stop media transfer over the JVB connection
  2473. if (this.jvbJingleSession) {
  2474. this._suspendMediaTransferForJvbConnection();
  2475. }
  2476. logger.info('Starting remote stats with p2p connection');
  2477. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2478. Statistics.sendAnalyticsAndLog(
  2479. createP2PEvent(
  2480. ACTION_P2P_ESTABLISHED,
  2481. {
  2482. initiator: this.p2pJingleSession.isInitiator
  2483. }));
  2484. };
  2485. /**
  2486. * Called when the chat room reads a new list of properties from jicofo's
  2487. * presence. The properties may have changed, but they don't have to.
  2488. *
  2489. * @param {Object} properties - The properties keyed by the property name
  2490. * ('key').
  2491. * @private
  2492. */
  2493. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2494. const changed = !isEqual(properties, this.properties);
  2495. this.properties = properties;
  2496. if (changed) {
  2497. this.eventEmitter.emit(
  2498. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2499. this.properties);
  2500. // Some of the properties need to be added to analytics events.
  2501. const analyticsKeys = [
  2502. // The number of jitsi-videobridge instances currently used for the
  2503. // conference.
  2504. 'bridge-count',
  2505. // The conference creation time (set by jicofo).
  2506. 'created-ms'
  2507. ];
  2508. analyticsKeys.forEach(key => {
  2509. if (properties[key] !== undefined) {
  2510. Statistics.analytics.addPermanentProperties({
  2511. [key.replace('-', '_')]: properties[key]
  2512. });
  2513. }
  2514. });
  2515. }
  2516. };
  2517. /**
  2518. * Gets a conference property with a given key.
  2519. *
  2520. * @param {string} key - The key.
  2521. * @returns {*} The value
  2522. */
  2523. JitsiConference.prototype.getProperty = function(key) {
  2524. return this.properties[key];
  2525. };
  2526. /**
  2527. * Clears the deferred start P2P task if it has been scheduled.
  2528. * @private
  2529. */
  2530. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2531. if (this.deferredStartP2PTask) {
  2532. logger.info('Cleared deferred start P2P task');
  2533. clearTimeout(this.deferredStartP2PTask);
  2534. this.deferredStartP2PTask = null;
  2535. }
  2536. };
  2537. /**
  2538. * Removes from the conference remote tracks associated with the JVB
  2539. * connection.
  2540. * @private
  2541. */
  2542. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2543. this._removeRemoteTracks(
  2544. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2545. };
  2546. /**
  2547. * Removes from the conference remote tracks associated with the P2P
  2548. * connection.
  2549. * @private
  2550. */
  2551. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2552. this._removeRemoteTracks(
  2553. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2554. };
  2555. /**
  2556. * Generates fake "remote track removed" events for given Jingle session.
  2557. * @param {string} sessionNickname the session's nickname which will appear in
  2558. * log messages.
  2559. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2560. * @private
  2561. */
  2562. JitsiConference.prototype._removeRemoteTracks = function(
  2563. sessionNickname,
  2564. remoteTracks) {
  2565. for (const track of remoteTracks) {
  2566. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2567. this.onRemoteTrackRemoved(track);
  2568. }
  2569. };
  2570. /**
  2571. * Resumes media transfer over the JVB connection.
  2572. * @private
  2573. */
  2574. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2575. logger.info('Resuming media transfer over the JVB connection...');
  2576. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2577. () => {
  2578. logger.info('Resumed media transfer over the JVB connection!');
  2579. },
  2580. error => {
  2581. logger.error(
  2582. 'Failed to resume media transfer over the JVB connection:',
  2583. error);
  2584. });
  2585. };
  2586. /**
  2587. * Sets new P2P status and updates some events/states hijacked from
  2588. * the <tt>JitsiConference</tt>.
  2589. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2590. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2591. * @private
  2592. */
  2593. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2594. if (this.p2p === newStatus) {
  2595. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2596. return;
  2597. }
  2598. this.p2p = newStatus;
  2599. if (newStatus) {
  2600. logger.info('Peer to peer connection established!');
  2601. // When we end up in a valid P2P session need to reset the properties
  2602. // in case they have persisted, after session with another peer.
  2603. Statistics.analytics.addPermanentProperties({
  2604. p2pFailed: false,
  2605. forceJvb121: false
  2606. });
  2607. // Sync up video transfer active in case p2pJingleSession not existed
  2608. // when the lastN value was being adjusted.
  2609. const isVideoActive = this.rtc.getLastN() !== 0;
  2610. this.p2pJingleSession
  2611. .setMediaTransferActive(true, isVideoActive)
  2612. .catch(error => {
  2613. logger.error(
  2614. 'Failed to sync up P2P video transfer status'
  2615. + `(${isVideoActive})`, error);
  2616. });
  2617. } else {
  2618. logger.info('Peer to peer connection closed!');
  2619. }
  2620. // Put the JVB connection on hold/resume
  2621. if (this.jvbJingleSession) {
  2622. this.statistics.sendConnectionResumeOrHoldEvent(
  2623. this.jvbJingleSession.peerconnection, !newStatus);
  2624. }
  2625. // Clear dtmfManager, so that it can be recreated with new connection
  2626. this.dtmfManager = null;
  2627. // Update P2P status
  2628. this.eventEmitter.emit(
  2629. JitsiConferenceEvents.P2P_STATUS,
  2630. this,
  2631. this.p2p);
  2632. this.eventEmitter.emit(
  2633. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2634. this._getActiveMediaSession());
  2635. // Refresh connection interrupted/restored
  2636. this.eventEmitter.emit(
  2637. this.isConnectionInterrupted()
  2638. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2639. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2640. };
  2641. /**
  2642. * Starts new P2P session.
  2643. * @param {string} remoteJid the JID of the remote participant
  2644. * @private
  2645. */
  2646. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2647. this._maybeClearDeferredStartP2P();
  2648. if (this.p2pJingleSession) {
  2649. logger.error('P2P session already started!');
  2650. return;
  2651. }
  2652. this.isP2PConnectionInterrupted = false;
  2653. this.p2pJingleSession
  2654. = this.xmpp.connection.jingle.newP2PJingleSession(
  2655. this.room.myroomjid,
  2656. remoteJid);
  2657. logger.info(
  2658. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2659. this._sendConferenceJoinAnalyticsEvent();
  2660. this.p2pJingleSession.initialize(
  2661. this.room,
  2662. this.rtc, {
  2663. ...this.options.config,
  2664. enableInsertableStreams: this._isE2EEEnabled()
  2665. });
  2666. logger.info('Starting CallStats for P2P connection...');
  2667. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2668. const participant = this.participants[remoteID];
  2669. if (participant) {
  2670. remoteID = participant.getStatsID() || remoteID;
  2671. }
  2672. this.statistics.startCallStats(
  2673. this.p2pJingleSession.peerconnection,
  2674. remoteID);
  2675. // NOTE one may consider to start P2P with the local tracks detached,
  2676. // but no data will be sent until ICE succeeds anyway. And we switch
  2677. // immediately once the P2P ICE connects.
  2678. const localTracks = this.getLocalTracks();
  2679. this.p2pJingleSession.invite(localTracks);
  2680. };
  2681. /**
  2682. * Suspends media transfer over the JVB connection.
  2683. * @private
  2684. */
  2685. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2686. logger.info('Suspending media transfer over the JVB connection...');
  2687. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2688. () => {
  2689. logger.info('Suspended media transfer over the JVB connection !');
  2690. },
  2691. error => {
  2692. logger.error(
  2693. 'Failed to suspend media transfer over the JVB connection:',
  2694. error);
  2695. });
  2696. };
  2697. /**
  2698. * Method when called will decide whether it's the time to start or stop
  2699. * the P2P session.
  2700. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2701. * originates from the user left event.
  2702. * @private
  2703. */
  2704. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2705. if (!browser.supportsP2P()
  2706. || !this.isP2PEnabled()
  2707. || this.isP2PTestModeEnabled()) {
  2708. logger.info('Auto P2P disabled');
  2709. return;
  2710. }
  2711. const peers = this.getParticipants();
  2712. const peerCount = peers.length;
  2713. // FIXME 1 peer and it must *support* P2P switching
  2714. const shouldBeInP2P = this._shouldBeInP2PMode();
  2715. // Clear deferred "start P2P" task
  2716. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2717. this._maybeClearDeferredStartP2P();
  2718. }
  2719. // Start peer to peer session
  2720. if (!this.p2pJingleSession && shouldBeInP2P) {
  2721. const peer = peerCount && peers[0];
  2722. const myId = this.myUserId();
  2723. const peersId = peer.getId();
  2724. if (myId > peersId) {
  2725. logger.debug(
  2726. 'I\'m the bigger peersId - '
  2727. + 'the other peer should start P2P', myId, peersId);
  2728. return;
  2729. } else if (myId === peersId) {
  2730. logger.error('The same IDs ? ', myId, peersId);
  2731. return;
  2732. }
  2733. const jid = peer.getJid();
  2734. if (userLeftEvent) {
  2735. if (this.deferredStartP2PTask) {
  2736. logger.error('Deferred start P2P task\'s been set already!');
  2737. return;
  2738. }
  2739. logger.info(
  2740. `Will start P2P with: ${jid} after ${
  2741. this.backToP2PDelay} seconds...`);
  2742. this.deferredStartP2PTask = setTimeout(
  2743. this._startP2PSession.bind(this, jid),
  2744. this.backToP2PDelay * 1000);
  2745. } else {
  2746. logger.info(`Will start P2P with: ${jid}`);
  2747. this._startP2PSession(jid);
  2748. }
  2749. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2750. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2751. // Log that there will be a switch back to the JVB connection
  2752. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2753. Statistics.sendAnalyticsAndLog(
  2754. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2755. }
  2756. this._stopP2PSession();
  2757. }
  2758. };
  2759. /**
  2760. * Tells whether or not this conference should be currently in the P2P mode.
  2761. *
  2762. * @private
  2763. * @returns {boolean}
  2764. */
  2765. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2766. const peers = this.getParticipants();
  2767. const peerCount = peers.length;
  2768. const hasBotPeer = peers.find(p => p._botType === 'poltergeist' || p._features.has(FEATURE_JIGASI)) !== undefined;
  2769. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2770. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2771. return shouldBeInP2P;
  2772. };
  2773. /**
  2774. * Stops the current P2P session.
  2775. * @param {string} [reason="success"] one of the Jingle "reason" element
  2776. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2777. * @param {string} [reasonDescription="Turing off P2P session"] text
  2778. * description that will be included in the session terminate message
  2779. * @private
  2780. */
  2781. JitsiConference.prototype._stopP2PSession = function(
  2782. reason,
  2783. reasonDescription) {
  2784. if (!this.p2pJingleSession) {
  2785. logger.error('No P2P session to be stopped!');
  2786. return;
  2787. }
  2788. const wasP2PEstablished = this.isP2PActive();
  2789. // Swap remote tracks, but only if the P2P has been fully established
  2790. if (wasP2PEstablished) {
  2791. if (this.jvbJingleSession) {
  2792. this._resumeMediaTransferForJvbConnection();
  2793. }
  2794. // Remove remote P2P tracks
  2795. this._removeRemoteP2PTracks();
  2796. }
  2797. // Stop P2P stats
  2798. logger.info('Stopping remote stats for P2P connection');
  2799. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2800. logger.info('Stopping CallStats for P2P connection');
  2801. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2802. this.p2pJingleSession.terminate(
  2803. () => {
  2804. logger.info('P2P session terminate RESULT');
  2805. },
  2806. error => {
  2807. // Because both initiator and responder are simultaneously
  2808. // terminating their JingleSessions in case of the 'to JVB switch'
  2809. // when 3rd participant joins, both will dispose their sessions and
  2810. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2811. // want to log this as an error since it's expected behaviour.
  2812. //
  2813. // We want them both to terminate, because in case of initiator's
  2814. // crash the responder would stay in P2P mode until ICE fails which
  2815. // could take up to 20 seconds.
  2816. //
  2817. // NOTE lack of 'reason' is considered as graceful session terminate
  2818. // where both initiator and responder terminate their sessions
  2819. // simultaneously.
  2820. if (reason) {
  2821. logger.error(
  2822. 'An error occurred while trying to terminate'
  2823. + ' P2P Jingle session', error);
  2824. }
  2825. }, {
  2826. reason: reason ? reason : 'success',
  2827. reasonDescription: reasonDescription
  2828. ? reasonDescription : 'Turing off P2P session',
  2829. sendSessionTerminate: this.room
  2830. && this.getParticipantById(
  2831. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2832. });
  2833. this.p2pJingleSession = null;
  2834. // Update P2P status and other affected events/states
  2835. this._setP2PStatus(false);
  2836. if (wasP2PEstablished) {
  2837. // Add back remote JVB tracks
  2838. if (this.jvbJingleSession) {
  2839. this._addRemoteJVBTracks();
  2840. } else {
  2841. logger.info('Not adding remote JVB tracks - no session yet');
  2842. }
  2843. }
  2844. };
  2845. /**
  2846. * Checks whether or not the conference is currently in the peer to peer mode.
  2847. * Being in peer to peer mode means that the direct connection has been
  2848. * established and the P2P connection is being used for media transmission.
  2849. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2850. */
  2851. JitsiConference.prototype.isP2PActive = function() {
  2852. return this.p2p;
  2853. };
  2854. /**
  2855. * Returns the current ICE state of the P2P connection.
  2856. * NOTE: method is used by the jitsi-meet-torture tests.
  2857. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2858. * no P2P connection.
  2859. */
  2860. JitsiConference.prototype.getP2PConnectionState = function() {
  2861. if (this.isP2PActive()) {
  2862. return this.p2pJingleSession.peerconnection.getConnectionState();
  2863. }
  2864. return null;
  2865. };
  2866. /**
  2867. * Manually starts new P2P session (should be used only in the tests).
  2868. */
  2869. JitsiConference.prototype.startP2PSession = function() {
  2870. const peers = this.getParticipants();
  2871. // Start peer to peer session
  2872. if (peers.length === 1) {
  2873. const peerJid = peers[0].getJid();
  2874. this._startP2PSession(peerJid);
  2875. } else {
  2876. throw new Error(
  2877. 'There must be exactly 1 participant to start the P2P session !');
  2878. }
  2879. };
  2880. /**
  2881. * Manually stops the current P2P session (should be used only in the tests)
  2882. */
  2883. JitsiConference.prototype.stopP2PSession = function() {
  2884. this._stopP2PSession();
  2885. };
  2886. /**
  2887. * Get a summary of how long current participants have been the dominant speaker
  2888. * @returns {object}
  2889. */
  2890. JitsiConference.prototype.getSpeakerStats = function() {
  2891. return this.speakerStatsCollector.getStats();
  2892. };
  2893. /**
  2894. * Sets the maximum video size the local participant should receive from remote
  2895. * participants.
  2896. *
  2897. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2898. * this receiver is willing to receive.
  2899. * @returns {void}
  2900. */
  2901. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2902. this.qualityController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2903. };
  2904. /**
  2905. * Sets the maximum video size the local participant should send to remote
  2906. * participants.
  2907. * @param {number} maxFrameHeight - The user preferred max frame height.
  2908. * @returns {Promise} promise that will be resolved when the operation is
  2909. * successful and rejected otherwise.
  2910. */
  2911. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2912. return this.qualityController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2913. };
  2914. /**
  2915. * Creates a video SIP GW session and returns it if service is enabled. Before
  2916. * creating a session one need to check whether video SIP GW service is
  2917. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2918. * if there are available nodes to serve this request, after creating the
  2919. * session those nodes can be taken and the request about using the
  2920. * created session can fail.
  2921. *
  2922. * @param {string} sipAddress - The sip address to be used.
  2923. * @param {string} displayName - The display name to be used for this session.
  2924. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2925. * initialised and there is no room.
  2926. */
  2927. JitsiConference.prototype.createVideoSIPGWSession
  2928. = function(sipAddress, displayName) {
  2929. if (!this.room) {
  2930. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2931. }
  2932. return this.videoSIPGWHandler
  2933. .createVideoSIPGWSession(sipAddress, displayName);
  2934. };
  2935. /**
  2936. * Sends a conference.join analytics event.
  2937. *
  2938. * @returns {void}
  2939. */
  2940. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  2941. const meetingId = this.getMeetingUniqueId();
  2942. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  2943. return;
  2944. }
  2945. Statistics.sendAnalytics(createConferenceEvent('joined', {
  2946. meetingId,
  2947. participantId: `${meetingId}.${this._statsCurrentId}`
  2948. }));
  2949. this._conferenceJoinAnalyticsEventSent = Date.now();
  2950. };
  2951. /**
  2952. * Sends conference.left analytics event.
  2953. * @private
  2954. */
  2955. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  2956. const meetingId = this.getMeetingUniqueId();
  2957. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  2958. return;
  2959. }
  2960. Statistics.sendAnalytics(createConferenceEvent('left', {
  2961. meetingId,
  2962. participantId: `${meetingId}.${this._statsCurrentId}`,
  2963. stats: {
  2964. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  2965. perf: this.getPerformanceStats()
  2966. }
  2967. }));
  2968. };
  2969. /**
  2970. * Restarts all active media sessions.
  2971. *
  2972. * @returns {void}
  2973. */
  2974. JitsiConference.prototype._restartMediaSessions = function() {
  2975. if (this.p2pJingleSession) {
  2976. this.stopP2PSession();
  2977. }
  2978. if (this.jvbJingleSession) {
  2979. this.jvbJingleSession.terminate(
  2980. null /* success callback => we don't care */,
  2981. error => {
  2982. logger.warn('An error occurred while trying to terminate the JVB session', error);
  2983. }, {
  2984. reason: 'success',
  2985. reasonDescription: 'restart required',
  2986. requestRestart: true,
  2987. sendSessionTerminate: true
  2988. });
  2989. }
  2990. this._maybeStartOrStopP2P(false);
  2991. };
  2992. /**
  2993. * Returns whether End-To-End encryption is enabled.
  2994. *
  2995. * @returns {boolean}
  2996. */
  2997. JitsiConference.prototype._isE2EEEnabled = function() {
  2998. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  2999. };
  3000. /**
  3001. * Returns whether End-To-End encryption is supported. Note that not all participants
  3002. * in the conference may support it.
  3003. *
  3004. * @returns {boolean}
  3005. */
  3006. JitsiConference.prototype.isE2EESupported = function() {
  3007. return E2EEncryption.isSupported(this.options.config);
  3008. };
  3009. /**
  3010. * Enables / disables End-to-End encryption.
  3011. *
  3012. * @param {boolean} enabled whether to enable E2EE or not.
  3013. * @returns {void}
  3014. */
  3015. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3016. if (!this.isE2EESupported()) {
  3017. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3018. return;
  3019. }
  3020. this._e2eEncryption.setEnabled(enabled);
  3021. };
  3022. /**
  3023. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3024. *
  3025. * @returns {boolean} whether lobby is supported in the backend.
  3026. */
  3027. JitsiConference.prototype.isLobbySupported = function() {
  3028. return Boolean(this.room && this.room.getLobby().isSupported());
  3029. };
  3030. /**
  3031. * Returns <tt>true</tt> if the room has members only enabled.
  3032. *
  3033. * @returns {boolean} whether conference room is members only.
  3034. */
  3035. JitsiConference.prototype.isMembersOnly = function() {
  3036. return Boolean(this.room && this.room.membersOnlyEnabled);
  3037. };
  3038. /**
  3039. * Enables lobby by moderators
  3040. *
  3041. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3042. */
  3043. JitsiConference.prototype.enableLobby = function() {
  3044. if (this.room && this.isModerator()) {
  3045. return this.room.getLobby().enable();
  3046. }
  3047. return Promise.reject(
  3048. new Error('The conference not started or user is not moderator'));
  3049. };
  3050. /**
  3051. * Disabled lobby by moderators
  3052. *
  3053. * @returns {void}
  3054. */
  3055. JitsiConference.prototype.disableLobby = function() {
  3056. if (this.room && this.isModerator()) {
  3057. this.room.getLobby().disable();
  3058. }
  3059. };
  3060. /**
  3061. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3062. *
  3063. * @param {string} displayName Display name should be set to show it to moderators.
  3064. * @param {string} email Optional email is used to present avatar to the moderator.
  3065. * @returns {Promise<never>}
  3066. */
  3067. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3068. if (this.room) {
  3069. return this.room.getLobby().join(displayName, email);
  3070. }
  3071. return Promise.reject(new Error('The conference not started'));
  3072. };
  3073. /**
  3074. * Denies an occupant in the lobby room access to the conference.
  3075. * @param {string} id The participant id.
  3076. */
  3077. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3078. if (this.room) {
  3079. this.room.getLobby().denyAccess(id);
  3080. }
  3081. };
  3082. /**
  3083. * Approves the request to join the conference to a participant waiting in the lobby.
  3084. *
  3085. * @param {string} id The participant id.
  3086. */
  3087. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3088. if (this.room) {
  3089. this.room.getLobby().approveAccess(id);
  3090. }
  3091. };