Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

JitsiConference.js 113KB

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