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 113KB

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