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

JitsiConference.js 111KB

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