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

JitsiConference.js 115KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  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.isSafari()) {
  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.isSafari()) {
  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. if (newTrack) {
  969. // Now handle the addition of the newTrack at the
  970. // JitsiConference level
  971. this._setupNewTrack(newTrack);
  972. }
  973. return Promise.resolve();
  974. }, error => Promise.reject(new Error(error)));
  975. };
  976. /**
  977. * Replaces the tracks at the lower level by going through the Jingle session
  978. * and WebRTC peer connection. The method will resolve immediately if there is
  979. * currently no JingleSession started.
  980. * @param {JitsiLocalTrack|null} oldTrack the track to be removed during
  981. * the process or <tt>null</t> if the method should act as "add track"
  982. * @param {JitsiLocalTrack|null} newTrack the new track to be added or
  983. * <tt>null</tt> if the method should act as "remove track"
  984. * @return {Promise} resolved when the process is done or rejected with a string
  985. * which describes the error.
  986. * @private
  987. */
  988. JitsiConference.prototype._doReplaceTrack = function(oldTrack, newTrack) {
  989. const replaceTrackPromises = [];
  990. if (this.jvbJingleSession) {
  991. replaceTrackPromises.push(
  992. this.jvbJingleSession.replaceTrack(oldTrack, newTrack));
  993. } else {
  994. logger.info('_doReplaceTrack - no JVB JingleSession');
  995. }
  996. if (this.p2pJingleSession) {
  997. replaceTrackPromises.push(
  998. this.p2pJingleSession.replaceTrack(oldTrack, newTrack));
  999. } else {
  1000. logger.info('_doReplaceTrack - no P2P JingleSession');
  1001. }
  1002. return Promise.all(replaceTrackPromises);
  1003. };
  1004. /**
  1005. * Operations related to creating a new track
  1006. * @param {JitsiLocalTrack} newTrack the new track being created
  1007. */
  1008. JitsiConference.prototype._setupNewTrack = function(newTrack) {
  1009. if (newTrack.isAudioTrack() || (newTrack.isVideoTrack()
  1010. && newTrack.videoType !== VideoType.DESKTOP)) {
  1011. // Report active device to statistics
  1012. const devices = RTC.getCurrentlyAvailableMediaDevices();
  1013. const device
  1014. = devices.find(
  1015. d =>
  1016. d.kind === `${newTrack.getTrack().kind}input`
  1017. && d.label === newTrack.getTrack().label);
  1018. if (device) {
  1019. Statistics.sendActiveDeviceListEvent(
  1020. RTC.getEventDataForActiveDevice(device));
  1021. }
  1022. }
  1023. if (newTrack.isVideoTrack()) {
  1024. this.sendCommand('videoType', {
  1025. value: newTrack.videoType,
  1026. attributes: {
  1027. xmlns: 'http://jitsi.org/jitmeet/video'
  1028. }
  1029. });
  1030. }
  1031. this.rtc.addLocalTrack(newTrack);
  1032. // ensure that we're sharing proper "is muted" state
  1033. if (newTrack.isAudioTrack()) {
  1034. this.room.setAudioMute(newTrack.isMuted());
  1035. } else {
  1036. this.room.setVideoMute(newTrack.isMuted());
  1037. }
  1038. newTrack.muteHandler = this._fireMuteChangeEvent.bind(this, newTrack);
  1039. newTrack.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  1040. newTrack.addEventListener(
  1041. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1042. newTrack.muteHandler);
  1043. newTrack.addEventListener(
  1044. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1045. newTrack.audioLevelHandler);
  1046. newTrack._setConference(this);
  1047. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, newTrack);
  1048. };
  1049. /**
  1050. * Method called by the {@link JitsiLocalTrack} (a video one) in order to add
  1051. * back the underlying WebRTC MediaStream to the PeerConnection (which has
  1052. * removed on video mute).
  1053. * @param {JitsiLocalTrack} track the local track that will be added as part of
  1054. * the unmute operation.
  1055. * @return {Promise} resolved when the process is done or rejected with a string
  1056. * which describes the error.
  1057. */
  1058. JitsiConference.prototype._addLocalTrackAsUnmute = function(track) {
  1059. const addAsUnmutePromises = [];
  1060. if (this.jvbJingleSession) {
  1061. addAsUnmutePromises.push(this.jvbJingleSession.addTrackAsUnmute(track));
  1062. } else {
  1063. logger.info(
  1064. 'Add local MediaStream as unmute -'
  1065. + ' no JVB Jingle session started yet');
  1066. }
  1067. if (this.p2pJingleSession) {
  1068. addAsUnmutePromises.push(this.p2pJingleSession.addTrackAsUnmute(track));
  1069. } else {
  1070. logger.info(
  1071. 'Add local MediaStream as unmute -'
  1072. + ' no P2P Jingle session started yet');
  1073. }
  1074. return Promise.all(addAsUnmutePromises);
  1075. };
  1076. /**
  1077. * Method called by the {@link JitsiLocalTrack} (a video one) in order to remove
  1078. * the underlying WebRTC MediaStream from the PeerConnection. The purpose of
  1079. * that is to stop sending any data and turn off the HW camera device.
  1080. * @param {JitsiLocalTrack} track the local track that will be removed.
  1081. * @return {Promise}
  1082. */
  1083. JitsiConference.prototype._removeLocalTrackAsMute = function(track) {
  1084. const removeAsMutePromises = [];
  1085. if (this.jvbJingleSession) {
  1086. removeAsMutePromises.push(
  1087. this.jvbJingleSession.removeTrackAsMute(track));
  1088. } else {
  1089. logger.info(
  1090. 'Remove local MediaStream - no JVB JingleSession started yet');
  1091. }
  1092. if (this.p2pJingleSession) {
  1093. removeAsMutePromises.push(
  1094. this.p2pJingleSession.removeTrackAsMute(track));
  1095. } else {
  1096. logger.info(
  1097. 'Remove local MediaStream - no P2P JingleSession started yet');
  1098. }
  1099. return Promise.all(removeAsMutePromises);
  1100. };
  1101. /**
  1102. * Get role of the local user.
  1103. * @returns {string} user role: 'moderator' or 'none'
  1104. */
  1105. JitsiConference.prototype.getRole = function() {
  1106. return this.room.role;
  1107. };
  1108. /**
  1109. * Returns whether or not the current conference has been joined as a hidden
  1110. * user.
  1111. *
  1112. * @returns {boolean|null} True if hidden, false otherwise. Will return null if
  1113. * no connection is active.
  1114. */
  1115. JitsiConference.prototype.isHidden = function() {
  1116. if (!this.connection) {
  1117. return null;
  1118. }
  1119. return Strophe.getDomainFromJid(this.connection.getJid())
  1120. === this.options.config.hiddenDomain;
  1121. };
  1122. /**
  1123. * Check if local user is moderator.
  1124. * @returns {boolean|null} true if local user is moderator, false otherwise. If
  1125. * we're no longer in the conference room then <tt>null</tt> is returned.
  1126. */
  1127. JitsiConference.prototype.isModerator = function() {
  1128. return this.room ? this.room.isModerator() : null;
  1129. };
  1130. /**
  1131. * Set password for the room.
  1132. * @param {string} password new password for the room.
  1133. * @returns {Promise}
  1134. */
  1135. JitsiConference.prototype.lock = function(password) {
  1136. if (!this.isModerator()) {
  1137. return Promise.reject(new Error('You are not moderator.'));
  1138. }
  1139. return new Promise((resolve, reject) => {
  1140. this.room.lockRoom(
  1141. password || '',
  1142. () => resolve(),
  1143. err => reject(err),
  1144. () => reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED));
  1145. });
  1146. };
  1147. /**
  1148. * Remove password from the room.
  1149. * @returns {Promise}
  1150. */
  1151. JitsiConference.prototype.unlock = function() {
  1152. return this.lock();
  1153. };
  1154. /**
  1155. * Elects the participant with the given id to be the selected participant in
  1156. * order to receive higher video quality (if simulcast is enabled).
  1157. * Or cache it if channel is not created and send it once channel is available.
  1158. * @param participantId the identifier of the participant
  1159. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  1160. * @returns {void}
  1161. */
  1162. JitsiConference.prototype.selectParticipant = function(participantId) {
  1163. this.selectParticipants([ participantId ]);
  1164. };
  1165. /*
  1166. * Elects participants with given ids to be the selected participants in order
  1167. * to receive higher video quality (if simulcast is enabled). The argument
  1168. * should be an array of participant id strings or an empty array; an error will
  1169. * be thrown if a non-array is passed in. The error is thrown as a layer of
  1170. * protection against passing an invalid argument, as the error will happen in
  1171. * the bridge and may not be visible in the client.
  1172. *
  1173. * @param {Array<strings>} participantIds - An array of identifiers for
  1174. * participants.
  1175. * @returns {void}
  1176. */
  1177. JitsiConference.prototype.selectParticipants = function(participantIds) {
  1178. if (!Array.isArray(participantIds)) {
  1179. throw new Error('Invalid argument; participantIds must be an array.');
  1180. }
  1181. this.receiveVideoController.selectEndpoints(participantIds);
  1182. };
  1183. /**
  1184. * Obtains the current value for "lastN". See {@link setLastN} for more info.
  1185. * @returns {number}
  1186. */
  1187. JitsiConference.prototype.getLastN = function() {
  1188. return this.receiveVideoController.getLastN();
  1189. };
  1190. /**
  1191. * Selects a new value for "lastN". The requested amount of videos are going
  1192. * to be delivered after the value is in effect. Set to -1 for unlimited or
  1193. * all available videos.
  1194. * @param lastN the new number of videos the user would like to receive.
  1195. * @throws Error or RangeError if the given value is not a number or is smaller
  1196. * than -1.
  1197. */
  1198. JitsiConference.prototype.setLastN = function(lastN) {
  1199. if (!Number.isInteger(lastN) && !Number.parseInt(lastN, 10)) {
  1200. throw new Error(`Invalid value for lastN: ${lastN}`);
  1201. }
  1202. const n = Number(lastN);
  1203. if (n < -1) {
  1204. throw new RangeError('lastN cannot be smaller than -1');
  1205. }
  1206. this.receiveVideoController.setLastN(n);
  1207. // If the P2P session is not fully established yet, we wait until it gets
  1208. // established.
  1209. if (this.p2pJingleSession) {
  1210. const isVideoActive = n !== 0;
  1211. this.p2pJingleSession
  1212. .setMediaTransferActive(true, isVideoActive)
  1213. .catch(error => {
  1214. logger.error(
  1215. `Failed to adjust video transfer status (${isVideoActive})`,
  1216. error);
  1217. });
  1218. }
  1219. };
  1220. /**
  1221. * Checks if the participant given by participantId is currently included in
  1222. * the last N.
  1223. * @param {string} participantId the identifier of the participant we would
  1224. * like to check.
  1225. * @return {boolean} true if the participant with id is in the last N set or
  1226. * if there's no last N set, false otherwise.
  1227. * @deprecated this method should never be used to figure out the UI, but
  1228. * {@link ParticipantConnectionStatus} should be used instead.
  1229. */
  1230. JitsiConference.prototype.isInLastN = function(participantId) {
  1231. return this.rtc.isInLastN(participantId);
  1232. };
  1233. /**
  1234. * @return Array<JitsiParticipant> an array of all participants in this
  1235. * conference.
  1236. */
  1237. JitsiConference.prototype.getParticipants = function() {
  1238. return Object.values(this.participants);
  1239. };
  1240. /**
  1241. * Returns the number of participants in the conference, including the local
  1242. * participant.
  1243. * @param countHidden {boolean} Whether or not to include hidden participants
  1244. * in the count. Default: false.
  1245. **/
  1246. JitsiConference.prototype.getParticipantCount
  1247. = function(countHidden = false) {
  1248. let participants = this.getParticipants();
  1249. if (!countHidden) {
  1250. participants = participants.filter(p => !p.isHidden());
  1251. }
  1252. // Add one for the local participant.
  1253. return participants.length + 1;
  1254. };
  1255. /**
  1256. * @returns {JitsiParticipant} the participant in this conference with the
  1257. * specified id (or undefined if there isn't one).
  1258. * @param id the id of the participant.
  1259. */
  1260. JitsiConference.prototype.getParticipantById = function(id) {
  1261. return this.participants[id];
  1262. };
  1263. /**
  1264. * Grant owner rights to the participant.
  1265. * @param {string} id id of the participant to grant owner rights to.
  1266. */
  1267. JitsiConference.prototype.grantOwner = function(id) {
  1268. const participant = this.getParticipantById(id);
  1269. if (!participant) {
  1270. return;
  1271. }
  1272. this.room.setAffiliation(participant.getJid(), 'owner');
  1273. };
  1274. /**
  1275. * Kick participant from this conference.
  1276. * @param {string} id id of the participant to kick
  1277. */
  1278. JitsiConference.prototype.kickParticipant = function(id) {
  1279. const participant = this.getParticipantById(id);
  1280. if (!participant) {
  1281. return;
  1282. }
  1283. this.room.kick(participant.getJid());
  1284. };
  1285. /**
  1286. * Maybe clears the timeout which emits {@link ACTION_JINGLE_SI_TIMEOUT}
  1287. * analytics event.
  1288. * @private
  1289. */
  1290. JitsiConference.prototype._maybeClearSITimeout = function() {
  1291. if (this._sessionInitiateTimeout
  1292. && (this.jvbJingleSession || this.getParticipantCount() < 2)) {
  1293. window.clearTimeout(this._sessionInitiateTimeout);
  1294. this._sessionInitiateTimeout = null;
  1295. }
  1296. };
  1297. /**
  1298. * Sets a timeout which will emit {@link ACTION_JINGLE_SI_TIMEOUT} analytics
  1299. * event.
  1300. * @private
  1301. */
  1302. JitsiConference.prototype._maybeSetSITimeout = function() {
  1303. // Jicofo is supposed to invite if there are at least 2 participants
  1304. if (!this.jvbJingleSession
  1305. && this.getParticipantCount() >= 2
  1306. && !this._sessionInitiateTimeout) {
  1307. this._sessionInitiateTimeout = window.setTimeout(() => {
  1308. this._sessionInitiateTimeout = null;
  1309. Statistics.sendAnalytics(createJingleEvent(
  1310. ACTION_JINGLE_SI_TIMEOUT,
  1311. {
  1312. p2p: false,
  1313. value: JINGLE_SI_TIMEOUT
  1314. }));
  1315. }, JINGLE_SI_TIMEOUT);
  1316. }
  1317. };
  1318. /**
  1319. * Mutes a participant.
  1320. * @param {string} id The id of the participant to mute.
  1321. */
  1322. JitsiConference.prototype.muteParticipant = function(id, mediaType) {
  1323. const muteMediaType = mediaType ? mediaType : MediaType.AUDIO;
  1324. if (muteMediaType !== MediaType.AUDIO && muteMediaType !== MediaType.VIDEO) {
  1325. logger.error(`Unsupported media type: ${muteMediaType}`);
  1326. return;
  1327. }
  1328. const participant = this.getParticipantById(id);
  1329. if (!participant) {
  1330. return;
  1331. }
  1332. this.room.muteParticipant(participant.getJid(), true, muteMediaType);
  1333. };
  1334. /* eslint-disable max-params */
  1335. /**
  1336. * Notifies this JitsiConference that a new member has joined its chat room.
  1337. *
  1338. * FIXME This should NOT be exposed!
  1339. *
  1340. * @param jid the jid of the participant in the MUC
  1341. * @param nick the display name of the participant
  1342. * @param role the role of the participant in the MUC
  1343. * @param isHidden indicates if this is a hidden participant (system
  1344. * participant for example a recorder).
  1345. * @param statsID the participant statsID (optional)
  1346. * @param status the initial status if any
  1347. * @param identity the member identity, if any
  1348. * @param botType the member botType, if any
  1349. * @param fullJid the member full jid, if any
  1350. * @param features the member botType, if any
  1351. */
  1352. JitsiConference.prototype.onMemberJoined = function(
  1353. jid, nick, role, isHidden, statsID, status, identity, botType, fullJid, features) {
  1354. const id = Strophe.getResourceFromJid(jid);
  1355. if (id === 'focus' || this.myUserId() === id) {
  1356. return;
  1357. }
  1358. const participant
  1359. = new JitsiParticipant(jid, this, nick, isHidden, statsID, status, identity);
  1360. participant.setRole(role);
  1361. participant.setBotType(botType);
  1362. participant.setFeatures(features);
  1363. this.participants[id] = participant;
  1364. this.eventEmitter.emit(
  1365. JitsiConferenceEvents.USER_JOINED,
  1366. id,
  1367. participant);
  1368. this._updateFeatures(participant);
  1369. // maybeStart only if we had finished joining as then we will have information for the number of participants
  1370. if (this.isJoined()) {
  1371. this._maybeStartOrStopP2P();
  1372. }
  1373. this._maybeSetSITimeout();
  1374. };
  1375. /* eslint-enable max-params */
  1376. /**
  1377. * Get notified when we joined the room.
  1378. *
  1379. * FIXME This should NOT be exposed!
  1380. *
  1381. * @private
  1382. */
  1383. JitsiConference.prototype._onMucJoined = function() {
  1384. this._maybeStartOrStopP2P();
  1385. };
  1386. /**
  1387. * Updates features for a participant.
  1388. * @param {JitsiParticipant} participant - The participant to query for features.
  1389. * @returns {void}
  1390. * @private
  1391. */
  1392. JitsiConference.prototype._updateFeatures = function(participant) {
  1393. participant.getFeatures()
  1394. .then(features => {
  1395. participant._supportsDTMF = features.has('urn:xmpp:jingle:dtmf:0');
  1396. this.updateDTMFSupport();
  1397. if (features.has(FEATURE_JIGASI)) {
  1398. participant.setProperty('features_jigasi', true);
  1399. }
  1400. if (features.has(FEATURE_E2EE)) {
  1401. participant.setProperty('features_e2ee', true);
  1402. }
  1403. })
  1404. .catch(() => false);
  1405. };
  1406. /**
  1407. * Get notified when member bot type had changed.
  1408. * @param jid the member jid
  1409. * @param botType the new botType value
  1410. * @private
  1411. */
  1412. JitsiConference.prototype._onMemberBotTypeChanged = function(jid, botType) {
  1413. // find the participant and mark it as non bot, as the real one will join
  1414. // in a moment
  1415. const peers = this.getParticipants();
  1416. const botParticipant = peers.find(p => p.getJid() === jid);
  1417. if (botParticipant) {
  1418. botParticipant.setBotType(botType);
  1419. const id = Strophe.getResourceFromJid(jid);
  1420. this.eventEmitter.emit(
  1421. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1422. id,
  1423. botType);
  1424. }
  1425. // if botType changed to undefined, botType was removed, in case of
  1426. // poltergeist mode this is the moment when the poltergeist had exited and
  1427. // the real participant had already replaced it.
  1428. // In this case we can check and try p2p
  1429. if (!botParticipant.getBotType()) {
  1430. this._maybeStartOrStopP2P();
  1431. }
  1432. };
  1433. JitsiConference.prototype.onMemberLeft = function(jid) {
  1434. const id = Strophe.getResourceFromJid(jid);
  1435. if (id === 'focus' || this.myUserId() === id) {
  1436. return;
  1437. }
  1438. const participant = this.participants[id];
  1439. delete this.participants[id];
  1440. const removedTracks = this.rtc.removeRemoteTracks(id);
  1441. removedTracks.forEach(
  1442. track =>
  1443. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track));
  1444. // there can be no participant in case the member that left is focus
  1445. if (participant) {
  1446. this.eventEmitter.emit(
  1447. JitsiConferenceEvents.USER_LEFT, id, participant);
  1448. }
  1449. this._maybeStartOrStopP2P(true /* triggered by user left event */);
  1450. this._maybeClearSITimeout();
  1451. };
  1452. /**
  1453. * Designates an event indicating that we were kicked from the XMPP MUC.
  1454. * @param {boolean} isSelfPresence - whether it is for local participant
  1455. * or another participant.
  1456. * @param {string} actorId - the id of the participant who was initiator
  1457. * of the kick.
  1458. * @param {string?} kickedParticipantId - when it is not a kick for local participant,
  1459. * this is the id of the participant which was kicked.
  1460. */
  1461. JitsiConference.prototype.onMemberKicked = function(isSelfPresence, actorId, kickedParticipantId) {
  1462. // This check which be true when we kick someone else. With the introduction of lobby
  1463. // the ChatRoom KICKED event is now also emitted for ourselves (the kicker) so we want to
  1464. // avoid emitting an event where `undefined` kicked someone.
  1465. if (actorId === this.myUserId()) {
  1466. return;
  1467. }
  1468. const actorParticipant = this.participants[actorId];
  1469. if (isSelfPresence) {
  1470. this.eventEmitter.emit(
  1471. JitsiConferenceEvents.KICKED, actorParticipant);
  1472. this.leave();
  1473. return;
  1474. }
  1475. const kickedParticipant = this.participants[kickedParticipantId];
  1476. this.eventEmitter.emit(
  1477. JitsiConferenceEvents.PARTICIPANT_KICKED, actorParticipant, kickedParticipant);
  1478. };
  1479. /**
  1480. * Method called on local MUC role change.
  1481. * @param {string} role the name of new user's role as defined by XMPP MUC.
  1482. */
  1483. JitsiConference.prototype.onLocalRoleChanged = function(role) {
  1484. // Emit role changed for local JID
  1485. this.eventEmitter.emit(
  1486. JitsiConferenceEvents.USER_ROLE_CHANGED, this.myUserId(), role);
  1487. };
  1488. JitsiConference.prototype.onUserRoleChanged = function(jid, role) {
  1489. const id = Strophe.getResourceFromJid(jid);
  1490. const participant = this.getParticipantById(id);
  1491. if (!participant) {
  1492. return;
  1493. }
  1494. participant.setRole(role);
  1495. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  1496. };
  1497. JitsiConference.prototype.onDisplayNameChanged = function(jid, displayName) {
  1498. const id = Strophe.getResourceFromJid(jid);
  1499. const participant = this.getParticipantById(id);
  1500. if (!participant) {
  1501. return;
  1502. }
  1503. if (participant._displayName === displayName) {
  1504. return;
  1505. }
  1506. participant._displayName = displayName;
  1507. this.eventEmitter.emit(
  1508. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1509. id,
  1510. displayName);
  1511. };
  1512. /**
  1513. * Notifies this JitsiConference that a JitsiRemoteTrack was added into
  1514. * the conference.
  1515. *
  1516. * @param {JitsiRemoteTrack} track the JitsiRemoteTrack which was added to this
  1517. * JitsiConference
  1518. */
  1519. JitsiConference.prototype.onRemoteTrackAdded = function(track) {
  1520. if (track.isP2P && !this.isP2PActive()) {
  1521. logger.info(
  1522. 'Trying to add remote P2P track, when not in P2P - IGNORED');
  1523. return;
  1524. } else if (!track.isP2P && this.isP2PActive()) {
  1525. logger.info(
  1526. 'Trying to add remote JVB track, when in P2P - IGNORED');
  1527. return;
  1528. }
  1529. const id = track.getParticipantId();
  1530. const participant = this.getParticipantById(id);
  1531. if (!participant) {
  1532. logger.error(`No participant found for id: ${id}`);
  1533. return;
  1534. }
  1535. // Add track to JitsiParticipant.
  1536. participant._tracks.push(track);
  1537. if (this.transcriber) {
  1538. this.transcriber.addTrack(track);
  1539. }
  1540. const emitter = this.eventEmitter;
  1541. track.addEventListener(
  1542. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  1543. () => emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track));
  1544. track.addEventListener(
  1545. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1546. (audioLevel, tpc) => {
  1547. const activeTPC = this.getActivePeerConnection();
  1548. if (activeTPC === tpc) {
  1549. emitter.emit(
  1550. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  1551. id,
  1552. audioLevel);
  1553. }
  1554. }
  1555. );
  1556. emitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  1557. };
  1558. /**
  1559. * Callback called by the Jingle plugin when 'session-answer' is received.
  1560. * @param {JingleSessionPC} session the Jingle session for which an answer was
  1561. * received.
  1562. * @param {jQuery} answer a jQuery selector pointing to 'jingle' IQ element
  1563. */
  1564. // eslint-disable-next-line no-unused-vars
  1565. JitsiConference.prototype.onCallAccepted = function(session, answer) {
  1566. if (this.p2pJingleSession === session) {
  1567. logger.info('P2P setAnswer');
  1568. this.p2pJingleSession.setAnswer(answer);
  1569. this.eventEmitter.emit(JitsiConferenceEvents._MEDIA_SESSION_STARTED, this.p2pJingleSession);
  1570. }
  1571. };
  1572. /**
  1573. * Callback called by the Jingle plugin when 'transport-info' is received.
  1574. * @param {JingleSessionPC} session the Jingle session for which the IQ was
  1575. * received
  1576. * @param {jQuery} transportInfo a jQuery selector pointing to 'jingle' IQ
  1577. * element
  1578. */
  1579. // eslint-disable-next-line no-unused-vars
  1580. JitsiConference.prototype.onTransportInfo = function(session, transportInfo) {
  1581. if (this.p2pJingleSession === session) {
  1582. logger.info('P2P addIceCandidates');
  1583. this.p2pJingleSession.addIceCandidates(transportInfo);
  1584. }
  1585. };
  1586. /**
  1587. * Notifies this JitsiConference that a JitsiRemoteTrack was removed from
  1588. * the conference.
  1589. *
  1590. * @param {JitsiRemoteTrack} removedTrack
  1591. */
  1592. JitsiConference.prototype.onRemoteTrackRemoved = function(removedTrack) {
  1593. this.getParticipants().forEach(participant => {
  1594. const tracks = participant.getTracks();
  1595. for (let i = 0; i < tracks.length; i++) {
  1596. if (tracks[i] === removedTrack) {
  1597. // Since the tracks have been compared and are
  1598. // considered equal the result of splice can be ignored.
  1599. participant._tracks.splice(i, 1);
  1600. this.eventEmitter.emit(
  1601. JitsiConferenceEvents.TRACK_REMOVED, removedTrack);
  1602. if (this.transcriber) {
  1603. this.transcriber.removeTrack(removedTrack);
  1604. }
  1605. break;
  1606. }
  1607. }
  1608. }, this);
  1609. };
  1610. /**
  1611. * Handles an incoming call event for the P2P jingle session.
  1612. */
  1613. JitsiConference.prototype._onIncomingCallP2P = function(
  1614. jingleSession,
  1615. jingleOffer) {
  1616. let rejectReason;
  1617. if (!browser.supportsP2P()) {
  1618. rejectReason = {
  1619. reason: 'unsupported-applications',
  1620. reasonDescription: 'P2P not supported',
  1621. errorMsg: 'This client does not support P2P connections'
  1622. };
  1623. } else if (!this.isP2PEnabled() && !this.isP2PTestModeEnabled()) {
  1624. rejectReason = {
  1625. reason: 'decline',
  1626. reasonDescription: 'P2P disabled',
  1627. errorMsg: 'P2P mode disabled in the configuration'
  1628. };
  1629. } else if (this.p2pJingleSession) {
  1630. // Reject incoming P2P call (already in progress)
  1631. rejectReason = {
  1632. reason: 'busy',
  1633. reasonDescription: 'P2P already in progress',
  1634. errorMsg: 'Duplicated P2P "session-initiate"'
  1635. };
  1636. } else if (!this._shouldBeInP2PMode()) {
  1637. rejectReason = {
  1638. reason: 'decline',
  1639. reasonDescription: 'P2P requirements not met',
  1640. errorMsg: 'Received P2P "session-initiate" when should not be in P2P mode'
  1641. };
  1642. Statistics.sendAnalytics(createJingleEvent(ACTION_P2P_DECLINED));
  1643. }
  1644. if (rejectReason) {
  1645. this._rejectIncomingCall(jingleSession, rejectReason);
  1646. } else {
  1647. this._acceptP2PIncomingCall(jingleSession, jingleOffer);
  1648. }
  1649. };
  1650. /**
  1651. * Handles an incoming call event.
  1652. */
  1653. JitsiConference.prototype.onIncomingCall = function(
  1654. jingleSession,
  1655. jingleOffer,
  1656. now) {
  1657. // Handle incoming P2P call
  1658. if (jingleSession.isP2P) {
  1659. this._onIncomingCallP2P(jingleSession, jingleOffer);
  1660. } else {
  1661. if (!this.room.isFocus(jingleSession.remoteJid)) {
  1662. const description = 'Rejecting session-initiate from non-focus.';
  1663. this._rejectIncomingCall(
  1664. jingleSession, {
  1665. reason: 'security-error',
  1666. reasonDescription: description,
  1667. errorMsg: description
  1668. });
  1669. return;
  1670. }
  1671. this._acceptJvbIncomingCall(jingleSession, jingleOffer, now);
  1672. }
  1673. };
  1674. /**
  1675. * Accepts an incoming call event for the JVB jingle session.
  1676. */
  1677. JitsiConference.prototype._acceptJvbIncomingCall = function(
  1678. jingleSession,
  1679. jingleOffer,
  1680. now) {
  1681. // Accept incoming call
  1682. this.jvbJingleSession = jingleSession;
  1683. this.room.connectionTimes['session.initiate'] = now;
  1684. this._sendConferenceJoinAnalyticsEvent();
  1685. if (this.wasStopped) {
  1686. Statistics.sendAnalyticsAndLog(
  1687. createJingleEvent(ACTION_JINGLE_RESTART, { p2p: false }));
  1688. }
  1689. const serverRegion
  1690. = $(jingleOffer)
  1691. .find('>bridge-session[xmlns="http://jitsi.org/protocol/focus"]')
  1692. .attr('region');
  1693. this.eventEmitter.emit(
  1694. JitsiConferenceEvents.SERVER_REGION_CHANGED,
  1695. serverRegion);
  1696. this._maybeClearSITimeout();
  1697. Statistics.sendAnalytics(createJingleEvent(
  1698. ACTION_JINGLE_SI_RECEIVED,
  1699. {
  1700. p2p: false,
  1701. value: now
  1702. }));
  1703. try {
  1704. jingleSession.initialize(this.room, this.rtc, {
  1705. ...this.options.config,
  1706. enableInsertableStreams: this._isE2EEEnabled()
  1707. });
  1708. } catch (error) {
  1709. GlobalOnErrorHandler.callErrorHandler(error);
  1710. logger.error(error);
  1711. return;
  1712. }
  1713. // Open a channel with the videobridge.
  1714. this._setBridgeChannel(jingleOffer, jingleSession.peerconnection);
  1715. const localTracks = this._getInitialLocalTracks();
  1716. try {
  1717. jingleSession.acceptOffer(
  1718. jingleOffer,
  1719. () => {
  1720. // If for any reason invite for the JVB session arrived after
  1721. // the P2P has been established already the media transfer needs
  1722. // to be turned off here.
  1723. if (this.isP2PActive() && this.jvbJingleSession) {
  1724. this._suspendMediaTransferForJvbConnection();
  1725. }
  1726. this.eventEmitter.emit(
  1727. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  1728. jingleSession);
  1729. if (!this.isP2PActive()) {
  1730. this.eventEmitter.emit(
  1731. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  1732. jingleSession);
  1733. }
  1734. },
  1735. error => {
  1736. GlobalOnErrorHandler.callErrorHandler(error);
  1737. logger.error(
  1738. 'Failed to accept incoming Jingle session', error);
  1739. },
  1740. localTracks
  1741. );
  1742. // Start callstats as soon as peerconnection is initialized,
  1743. // do not wait for XMPPEvents.PEERCONNECTION_READY, as it may never
  1744. // happen in case if user doesn't have or denied permission to
  1745. // both camera and microphone.
  1746. logger.info('Starting CallStats for JVB connection...');
  1747. this.statistics.startCallStats(
  1748. this.jvbJingleSession.peerconnection,
  1749. 'jitsi' /* Remote user ID for JVB is 'jitsi' */);
  1750. this.statistics.startRemoteStats(this.jvbJingleSession.peerconnection);
  1751. } catch (e) {
  1752. GlobalOnErrorHandler.callErrorHandler(e);
  1753. logger.error(e);
  1754. }
  1755. };
  1756. /**
  1757. * Sets the BridgeChannel.
  1758. *
  1759. * @param {jQuery} offerIq a jQuery selector pointing to the jingle element of
  1760. * the offer IQ which may carry the WebSocket URL for the 'websocket'
  1761. * BridgeChannel mode.
  1762. * @param {TraceablePeerConnection} pc the peer connection which will be used
  1763. * to listen for new WebRTC Data Channels (in the 'datachannel' mode).
  1764. */
  1765. JitsiConference.prototype._setBridgeChannel = function(offerIq, pc) {
  1766. let wsUrl = null;
  1767. const webSocket
  1768. = $(offerIq)
  1769. .find('>content>transport>web-socket')
  1770. .first();
  1771. if (webSocket.length === 1) {
  1772. wsUrl = webSocket[0].getAttribute('url');
  1773. }
  1774. if (wsUrl) {
  1775. // If the offer contains a websocket use it.
  1776. this.rtc.initializeBridgeChannel(null, wsUrl);
  1777. } else {
  1778. // Otherwise, fall back to an attempt to use SCTP.
  1779. this.rtc.initializeBridgeChannel(pc, null);
  1780. }
  1781. };
  1782. /**
  1783. * Rejects incoming Jingle call.
  1784. * @param {JingleSessionPC} jingleSession the session instance to be rejected.
  1785. * @param {object} [options]
  1786. * @param {string} options.reason the name of the reason element as defined
  1787. * by Jingle
  1788. * @param {string} options.reasonDescription the reason description which will
  1789. * be included in Jingle 'session-terminate' message.
  1790. * @param {string} options.errorMsg an error message to be logged on global
  1791. * error handler
  1792. * @private
  1793. */
  1794. JitsiConference.prototype._rejectIncomingCall = function(
  1795. jingleSession,
  1796. options) {
  1797. if (options && options.errorMsg) {
  1798. GlobalOnErrorHandler.callErrorHandler(new Error(options.errorMsg));
  1799. }
  1800. // Terminate the jingle session with a reason
  1801. jingleSession.terminate(
  1802. null /* success callback => we don't care */,
  1803. error => {
  1804. logger.warn(
  1805. 'An error occurred while trying to terminate'
  1806. + ' invalid Jingle session', error);
  1807. }, {
  1808. reason: options && options.reason,
  1809. reasonDescription: options && options.reasonDescription,
  1810. sendSessionTerminate: true
  1811. });
  1812. };
  1813. /**
  1814. * Handles the call ended event.
  1815. * XXX is this due to the remote side terminating the Jingle session?
  1816. *
  1817. * @param {JingleSessionPC} jingleSession the jingle session which has been
  1818. * terminated.
  1819. * @param {String} reasonCondition the Jingle reason condition.
  1820. * @param {String|null} reasonText human readable reason text which may provide
  1821. * more details about why the call has been terminated.
  1822. */
  1823. JitsiConference.prototype.onCallEnded = function(
  1824. jingleSession,
  1825. reasonCondition,
  1826. reasonText) {
  1827. logger.info(
  1828. `Call ended: ${reasonCondition} - ${reasonText} P2P ?${
  1829. jingleSession.isP2P}`);
  1830. if (jingleSession === this.jvbJingleSession) {
  1831. this.wasStopped = true;
  1832. Statistics.sendAnalytics(
  1833. createJingleEvent(ACTION_JINGLE_TERMINATE, { p2p: false }));
  1834. // Stop the stats
  1835. if (this.statistics) {
  1836. this.statistics.stopRemoteStats(
  1837. this.jvbJingleSession.peerconnection);
  1838. logger.info('Stopping JVB CallStats');
  1839. this.statistics.stopCallStats(
  1840. this.jvbJingleSession.peerconnection);
  1841. }
  1842. // Current JVB JingleSession is no longer valid, so set it to null
  1843. this.jvbJingleSession = null;
  1844. // Let the RTC service do any cleanups
  1845. this.rtc.onCallEnded();
  1846. } else if (jingleSession === this.p2pJingleSession) {
  1847. // It's the responder who decides to enforce JVB mode, so that both
  1848. // initiator and responder are aware if it was intentional.
  1849. if (reasonCondition === 'decline' && reasonText === 'force JVB121') {
  1850. logger.info('In forced JVB 121 mode...');
  1851. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  1852. } else if (reasonCondition === 'connectivity-error'
  1853. && reasonText === 'ICE FAILED') {
  1854. // It can happen that the other peer detects ICE failed and
  1855. // terminates the session, before we get the event on our side.
  1856. // But we are able to parse the reason and mark it here.
  1857. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  1858. }
  1859. this._stopP2PSession();
  1860. } else {
  1861. logger.error(
  1862. 'Received onCallEnded for invalid session',
  1863. jingleSession.sid,
  1864. jingleSession.remoteJid,
  1865. reasonCondition,
  1866. reasonText);
  1867. }
  1868. };
  1869. /**
  1870. * Handles the suspend detected event. Leaves the room and fires suspended.
  1871. * @param {JingleSessionPC} jingleSession
  1872. */
  1873. JitsiConference.prototype.onSuspendDetected = function(jingleSession) {
  1874. if (!jingleSession.isP2P) {
  1875. this.leave();
  1876. this.eventEmitter.emit(JitsiConferenceEvents.SUSPEND_DETECTED);
  1877. }
  1878. };
  1879. JitsiConference.prototype.updateDTMFSupport = function() {
  1880. let somebodySupportsDTMF = false;
  1881. const participants = this.getParticipants();
  1882. // check if at least 1 participant supports DTMF
  1883. for (let i = 0; i < participants.length; i += 1) {
  1884. if (participants[i].supportsDTMF()) {
  1885. somebodySupportsDTMF = true;
  1886. break;
  1887. }
  1888. }
  1889. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  1890. this.somebodySupportsDTMF = somebodySupportsDTMF;
  1891. this.eventEmitter.emit(
  1892. JitsiConferenceEvents.DTMF_SUPPORT_CHANGED,
  1893. somebodySupportsDTMF);
  1894. }
  1895. };
  1896. /**
  1897. * Allows to check if there is at least one user in the conference
  1898. * that supports DTMF.
  1899. * @returns {boolean} true if somebody supports DTMF, false otherwise
  1900. */
  1901. JitsiConference.prototype.isDTMFSupported = function() {
  1902. return this.somebodySupportsDTMF;
  1903. };
  1904. /**
  1905. * Returns the local user's ID
  1906. * @return {string} local user's ID
  1907. */
  1908. JitsiConference.prototype.myUserId = function() {
  1909. return (
  1910. this.room && this.room.myroomjid
  1911. ? Strophe.getResourceFromJid(this.room.myroomjid)
  1912. : null);
  1913. };
  1914. JitsiConference.prototype.sendTones = function(tones, duration, pause) {
  1915. const peerConnection = this.getActivePeerConnection();
  1916. if (peerConnection) {
  1917. peerConnection.sendTones(tones, duration, pause);
  1918. } else {
  1919. logger.warn('cannot sendTones: no peer connection');
  1920. }
  1921. };
  1922. /**
  1923. * Starts recording the current conference.
  1924. *
  1925. * @param {Object} options - Configuration for the recording. See
  1926. * {@link Chatroom#startRecording} for more info.
  1927. * @returns {Promise} See {@link Chatroom#startRecording} for more info.
  1928. */
  1929. JitsiConference.prototype.startRecording = function(options) {
  1930. if (this.room) {
  1931. return this.recordingManager.startRecording(options);
  1932. }
  1933. return Promise.reject(new Error('The conference is not created yet!'));
  1934. };
  1935. /**
  1936. * Stop a recording session.
  1937. *
  1938. * @param {string} sessionID - The ID of the recording session that
  1939. * should be stopped.
  1940. * @returns {Promise} See {@link Chatroom#stopRecording} for more info.
  1941. */
  1942. JitsiConference.prototype.stopRecording = function(sessionID) {
  1943. if (this.room) {
  1944. return this.recordingManager.stopRecording(sessionID);
  1945. }
  1946. return Promise.reject(new Error('The conference is not created yet!'));
  1947. };
  1948. /**
  1949. * Returns true if the SIP calls are supported and false otherwise
  1950. */
  1951. JitsiConference.prototype.isSIPCallingSupported = function() {
  1952. if (this.room) {
  1953. return this.room.isSIPCallingSupported();
  1954. }
  1955. return false;
  1956. };
  1957. /**
  1958. * Dials a number.
  1959. * @param number the number
  1960. */
  1961. JitsiConference.prototype.dial = function(number) {
  1962. if (this.room) {
  1963. return this.room.dial(number);
  1964. }
  1965. return new Promise((resolve, reject) => {
  1966. reject(new Error('The conference is not created yet!'));
  1967. });
  1968. };
  1969. /**
  1970. * Hangup an existing call
  1971. */
  1972. JitsiConference.prototype.hangup = function() {
  1973. if (this.room) {
  1974. return this.room.hangup();
  1975. }
  1976. return new Promise((resolve, reject) => {
  1977. reject(new Error('The conference is not created yet!'));
  1978. });
  1979. };
  1980. /**
  1981. * Starts the transcription service.
  1982. */
  1983. JitsiConference.prototype.startTranscriber = function() {
  1984. return this.dial('jitsi_meet_transcribe');
  1985. };
  1986. /**
  1987. * Stops the transcription service.
  1988. */
  1989. JitsiConference.prototype.stopTranscriber = JitsiConference.prototype.hangup;
  1990. /**
  1991. * Returns the phone number for joining the conference.
  1992. */
  1993. JitsiConference.prototype.getPhoneNumber = function() {
  1994. if (this.room) {
  1995. return this.room.getPhoneNumber();
  1996. }
  1997. return null;
  1998. };
  1999. /**
  2000. * Returns the pin for joining the conference with phone.
  2001. */
  2002. JitsiConference.prototype.getPhonePin = function() {
  2003. if (this.room) {
  2004. return this.room.getPhonePin();
  2005. }
  2006. return null;
  2007. };
  2008. /**
  2009. * Returns the meeting unique ID if any.
  2010. *
  2011. * @returns {string|undefined}
  2012. */
  2013. JitsiConference.prototype.getMeetingUniqueId = function() {
  2014. if (this.room) {
  2015. return this.room.getMeetingId();
  2016. }
  2017. };
  2018. /**
  2019. * Will return P2P or JVB <tt>TraceablePeerConnection</tt> depending on
  2020. * which connection is currently active.
  2021. *
  2022. * @return {TraceablePeerConnection|null} null if there isn't any active
  2023. * <tt>TraceablePeerConnection</tt> currently available.
  2024. * @public (FIXME how to make package local ?)
  2025. */
  2026. JitsiConference.prototype.getActivePeerConnection = function() {
  2027. if (this.isP2PActive()) {
  2028. return this.p2pJingleSession.peerconnection;
  2029. }
  2030. return this.jvbJingleSession ? this.jvbJingleSession.peerconnection : null;
  2031. };
  2032. /**
  2033. * Returns the connection state for the current room. Its ice connection state
  2034. * for its session.
  2035. * NOTE that "completed" ICE state which can appear on the P2P connection will
  2036. * be converted to "connected".
  2037. * @return {string|null} ICE state name or <tt>null</tt> if there is no active
  2038. * peer connection at this time.
  2039. */
  2040. JitsiConference.prototype.getConnectionState = function() {
  2041. const peerConnection = this.getActivePeerConnection();
  2042. return peerConnection ? peerConnection.getConnectionState() : null;
  2043. };
  2044. /**
  2045. * Make all new participants mute their audio/video on join.
  2046. * @param policy {Object} object with 2 boolean properties for video and audio:
  2047. * @param {boolean} audio if audio should be muted.
  2048. * @param {boolean} video if video should be muted.
  2049. */
  2050. JitsiConference.prototype.setStartMutedPolicy = function(policy) {
  2051. if (!this.isModerator()) {
  2052. return;
  2053. }
  2054. this.startMutedPolicy = policy;
  2055. this.room.addOrReplaceInPresence('startmuted', {
  2056. attributes: {
  2057. audio: policy.audio,
  2058. video: policy.video,
  2059. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  2060. }
  2061. }) && this.room.sendPresence();
  2062. };
  2063. /**
  2064. * Returns current start muted policy
  2065. * @returns {Object} with 2 properties - audio and video.
  2066. */
  2067. JitsiConference.prototype.getStartMutedPolicy = function() {
  2068. return this.startMutedPolicy;
  2069. };
  2070. /**
  2071. * Check if audio is muted on join.
  2072. */
  2073. JitsiConference.prototype.isStartAudioMuted = function() {
  2074. return this.startAudioMuted;
  2075. };
  2076. /**
  2077. * Check if video is muted on join.
  2078. */
  2079. JitsiConference.prototype.isStartVideoMuted = function() {
  2080. return this.startVideoMuted;
  2081. };
  2082. /**
  2083. * Returns measured connectionTimes.
  2084. */
  2085. JitsiConference.prototype.getConnectionTimes = function() {
  2086. return this.room.connectionTimes;
  2087. };
  2088. /**
  2089. * Sets a property for the local participant.
  2090. */
  2091. JitsiConference.prototype.setLocalParticipantProperty = function(name, value) {
  2092. this.sendCommand(`jitsi_participant_${name}`, { value });
  2093. };
  2094. /**
  2095. * Removes a property for the local participant and sends the updated presence.
  2096. */
  2097. JitsiConference.prototype.removeLocalParticipantProperty = function(name) {
  2098. this.removeCommand(`jitsi_participant_${name}`);
  2099. this.room.sendPresence();
  2100. };
  2101. /**
  2102. * Gets a local participant property.
  2103. *
  2104. * @return value of the local participant property if the tagName exists in the
  2105. * list of properties, otherwise returns undefined.
  2106. */
  2107. JitsiConference.prototype.getLocalParticipantProperty = function(name) {
  2108. const property = this.room.presMap.nodes.find(prop =>
  2109. prop.tagName === `jitsi_participant_${name}`
  2110. );
  2111. return property ? property.value : undefined;
  2112. };
  2113. /**
  2114. * Sends the given feedback through CallStats if enabled.
  2115. *
  2116. * @param overallFeedback an integer between 1 and 5 indicating the
  2117. * user feedback
  2118. * @param detailedFeedback detailed feedback from the user. Not yet used
  2119. * @returns {Promise} Resolves if feedback is submitted successfully.
  2120. */
  2121. JitsiConference.prototype.sendFeedback = function(
  2122. overallFeedback,
  2123. detailedFeedback) {
  2124. return this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  2125. };
  2126. /**
  2127. * Returns true if the callstats integration is enabled, otherwise returns
  2128. * false.
  2129. *
  2130. * @returns true if the callstats integration is enabled, otherwise returns
  2131. * false.
  2132. */
  2133. JitsiConference.prototype.isCallstatsEnabled = function() {
  2134. return this.statistics.isCallstatsEnabled();
  2135. };
  2136. /**
  2137. * Finds the SSRC of a given track
  2138. *
  2139. * @param track
  2140. * @returns {number|undefined} the SSRC of the specificed track, otherwise undefined.
  2141. */
  2142. JitsiConference.prototype.getSsrcByTrack = function(track) {
  2143. return track.isLocal() ? this.getActivePeerConnection()?.getLocalSSRC(track) : track.getSSRC();
  2144. };
  2145. /**
  2146. * Handles track attached to container (Calls associateStreamWithVideoTag method
  2147. * from statistics module)
  2148. * @param {JitsiLocalTrack|JitsiRemoteTrack} track the track
  2149. * @param container the container
  2150. */
  2151. JitsiConference.prototype._onTrackAttach = function(track, container) {
  2152. const isLocal = track.isLocal();
  2153. let ssrc = null;
  2154. const isP2P = track.isP2P;
  2155. const remoteUserId = isP2P ? track.getParticipantId() : 'jitsi';
  2156. const peerConnection
  2157. = isP2P
  2158. ? this.p2pJingleSession && this.p2pJingleSession.peerconnection
  2159. : this.jvbJingleSession && this.jvbJingleSession.peerconnection;
  2160. if (isLocal) {
  2161. // Local tracks have SSRC stored on per peer connection basis.
  2162. if (peerConnection) {
  2163. ssrc = peerConnection.getLocalSSRC(track);
  2164. }
  2165. } else {
  2166. ssrc = track.getSSRC();
  2167. }
  2168. if (!container.id || !ssrc || !peerConnection) {
  2169. return;
  2170. }
  2171. this.statistics.associateStreamWithVideoTag(
  2172. peerConnection,
  2173. ssrc,
  2174. isLocal,
  2175. remoteUserId,
  2176. track.getUsageLabel(),
  2177. container.id);
  2178. };
  2179. /**
  2180. * Logs an "application log" message.
  2181. * @param message {string} The message to log. Note that while this can be a
  2182. * generic string, the convention used by lib-jitsi-meet and jitsi-meet is to
  2183. * log valid JSON strings, with an "id" field used for distinguishing between
  2184. * message types. E.g.: {id: "recorder_status", status: "off"}
  2185. */
  2186. JitsiConference.prototype.sendApplicationLog = function(message) {
  2187. Statistics.sendLog(message);
  2188. };
  2189. /**
  2190. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  2191. * focus.
  2192. * @param mucJid the full MUC address of the user to be checked.
  2193. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus,
  2194. * <tt>false</tt> when is not. <tt>null</tt> if we're not in the MUC anymore and
  2195. * are unable to figure out the status or if given <tt>mucJid</tt> is invalid.
  2196. */
  2197. JitsiConference.prototype._isFocus = function(mucJid) {
  2198. return this.room ? this.room.isFocus(mucJid) : null;
  2199. };
  2200. /**
  2201. * Fires CONFERENCE_FAILED event with INCOMPATIBLE_SERVER_VERSIONS parameter
  2202. */
  2203. JitsiConference.prototype._fireIncompatibleVersionsEvent = function() {
  2204. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED,
  2205. JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS);
  2206. };
  2207. /**
  2208. * Sends a message via the data channel.
  2209. * @param to {string} the id of the endpoint that should receive the message.
  2210. * If "" the message will be sent to all participants.
  2211. * @param payload {object} the payload of the message.
  2212. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2213. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2214. */
  2215. JitsiConference.prototype.sendEndpointMessage = function(to, payload) {
  2216. this.rtc.sendChannelMessage(to, payload);
  2217. };
  2218. /**
  2219. * Sends a broadcast message via the data channel.
  2220. * @param payload {object} the payload of the message.
  2221. * @throws NetworkError or InvalidStateError or Error if the operation fails.
  2222. * @deprecated Use 'sendMessage' instead. TODO: this should be private.
  2223. */
  2224. JitsiConference.prototype.broadcastEndpointMessage = function(payload) {
  2225. this.sendEndpointMessage('', payload);
  2226. };
  2227. /**
  2228. * Sends a message to a given endpoint (if 'to' is a non-empty string), or
  2229. * broadcasts it to all endpoints in the conference.
  2230. * @param {string} to The ID of the endpoint/participant which is to receive
  2231. * the message, or '' to broadcast the message to all endpoints in the
  2232. * conference.
  2233. * @param {string|object} message the message to send. If this is of type
  2234. * 'string' it will be sent as a chat message. If it is of type 'object', it
  2235. * will be encapsulated in a format recognized by jitsi-meet and converted to
  2236. * JSON before being sent.
  2237. * @param {boolean} sendThroughVideobridge Whether to send the message through
  2238. * jitsi-videobridge (via the COLIBRI data channel or web socket), or through
  2239. * the XMPP MUC. Currently only objects can be sent through jitsi-videobridge.
  2240. */
  2241. JitsiConference.prototype.sendMessage = function(
  2242. message,
  2243. to = '',
  2244. sendThroughVideobridge = false) {
  2245. const messageType = typeof message;
  2246. // Through videobridge we support only objects. Through XMPP we support
  2247. // objects (encapsulated in a specific JSON format) and strings (i.e.
  2248. // regular chat messages).
  2249. if (messageType !== 'object'
  2250. && (sendThroughVideobridge || messageType !== 'string')) {
  2251. logger.error(`Can not send a message of type ${messageType}`);
  2252. return;
  2253. }
  2254. if (sendThroughVideobridge) {
  2255. this.sendEndpointMessage(to, message);
  2256. } else {
  2257. let messageToSend = message;
  2258. // Name of packet extension of message stanza to send the required
  2259. // message in.
  2260. let elementName = 'body';
  2261. if (messageType === 'object') {
  2262. elementName = 'json-message';
  2263. // Mark as valid JSON message if not already
  2264. if (!messageToSend.hasOwnProperty(JITSI_MEET_MUC_TYPE)) {
  2265. messageToSend[JITSI_MEET_MUC_TYPE] = '';
  2266. }
  2267. try {
  2268. messageToSend = JSON.stringify(messageToSend);
  2269. } catch (e) {
  2270. logger.error('Can not send a message, stringify failed: ', e);
  2271. return;
  2272. }
  2273. }
  2274. if (to) {
  2275. this.sendPrivateTextMessage(to, messageToSend, elementName);
  2276. } else {
  2277. // Broadcast
  2278. this.sendTextMessage(messageToSend, elementName);
  2279. }
  2280. }
  2281. };
  2282. JitsiConference.prototype.isConnectionInterrupted = function() {
  2283. return this.isP2PActive()
  2284. ? this.isP2PConnectionInterrupted : this.isJvbConnectionInterrupted;
  2285. };
  2286. /**
  2287. * Handles {@link XMPPEvents.CONNECTION_RESTARTED} event. This happens when the bridge goes down
  2288. * and Jicofo moves conferences away to a different bridge.
  2289. * @param {JingleSessionPC} session
  2290. * @private
  2291. */
  2292. JitsiConference.prototype._onConferenceRestarted = function(session) {
  2293. if (!session.isP2P && this.options.config.enableForcedReload) {
  2294. this.restartInProgress = true;
  2295. this.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_RESTARTED);
  2296. }
  2297. };
  2298. /**
  2299. * Handles {@link XMPPEvents.CONNECTION_INTERRUPTED}
  2300. * @param {JingleSessionPC} session
  2301. * @private
  2302. */
  2303. JitsiConference.prototype._onIceConnectionInterrupted = function(session) {
  2304. if (session.isP2P) {
  2305. this.isP2PConnectionInterrupted = true;
  2306. } else {
  2307. this.isJvbConnectionInterrupted = true;
  2308. }
  2309. if (session.isP2P === this.isP2PActive()) {
  2310. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  2311. }
  2312. };
  2313. /**
  2314. * Handles {@link XMPPEvents.CONNECTION_ICE_FAILED}
  2315. * @param {JingleSessionPC} session
  2316. * @private
  2317. */
  2318. JitsiConference.prototype._onIceConnectionFailed = function(session) {
  2319. // We do nothing for the JVB connection, because it's up to the Jicofo to
  2320. // eventually come up with the new offer (at least for the time being).
  2321. if (session.isP2P) {
  2322. // Add p2pFailed property to analytics to distinguish, between "good"
  2323. // and "bad" connection
  2324. Statistics.analytics.addPermanentProperties({ p2pFailed: true });
  2325. if (this.p2pJingleSession) {
  2326. Statistics.sendAnalyticsAndLog(
  2327. createP2PEvent(
  2328. ACTION_P2P_FAILED,
  2329. {
  2330. initiator: this.p2pJingleSession.isInitiator
  2331. }));
  2332. }
  2333. this._stopP2PSession('connectivity-error', 'ICE FAILED');
  2334. } else if (session && this.jvbJingleSession === session) {
  2335. this._delayedIceFailed = new IceFailedHandling(this);
  2336. this._delayedIceFailed.start(session);
  2337. }
  2338. };
  2339. /**
  2340. * Handles {@link XMPPEvents.CONNECTION_RESTORED}
  2341. * @param {JingleSessionPC} session
  2342. * @private
  2343. */
  2344. JitsiConference.prototype._onIceConnectionRestored = function(session) {
  2345. if (session.isP2P) {
  2346. this.isP2PConnectionInterrupted = false;
  2347. } else {
  2348. this.isJvbConnectionInterrupted = false;
  2349. this._delayedIceFailed && this._delayedIceFailed.cancel();
  2350. }
  2351. if (session.isP2P === this.isP2PActive()) {
  2352. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  2353. }
  2354. };
  2355. /**
  2356. * Accept incoming P2P Jingle call.
  2357. * @param {JingleSessionPC} jingleSession the session instance
  2358. * @param {jQuery} jingleOffer a jQuery selector pointing to 'jingle' IQ element
  2359. * @private
  2360. */
  2361. JitsiConference.prototype._acceptP2PIncomingCall = function(
  2362. jingleSession,
  2363. jingleOffer) {
  2364. this.isP2PConnectionInterrupted = false;
  2365. // Accept the offer
  2366. this.p2pJingleSession = jingleSession;
  2367. this._sendConferenceJoinAnalyticsEvent();
  2368. this.p2pJingleSession.initialize(
  2369. this.room,
  2370. this.rtc, {
  2371. ...this.options.config,
  2372. enableInsertableStreams: this._isE2EEEnabled()
  2373. });
  2374. logger.info('Starting CallStats for P2P connection...');
  2375. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2376. const participant = this.participants[remoteID];
  2377. if (participant) {
  2378. remoteID = participant.getStatsID() || remoteID;
  2379. }
  2380. this.statistics.startCallStats(
  2381. this.p2pJingleSession.peerconnection,
  2382. remoteID);
  2383. const localTracks = this._getInitialLocalTracks();
  2384. this.p2pJingleSession.acceptOffer(
  2385. jingleOffer,
  2386. () => {
  2387. logger.debug('Got RESULT for P2P "session-accept"');
  2388. this.eventEmitter.emit(
  2389. JitsiConferenceEvents._MEDIA_SESSION_STARTED,
  2390. this.p2pJingleSession);
  2391. },
  2392. error => {
  2393. logger.error(
  2394. 'Failed to accept incoming P2P Jingle session', error);
  2395. },
  2396. localTracks);
  2397. };
  2398. /**
  2399. * Adds remote tracks to the conference associated with the JVB session.
  2400. * @private
  2401. */
  2402. JitsiConference.prototype._addRemoteJVBTracks = function() {
  2403. this._addRemoteTracks(
  2404. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2405. };
  2406. /**
  2407. * Adds remote tracks to the conference associated with the P2P session.
  2408. * @private
  2409. */
  2410. JitsiConference.prototype._addRemoteP2PTracks = function() {
  2411. this._addRemoteTracks(
  2412. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2413. };
  2414. /**
  2415. * Generates fake "remote track added" events for given Jingle session.
  2416. * @param {string} logName the session's nickname which will appear in log
  2417. * messages.
  2418. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be added
  2419. * @private
  2420. */
  2421. JitsiConference.prototype._addRemoteTracks = function(logName, remoteTracks) {
  2422. for (const track of remoteTracks) {
  2423. logger.info(`Adding remote ${logName} track: ${track}`);
  2424. this.onRemoteTrackAdded(track);
  2425. }
  2426. };
  2427. /**
  2428. * Called when {@link XMPPEvents.CONNECTION_ESTABLISHED} event is
  2429. * triggered for a {@link JingleSessionPC}. Switches the conference to use
  2430. * the P2P connection if the event comes from the P2P session.
  2431. * @param {JingleSessionPC} jingleSession the session instance.
  2432. * @private
  2433. */
  2434. JitsiConference.prototype._onIceConnectionEstablished = function(
  2435. jingleSession) {
  2436. if (this.p2pJingleSession !== null) {
  2437. // store the establishment time of the p2p session as a field of the
  2438. // JitsiConference because the p2pJingleSession might get disposed (thus
  2439. // the value is lost).
  2440. this.p2pEstablishmentDuration
  2441. = this.p2pJingleSession.establishmentDuration;
  2442. }
  2443. if (this.jvbJingleSession !== null) {
  2444. this.jvbEstablishmentDuration
  2445. = this.jvbJingleSession.establishmentDuration;
  2446. }
  2447. let done = false;
  2448. const forceJVB121Ratio = this.options.config.forceJVB121Ratio;
  2449. // We don't care about the JVB case, there's nothing to be done
  2450. if (!jingleSession.isP2P) {
  2451. done = true;
  2452. } else if (this.p2pJingleSession !== jingleSession) {
  2453. logger.error('CONNECTION_ESTABLISHED - wrong P2P session instance ?!');
  2454. done = true;
  2455. } else if (!jingleSession.isInitiator
  2456. && typeof forceJVB121Ratio === 'number'
  2457. && Math.random() < forceJVB121Ratio) {
  2458. logger.info(`Forcing JVB 121 mode (ratio=${forceJVB121Ratio})...`);
  2459. Statistics.analytics.addPermanentProperties({ forceJvb121: true });
  2460. this._stopP2PSession('decline', 'force JVB121');
  2461. done = true;
  2462. }
  2463. if (!isNaN(this.p2pEstablishmentDuration)
  2464. && !isNaN(this.jvbEstablishmentDuration)) {
  2465. const establishmentDurationDiff
  2466. = this.p2pEstablishmentDuration - this.jvbEstablishmentDuration;
  2467. Statistics.sendAnalytics(
  2468. ICE_ESTABLISHMENT_DURATION_DIFF,
  2469. { value: establishmentDurationDiff });
  2470. }
  2471. if (jingleSession.isP2P === this.isP2PActive()) {
  2472. this.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_ESTABLISHED);
  2473. }
  2474. if (done) {
  2475. return;
  2476. }
  2477. // Update P2P status and emit events
  2478. this._setP2PStatus(true);
  2479. // Remove remote tracks
  2480. if (this.jvbJingleSession) {
  2481. this._removeRemoteJVBTracks();
  2482. } else {
  2483. logger.info('Not removing remote JVB tracks - no session yet');
  2484. }
  2485. this._addRemoteP2PTracks();
  2486. // Stop media transfer over the JVB connection
  2487. if (this.jvbJingleSession) {
  2488. this._suspendMediaTransferForJvbConnection();
  2489. }
  2490. logger.info('Starting remote stats with p2p connection');
  2491. this.statistics.startRemoteStats(this.p2pJingleSession.peerconnection);
  2492. Statistics.sendAnalyticsAndLog(
  2493. createP2PEvent(
  2494. ACTION_P2P_ESTABLISHED,
  2495. {
  2496. initiator: this.p2pJingleSession.isInitiator
  2497. }));
  2498. };
  2499. /**
  2500. * Called when the chat room reads a new list of properties from jicofo's
  2501. * presence. The properties may have changed, but they don't have to.
  2502. *
  2503. * @param {Object} properties - The properties keyed by the property name
  2504. * ('key').
  2505. * @private
  2506. */
  2507. JitsiConference.prototype._updateProperties = function(properties = {}) {
  2508. const changed = !isEqual(properties, this.properties);
  2509. this.properties = properties;
  2510. if (changed) {
  2511. this.eventEmitter.emit(
  2512. JitsiConferenceEvents.PROPERTIES_CHANGED,
  2513. this.properties);
  2514. // Some of the properties need to be added to analytics events.
  2515. const analyticsKeys = [
  2516. // The number of jitsi-videobridge instances currently used for the
  2517. // conference.
  2518. 'bridge-count',
  2519. // The conference creation time (set by jicofo).
  2520. 'created-ms'
  2521. ];
  2522. analyticsKeys.forEach(key => {
  2523. if (properties[key] !== undefined) {
  2524. Statistics.analytics.addPermanentProperties({
  2525. [key.replace('-', '_')]: properties[key]
  2526. });
  2527. }
  2528. });
  2529. }
  2530. };
  2531. /**
  2532. * Gets a conference property with a given key.
  2533. *
  2534. * @param {string} key - The key.
  2535. * @returns {*} The value
  2536. */
  2537. JitsiConference.prototype.getProperty = function(key) {
  2538. return this.properties[key];
  2539. };
  2540. /**
  2541. * Clears the deferred start P2P task if it has been scheduled.
  2542. * @private
  2543. */
  2544. JitsiConference.prototype._maybeClearDeferredStartP2P = function() {
  2545. if (this.deferredStartP2PTask) {
  2546. logger.info('Cleared deferred start P2P task');
  2547. clearTimeout(this.deferredStartP2PTask);
  2548. this.deferredStartP2PTask = null;
  2549. }
  2550. };
  2551. /**
  2552. * Removes from the conference remote tracks associated with the JVB
  2553. * connection.
  2554. * @private
  2555. */
  2556. JitsiConference.prototype._removeRemoteJVBTracks = function() {
  2557. this._removeRemoteTracks(
  2558. 'JVB', this.jvbJingleSession.peerconnection.getRemoteTracks());
  2559. };
  2560. /**
  2561. * Removes from the conference remote tracks associated with the P2P
  2562. * connection.
  2563. * @private
  2564. */
  2565. JitsiConference.prototype._removeRemoteP2PTracks = function() {
  2566. this._removeRemoteTracks(
  2567. 'P2P', this.p2pJingleSession.peerconnection.getRemoteTracks());
  2568. };
  2569. /**
  2570. * Generates fake "remote track removed" events for given Jingle session.
  2571. * @param {string} sessionNickname the session's nickname which will appear in
  2572. * log messages.
  2573. * @param {Array<JitsiRemoteTrack>} remoteTracks the tracks that will be removed
  2574. * @private
  2575. */
  2576. JitsiConference.prototype._removeRemoteTracks = function(
  2577. sessionNickname,
  2578. remoteTracks) {
  2579. for (const track of remoteTracks) {
  2580. logger.info(`Removing remote ${sessionNickname} track: ${track}`);
  2581. this.onRemoteTrackRemoved(track);
  2582. }
  2583. };
  2584. /**
  2585. * Resumes media transfer over the JVB connection.
  2586. * @private
  2587. */
  2588. JitsiConference.prototype._resumeMediaTransferForJvbConnection = function() {
  2589. logger.info('Resuming media transfer over the JVB connection...');
  2590. this.jvbJingleSession.setMediaTransferActive(true, true).then(
  2591. () => {
  2592. logger.info('Resumed media transfer over the JVB connection!');
  2593. },
  2594. error => {
  2595. logger.error(
  2596. 'Failed to resume media transfer over the JVB connection:',
  2597. error);
  2598. });
  2599. };
  2600. /**
  2601. * Sets new P2P status and updates some events/states hijacked from
  2602. * the <tt>JitsiConference</tt>.
  2603. * @param {boolean} newStatus the new P2P status value, <tt>true</tt> means that
  2604. * P2P is now in use, <tt>false</tt> means that the JVB connection is now in use
  2605. * @private
  2606. */
  2607. JitsiConference.prototype._setP2PStatus = function(newStatus) {
  2608. if (this.p2p === newStatus) {
  2609. logger.debug(`Called _setP2PStatus with the same status: ${newStatus}`);
  2610. return;
  2611. }
  2612. this.p2p = newStatus;
  2613. if (newStatus) {
  2614. logger.info('Peer to peer connection established!');
  2615. // When we end up in a valid P2P session need to reset the properties
  2616. // in case they have persisted, after session with another peer.
  2617. Statistics.analytics.addPermanentProperties({
  2618. p2pFailed: false,
  2619. forceJvb121: false
  2620. });
  2621. // Sync up video transfer active in case p2pJingleSession not existed
  2622. // when the lastN value was being adjusted.
  2623. const isVideoActive = this.getLastN() !== 0;
  2624. this.p2pJingleSession
  2625. .setMediaTransferActive(true, isVideoActive)
  2626. .catch(error => {
  2627. logger.error(
  2628. 'Failed to sync up P2P video transfer status'
  2629. + `(${isVideoActive})`, error);
  2630. });
  2631. } else {
  2632. logger.info('Peer to peer connection closed!');
  2633. }
  2634. // Put the JVB connection on hold/resume
  2635. if (this.jvbJingleSession) {
  2636. this.statistics.sendConnectionResumeOrHoldEvent(
  2637. this.jvbJingleSession.peerconnection, !newStatus);
  2638. }
  2639. // Clear dtmfManager, so that it can be recreated with new connection
  2640. this.dtmfManager = null;
  2641. // Update P2P status
  2642. this.eventEmitter.emit(
  2643. JitsiConferenceEvents.P2P_STATUS,
  2644. this,
  2645. this.p2p);
  2646. this.eventEmitter.emit(
  2647. JitsiConferenceEvents._MEDIA_SESSION_ACTIVE_CHANGED,
  2648. this._getActiveMediaSession());
  2649. // Refresh connection interrupted/restored
  2650. this.eventEmitter.emit(
  2651. this.isConnectionInterrupted()
  2652. ? JitsiConferenceEvents.CONNECTION_INTERRUPTED
  2653. : JitsiConferenceEvents.CONNECTION_RESTORED);
  2654. };
  2655. /**
  2656. * Starts new P2P session.
  2657. * @param {string} remoteJid the JID of the remote participant
  2658. * @private
  2659. */
  2660. JitsiConference.prototype._startP2PSession = function(remoteJid) {
  2661. this._maybeClearDeferredStartP2P();
  2662. if (this.p2pJingleSession) {
  2663. logger.error('P2P session already started!');
  2664. return;
  2665. }
  2666. this.isP2PConnectionInterrupted = false;
  2667. this.p2pJingleSession
  2668. = this.xmpp.connection.jingle.newP2PJingleSession(
  2669. this.room.myroomjid,
  2670. remoteJid);
  2671. logger.info(
  2672. 'Created new P2P JingleSession', this.room.myroomjid, remoteJid);
  2673. this._sendConferenceJoinAnalyticsEvent();
  2674. this.p2pJingleSession.initialize(
  2675. this.room,
  2676. this.rtc, {
  2677. ...this.options.config,
  2678. enableInsertableStreams: this._isE2EEEnabled()
  2679. });
  2680. logger.info('Starting CallStats for P2P connection...');
  2681. let remoteID = Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid);
  2682. const participant = this.participants[remoteID];
  2683. if (participant) {
  2684. remoteID = participant.getStatsID() || remoteID;
  2685. }
  2686. this.statistics.startCallStats(
  2687. this.p2pJingleSession.peerconnection,
  2688. remoteID);
  2689. const localTracks = this._getInitialLocalTracks();
  2690. this.p2pJingleSession.invite(localTracks);
  2691. };
  2692. /**
  2693. * Suspends media transfer over the JVB connection.
  2694. * @private
  2695. */
  2696. JitsiConference.prototype._suspendMediaTransferForJvbConnection = function() {
  2697. logger.info('Suspending media transfer over the JVB connection...');
  2698. this.jvbJingleSession.setMediaTransferActive(false, false).then(
  2699. () => {
  2700. logger.info('Suspended media transfer over the JVB connection !');
  2701. },
  2702. error => {
  2703. logger.error(
  2704. 'Failed to suspend media transfer over the JVB connection:',
  2705. error);
  2706. });
  2707. };
  2708. /**
  2709. * Method when called will decide whether it's the time to start or stop
  2710. * the P2P session.
  2711. * @param {boolean} userLeftEvent if <tt>true</tt> it means that the call
  2712. * originates from the user left event.
  2713. * @private
  2714. */
  2715. JitsiConference.prototype._maybeStartOrStopP2P = function(userLeftEvent) {
  2716. if (!browser.supportsP2P()
  2717. || !this.isP2PEnabled()
  2718. || this.isP2PTestModeEnabled()) {
  2719. logger.info('Auto P2P disabled');
  2720. return;
  2721. }
  2722. const peers = this.getParticipants();
  2723. const peerCount = peers.length;
  2724. // FIXME 1 peer and it must *support* P2P switching
  2725. const shouldBeInP2P = this._shouldBeInP2PMode();
  2726. // Clear deferred "start P2P" task
  2727. if (!shouldBeInP2P && this.deferredStartP2PTask) {
  2728. this._maybeClearDeferredStartP2P();
  2729. }
  2730. // Start peer to peer session
  2731. if (!this.p2pJingleSession && shouldBeInP2P) {
  2732. const peer = peerCount && peers[0];
  2733. const myId = this.myUserId();
  2734. const peersId = peer.getId();
  2735. if (myId > peersId) {
  2736. logger.debug(
  2737. 'I\'m the bigger peersId - '
  2738. + 'the other peer should start P2P', myId, peersId);
  2739. return;
  2740. } else if (myId === peersId) {
  2741. logger.error('The same IDs ? ', myId, peersId);
  2742. return;
  2743. }
  2744. const jid = peer.getJid();
  2745. if (userLeftEvent) {
  2746. if (this.deferredStartP2PTask) {
  2747. logger.error('Deferred start P2P task\'s been set already!');
  2748. return;
  2749. }
  2750. logger.info(
  2751. `Will start P2P with: ${jid} after ${
  2752. this.backToP2PDelay} seconds...`);
  2753. this.deferredStartP2PTask = setTimeout(
  2754. this._startP2PSession.bind(this, jid),
  2755. this.backToP2PDelay * 1000);
  2756. } else {
  2757. logger.info(`Will start P2P with: ${jid}`);
  2758. this._startP2PSession(jid);
  2759. }
  2760. } else if (this.p2pJingleSession && !shouldBeInP2P) {
  2761. logger.info(`Will stop P2P with: ${this.p2pJingleSession.remoteJid}`);
  2762. // Log that there will be a switch back to the JVB connection
  2763. if (this.p2pJingleSession.isInitiator && peerCount > 1) {
  2764. Statistics.sendAnalyticsAndLog(
  2765. createP2PEvent(ACTION_P2P_SWITCH_TO_JVB));
  2766. }
  2767. this._stopP2PSession();
  2768. }
  2769. };
  2770. /**
  2771. * Tells whether or not this conference should be currently in the P2P mode.
  2772. *
  2773. * @private
  2774. * @returns {boolean}
  2775. */
  2776. JitsiConference.prototype._shouldBeInP2PMode = function() {
  2777. const peers = this.getParticipants();
  2778. const peerCount = peers.length;
  2779. const hasBotPeer = peers.find(p => p.getBotType() === 'poltergeist' || p.hasFeature(FEATURE_JIGASI)) !== undefined;
  2780. const shouldBeInP2P = peerCount === 1 && !hasBotPeer;
  2781. logger.debug(`P2P? peerCount: ${peerCount}, hasBotPeer: ${hasBotPeer} => ${shouldBeInP2P}`);
  2782. return shouldBeInP2P;
  2783. };
  2784. /**
  2785. * Stops the current P2P session.
  2786. * @param {string} [reason="success"] one of the Jingle "reason" element
  2787. * names as defined by https://xmpp.org/extensions/xep-0166.html#def-reason
  2788. * @param {string} [reasonDescription="Turing off P2P session"] text
  2789. * description that will be included in the session terminate message
  2790. * @private
  2791. */
  2792. JitsiConference.prototype._stopP2PSession = function(
  2793. reason,
  2794. reasonDescription) {
  2795. if (!this.p2pJingleSession) {
  2796. logger.error('No P2P session to be stopped!');
  2797. return;
  2798. }
  2799. const wasP2PEstablished = this.isP2PActive();
  2800. // Swap remote tracks, but only if the P2P has been fully established
  2801. if (wasP2PEstablished) {
  2802. if (this.jvbJingleSession) {
  2803. this._resumeMediaTransferForJvbConnection();
  2804. }
  2805. // Remove remote P2P tracks
  2806. this._removeRemoteP2PTracks();
  2807. }
  2808. // Stop P2P stats
  2809. logger.info('Stopping remote stats for P2P connection');
  2810. this.statistics.stopRemoteStats(this.p2pJingleSession.peerconnection);
  2811. logger.info('Stopping CallStats for P2P connection');
  2812. this.statistics.stopCallStats(this.p2pJingleSession.peerconnection);
  2813. this.p2pJingleSession.terminate(
  2814. () => {
  2815. logger.info('P2P session terminate RESULT');
  2816. },
  2817. error => {
  2818. // Because both initiator and responder are simultaneously
  2819. // terminating their JingleSessions in case of the 'to JVB switch'
  2820. // when 3rd participant joins, both will dispose their sessions and
  2821. // reply with 'item-not-found' (see strophe.jingle.js). We don't
  2822. // want to log this as an error since it's expected behaviour.
  2823. //
  2824. // We want them both to terminate, because in case of initiator's
  2825. // crash the responder would stay in P2P mode until ICE fails which
  2826. // could take up to 20 seconds.
  2827. //
  2828. // NOTE lack of 'reason' is considered as graceful session terminate
  2829. // where both initiator and responder terminate their sessions
  2830. // simultaneously.
  2831. if (reason) {
  2832. logger.error(
  2833. 'An error occurred while trying to terminate'
  2834. + ' P2P Jingle session', error);
  2835. }
  2836. }, {
  2837. reason: reason ? reason : 'success',
  2838. reasonDescription: reasonDescription
  2839. ? reasonDescription : 'Turing off P2P session',
  2840. sendSessionTerminate: this.room
  2841. && this.getParticipantById(
  2842. Strophe.getResourceFromJid(this.p2pJingleSession.remoteJid))
  2843. });
  2844. this.p2pJingleSession = null;
  2845. // Update P2P status and other affected events/states
  2846. this._setP2PStatus(false);
  2847. if (wasP2PEstablished) {
  2848. // Add back remote JVB tracks
  2849. if (this.jvbJingleSession) {
  2850. this._addRemoteJVBTracks();
  2851. } else {
  2852. logger.info('Not adding remote JVB tracks - no session yet');
  2853. }
  2854. }
  2855. };
  2856. /**
  2857. * Checks whether or not the conference is currently in the peer to peer mode.
  2858. * Being in peer to peer mode means that the direct connection has been
  2859. * established and the P2P connection is being used for media transmission.
  2860. * @return {boolean} <tt>true</tt> if in P2P mode or <tt>false</tt> otherwise.
  2861. */
  2862. JitsiConference.prototype.isP2PActive = function() {
  2863. return this.p2p;
  2864. };
  2865. /**
  2866. * Returns the current ICE state of the P2P connection.
  2867. * NOTE: method is used by the jitsi-meet-torture tests.
  2868. * @return {string|null} an ICE state or <tt>null</tt> if there's currently
  2869. * no P2P connection.
  2870. */
  2871. JitsiConference.prototype.getP2PConnectionState = function() {
  2872. if (this.isP2PActive()) {
  2873. return this.p2pJingleSession.peerconnection.getConnectionState();
  2874. }
  2875. return null;
  2876. };
  2877. /**
  2878. * Manually starts new P2P session (should be used only in the tests).
  2879. */
  2880. JitsiConference.prototype.startP2PSession = function() {
  2881. const peers = this.getParticipants();
  2882. // Start peer to peer session
  2883. if (peers.length === 1) {
  2884. const peerJid = peers[0].getJid();
  2885. this._startP2PSession(peerJid);
  2886. } else {
  2887. throw new Error(
  2888. 'There must be exactly 1 participant to start the P2P session !');
  2889. }
  2890. };
  2891. /**
  2892. * Manually stops the current P2P session (should be used only in the tests)
  2893. */
  2894. JitsiConference.prototype.stopP2PSession = function() {
  2895. this._stopP2PSession();
  2896. };
  2897. /**
  2898. * Get a summary of how long current participants have been the dominant speaker
  2899. * @returns {object}
  2900. */
  2901. JitsiConference.prototype.getSpeakerStats = function() {
  2902. return this.speakerStatsCollector.getStats();
  2903. };
  2904. /**
  2905. * Sets the maximum video size the local participant should receive from remote
  2906. * participants.
  2907. *
  2908. * @param {number} maxFrameHeight - the maximum frame height, in pixels,
  2909. * this receiver is willing to receive.
  2910. * @returns {void}
  2911. */
  2912. JitsiConference.prototype.setReceiverVideoConstraint = function(maxFrameHeight) {
  2913. this.receiveVideoController.setPreferredReceiveMaxFrameHeight(maxFrameHeight);
  2914. };
  2915. /**
  2916. * Sets the maximum video size the local participant should send to remote
  2917. * participants.
  2918. * @param {number} maxFrameHeight - The user preferred max frame height.
  2919. * @returns {Promise} promise that will be resolved when the operation is
  2920. * successful and rejected otherwise.
  2921. */
  2922. JitsiConference.prototype.setSenderVideoConstraint = function(maxFrameHeight) {
  2923. return this.sendVideoController.setPreferredSendMaxFrameHeight(maxFrameHeight);
  2924. };
  2925. /**
  2926. * Creates a video SIP GW session and returns it if service is enabled. Before
  2927. * creating a session one need to check whether video SIP GW service is
  2928. * available in the system {@link JitsiConference.isVideoSIPGWAvailable}. Even
  2929. * if there are available nodes to serve this request, after creating the
  2930. * session those nodes can be taken and the request about using the
  2931. * created session can fail.
  2932. *
  2933. * @param {string} sipAddress - The sip address to be used.
  2934. * @param {string} displayName - The display name to be used for this session.
  2935. * @returns {JitsiVideoSIPGWSession|Error} Returns null if conference is not
  2936. * initialised and there is no room.
  2937. */
  2938. JitsiConference.prototype.createVideoSIPGWSession
  2939. = function(sipAddress, displayName) {
  2940. if (!this.room) {
  2941. return new Error(VideoSIPGWConstants.ERROR_NO_CONNECTION);
  2942. }
  2943. return this.videoSIPGWHandler
  2944. .createVideoSIPGWSession(sipAddress, displayName);
  2945. };
  2946. /**
  2947. * Sends a conference.join analytics event.
  2948. *
  2949. * @returns {void}
  2950. */
  2951. JitsiConference.prototype._sendConferenceJoinAnalyticsEvent = function() {
  2952. const meetingId = this.getMeetingUniqueId();
  2953. if (this._conferenceJoinAnalyticsEventSent || !meetingId || this.getActivePeerConnection() === null) {
  2954. return;
  2955. }
  2956. Statistics.sendAnalytics(createConferenceEvent('joined', {
  2957. meetingId,
  2958. participantId: `${meetingId}.${this._statsCurrentId}`
  2959. }));
  2960. this._conferenceJoinAnalyticsEventSent = Date.now();
  2961. };
  2962. /**
  2963. * Sends conference.left analytics event.
  2964. * @private
  2965. */
  2966. JitsiConference.prototype._sendConferenceLeftAnalyticsEvent = function() {
  2967. const meetingId = this.getMeetingUniqueId();
  2968. if (!meetingId || !this._conferenceJoinAnalyticsEventSent) {
  2969. return;
  2970. }
  2971. Statistics.sendAnalytics(createConferenceEvent('left', {
  2972. meetingId,
  2973. participantId: `${meetingId}.${this._statsCurrentId}`,
  2974. stats: {
  2975. duration: Math.floor((Date.now() - this._conferenceJoinAnalyticsEventSent) / 1000),
  2976. perf: this.getPerformanceStats()
  2977. }
  2978. }));
  2979. };
  2980. /**
  2981. * Restarts all active media sessions.
  2982. *
  2983. * @returns {void}
  2984. */
  2985. JitsiConference.prototype._restartMediaSessions = function() {
  2986. if (this.p2pJingleSession) {
  2987. this.stopP2PSession();
  2988. }
  2989. if (this.jvbJingleSession) {
  2990. this.jvbJingleSession.terminate(
  2991. null /* success callback => we don't care */,
  2992. error => {
  2993. logger.warn('An error occurred while trying to terminate the JVB session', error);
  2994. }, {
  2995. reason: 'success',
  2996. reasonDescription: 'restart required',
  2997. requestRestart: true,
  2998. sendSessionTerminate: true
  2999. });
  3000. }
  3001. this._maybeStartOrStopP2P(false);
  3002. };
  3003. /**
  3004. * Returns whether End-To-End encryption is enabled.
  3005. *
  3006. * @returns {boolean}
  3007. */
  3008. JitsiConference.prototype._isE2EEEnabled = function() {
  3009. return this._e2eEncryption && this._e2eEncryption.isEnabled();
  3010. };
  3011. /**
  3012. * Returns whether End-To-End encryption is supported. Note that not all participants
  3013. * in the conference may support it.
  3014. *
  3015. * @returns {boolean}
  3016. */
  3017. JitsiConference.prototype.isE2EESupported = function() {
  3018. return E2EEncryption.isSupported(this.options.config);
  3019. };
  3020. /**
  3021. * Enables / disables End-to-End encryption.
  3022. *
  3023. * @param {boolean} enabled whether to enable E2EE or not.
  3024. * @returns {void}
  3025. */
  3026. JitsiConference.prototype.toggleE2EE = function(enabled) {
  3027. if (!this.isE2EESupported()) {
  3028. logger.warn('Cannot enable / disable E2EE: platform is not supported.');
  3029. return;
  3030. }
  3031. this._e2eEncryption.setEnabled(enabled);
  3032. };
  3033. /**
  3034. * Returns <tt>true</tt> if lobby support is enabled in the backend.
  3035. *
  3036. * @returns {boolean} whether lobby is supported in the backend.
  3037. */
  3038. JitsiConference.prototype.isLobbySupported = function() {
  3039. return Boolean(this.room && this.room.getLobby().isSupported());
  3040. };
  3041. /**
  3042. * Returns <tt>true</tt> if the room has members only enabled.
  3043. *
  3044. * @returns {boolean} whether conference room is members only.
  3045. */
  3046. JitsiConference.prototype.isMembersOnly = function() {
  3047. return Boolean(this.room && this.room.membersOnlyEnabled);
  3048. };
  3049. /**
  3050. * Enables lobby by moderators
  3051. *
  3052. * @returns {Promise} resolves when lobby room is joined or rejects with the error.
  3053. */
  3054. JitsiConference.prototype.enableLobby = function() {
  3055. if (this.room && this.isModerator()) {
  3056. return this.room.getLobby().enable();
  3057. }
  3058. return Promise.reject(
  3059. new Error('The conference not started or user is not moderator'));
  3060. };
  3061. /**
  3062. * Disabled lobby by moderators
  3063. *
  3064. * @returns {void}
  3065. */
  3066. JitsiConference.prototype.disableLobby = function() {
  3067. if (this.room && this.isModerator()) {
  3068. this.room.getLobby().disable();
  3069. }
  3070. };
  3071. /**
  3072. * Joins the lobby room with display name and optional email or with a shared password to skip waiting.
  3073. *
  3074. * @param {string} displayName Display name should be set to show it to moderators.
  3075. * @param {string} email Optional email is used to present avatar to the moderator.
  3076. * @returns {Promise<never>}
  3077. */
  3078. JitsiConference.prototype.joinLobby = function(displayName, email) {
  3079. if (this.room) {
  3080. return this.room.getLobby().join(displayName, email);
  3081. }
  3082. return Promise.reject(new Error('The conference not started'));
  3083. };
  3084. /**
  3085. * Denies an occupant in the lobby room access to the conference.
  3086. * @param {string} id The participant id.
  3087. */
  3088. JitsiConference.prototype.lobbyDenyAccess = function(id) {
  3089. if (this.room) {
  3090. this.room.getLobby().denyAccess(id);
  3091. }
  3092. };
  3093. /**
  3094. * Approves the request to join the conference to a participant waiting in the lobby.
  3095. *
  3096. * @param {string} id The participant id.
  3097. */
  3098. JitsiConference.prototype.lobbyApproveAccess = function(id) {
  3099. if (this.room) {
  3100. this.room.getLobby().approveAccess(id);
  3101. }
  3102. };