您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

JitsiConference.js 113KB

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