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

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