選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conference.js 111KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206
  1. /* global $, APP, JitsiMeetJS, config, interfaceConfig */
  2. import EventEmitter from 'events';
  3. import Logger from 'jitsi-meet-logger';
  4. import * as JitsiMeetConferenceEvents from './ConferenceEvents';
  5. import { openConnection } from './connection';
  6. import { ENDPOINT_TEXT_MESSAGE_NAME } from './modules/API/constants';
  7. import AuthHandler from './modules/UI/authentication/AuthHandler';
  8. import UIUtil from './modules/UI/util/UIUtil';
  9. import mediaDeviceHelper from './modules/devices/mediaDeviceHelper';
  10. import Recorder from './modules/recorder/Recorder';
  11. import { createTaskQueue } from './modules/util/helpers';
  12. import {
  13. createDeviceChangedEvent,
  14. createStartSilentEvent,
  15. createScreenSharingEvent,
  16. createTrackMutedEvent,
  17. sendAnalytics
  18. } from './react/features/analytics';
  19. import {
  20. maybeRedirectToWelcomePage,
  21. redirectToStaticPage,
  22. reloadWithStoredParams
  23. } from './react/features/app';
  24. import {
  25. AVATAR_ID_COMMAND,
  26. AVATAR_URL_COMMAND,
  27. EMAIL_COMMAND,
  28. authStatusChanged,
  29. commonUserJoinedHandling,
  30. commonUserLeftHandling,
  31. conferenceFailed,
  32. conferenceJoined,
  33. conferenceLeft,
  34. conferenceSubjectChanged,
  35. conferenceTimestampChanged,
  36. conferenceWillJoin,
  37. conferenceWillLeave,
  38. dataChannelOpened,
  39. kickedOut,
  40. lockStateChanged,
  41. onStartMutedPolicyChanged,
  42. p2pStatusChanged,
  43. sendLocalParticipant,
  44. setDesktopSharingEnabled
  45. } from './react/features/base/conference';
  46. import {
  47. checkAndNotifyForNewDevice,
  48. getAvailableDevices,
  49. notifyCameraError,
  50. notifyMicError,
  51. setAudioOutputDeviceId,
  52. updateDeviceList
  53. } from './react/features/base/devices';
  54. import {
  55. isFatalJitsiConnectionError,
  56. JitsiConferenceErrors,
  57. JitsiConferenceEvents,
  58. JitsiConnectionErrors,
  59. JitsiConnectionEvents,
  60. JitsiMediaDevicesEvents,
  61. JitsiParticipantConnectionStatus,
  62. JitsiTrackErrors,
  63. JitsiTrackEvents
  64. } from './react/features/base/lib-jitsi-meet';
  65. import {
  66. isVideoMutedByUser,
  67. MEDIA_TYPE,
  68. setAudioAvailable,
  69. setAudioMuted,
  70. setVideoAvailable,
  71. setVideoMuted
  72. } from './react/features/base/media';
  73. import {
  74. dominantSpeakerChanged,
  75. getLocalParticipant,
  76. getNormalizedDisplayName,
  77. getParticipantById,
  78. localParticipantConnectionStatusChanged,
  79. localParticipantRoleChanged,
  80. participantConnectionStatusChanged,
  81. participantKicked,
  82. participantMutedUs,
  83. participantPresenceChanged,
  84. participantRoleChanged,
  85. participantUpdated
  86. } from './react/features/base/participants';
  87. import {
  88. getUserSelectedCameraDeviceId,
  89. updateSettings
  90. } from './react/features/base/settings';
  91. import {
  92. createLocalPresenterTrack,
  93. createLocalTracksF,
  94. destroyLocalTracks,
  95. isLocalVideoTrackMuted,
  96. isLocalTrackMuted,
  97. isUserInteractionRequiredForUnmute,
  98. replaceLocalTrack,
  99. trackAdded,
  100. trackRemoved
  101. } from './react/features/base/tracks';
  102. import { getJitsiMeetGlobalNS } from './react/features/base/util';
  103. import { showDesktopPicker } from './react/features/desktop-picker';
  104. import { appendSuffix } from './react/features/display-name';
  105. import { setE2EEKey } from './react/features/e2ee';
  106. import {
  107. maybeOpenFeedbackDialog,
  108. submitFeedback
  109. } from './react/features/feedback';
  110. import { showNotification } from './react/features/notifications';
  111. import { mediaPermissionPromptVisibilityChanged } from './react/features/overlay';
  112. import { suspendDetected } from './react/features/power-monitor';
  113. import {
  114. initPrejoin,
  115. isPrejoinPageEnabled,
  116. isPrejoinPageVisible,
  117. replacePrejoinAudioTrack,
  118. replacePrejoinVideoTrack
  119. } from './react/features/prejoin';
  120. import { createRnnoiseProcessorPromise } from './react/features/rnnoise';
  121. import { toggleScreenshotCaptureEffect } from './react/features/screenshot-capture';
  122. import { setSharedVideoStatus } from './react/features/shared-video';
  123. import { AudioMixerEffect } from './react/features/stream-effects/audio-mixer/AudioMixerEffect';
  124. import { createPresenterEffect } from './react/features/stream-effects/presenter';
  125. import { endpointMessageReceived } from './react/features/subtitles';
  126. import UIEvents from './service/UI/UIEvents';
  127. import * as RemoteControlEvents
  128. from './service/remotecontrol/RemoteControlEvents';
  129. const logger = Logger.getLogger(__filename);
  130. const eventEmitter = new EventEmitter();
  131. let room;
  132. let connection;
  133. /**
  134. * The promise is used when the prejoin screen is shown.
  135. * While the user configures the devices the connection can be made.
  136. *
  137. * @type {Promise<Object>}
  138. * @private
  139. */
  140. let _connectionPromise;
  141. /**
  142. * This promise is used for chaining mutePresenterVideo calls in order to avoid calling GUM multiple times if it takes
  143. * a while to finish.
  144. *
  145. * @type {Promise<void>}
  146. * @private
  147. */
  148. let _prevMutePresenterVideo = Promise.resolve();
  149. /*
  150. * Logic to open a desktop picker put on the window global for
  151. * lib-jitsi-meet to detect and invoke
  152. */
  153. window.JitsiMeetScreenObtainer = {
  154. openDesktopPicker(options, onSourceChoose) {
  155. APP.store.dispatch(showDesktopPicker(options, onSourceChoose));
  156. }
  157. };
  158. /**
  159. * Known custom conference commands.
  160. */
  161. const commands = {
  162. AVATAR_ID: AVATAR_ID_COMMAND,
  163. AVATAR_URL: AVATAR_URL_COMMAND,
  164. CUSTOM_ROLE: 'custom-role',
  165. EMAIL: EMAIL_COMMAND,
  166. ETHERPAD: 'etherpad',
  167. SHARED_VIDEO: 'shared-video'
  168. };
  169. /**
  170. * Open Connection. When authentication failed it shows auth dialog.
  171. * @param roomName the room name to use
  172. * @returns Promise<JitsiConnection>
  173. */
  174. function connect(roomName) {
  175. return openConnection({
  176. retry: true,
  177. roomName
  178. })
  179. .catch(err => {
  180. if (err === JitsiConnectionErrors.PASSWORD_REQUIRED) {
  181. APP.UI.notifyTokenAuthFailed();
  182. } else {
  183. APP.UI.notifyConnectionFailed(err);
  184. }
  185. throw err;
  186. });
  187. }
  188. /**
  189. * Share data to other users.
  190. * @param command the command
  191. * @param {string} value new value
  192. */
  193. function sendData(command, value) {
  194. if (!room) {
  195. return;
  196. }
  197. room.removeCommand(command);
  198. room.sendCommand(command, { value });
  199. }
  200. /**
  201. * Get user nickname by user id.
  202. * @param {string} id user id
  203. * @returns {string?} user nickname or undefined if user is unknown.
  204. */
  205. function getDisplayName(id) {
  206. const participant = getParticipantById(APP.store.getState(), id);
  207. return participant && participant.name;
  208. }
  209. /**
  210. * Mute or unmute local audio stream if it exists.
  211. * @param {boolean} muted - if audio stream should be muted or unmuted.
  212. */
  213. function muteLocalAudio(muted) {
  214. APP.store.dispatch(setAudioMuted(muted));
  215. }
  216. /**
  217. * Mute or unmute local video stream if it exists.
  218. * @param {boolean} muted if video stream should be muted or unmuted.
  219. *
  220. */
  221. function muteLocalVideo(muted) {
  222. APP.store.dispatch(setVideoMuted(muted));
  223. }
  224. /**
  225. * A queue for the async replaceLocalTrack action so that multiple audio
  226. * replacements cannot happen simultaneously. This solves the issue where
  227. * replaceLocalTrack is called multiple times with an oldTrack of null, causing
  228. * multiple local tracks of the same type to be used.
  229. *
  230. * @private
  231. * @type {Object}
  232. */
  233. const _replaceLocalAudioTrackQueue = createTaskQueue();
  234. /**
  235. * A task queue for replacement local video tracks. This separate queue exists
  236. * so video replacement is not blocked by audio replacement tasks in the queue
  237. * {@link _replaceLocalAudioTrackQueue}.
  238. *
  239. * @private
  240. * @type {Object}
  241. */
  242. const _replaceLocalVideoTrackQueue = createTaskQueue();
  243. /**
  244. *
  245. */
  246. class ConferenceConnector {
  247. /**
  248. *
  249. */
  250. constructor(resolve, reject) {
  251. this._resolve = resolve;
  252. this._reject = reject;
  253. this.reconnectTimeout = null;
  254. room.on(JitsiConferenceEvents.CONFERENCE_JOINED,
  255. this._handleConferenceJoined.bind(this));
  256. room.on(JitsiConferenceEvents.CONFERENCE_FAILED,
  257. this._onConferenceFailed.bind(this));
  258. }
  259. /**
  260. *
  261. */
  262. _handleConferenceFailed(err) {
  263. this._unsubscribe();
  264. this._reject(err);
  265. }
  266. /**
  267. *
  268. */
  269. _onConferenceFailed(err, ...params) {
  270. APP.store.dispatch(conferenceFailed(room, err, ...params));
  271. logger.error('CONFERENCE FAILED:', err, ...params);
  272. switch (err) {
  273. case JitsiConferenceErrors.CONNECTION_ERROR: {
  274. const [ msg ] = params;
  275. APP.UI.notifyConnectionFailed(msg);
  276. break;
  277. }
  278. case JitsiConferenceErrors.NOT_ALLOWED_ERROR: {
  279. // let's show some auth not allowed page
  280. APP.store.dispatch(redirectToStaticPage('static/authError.html'));
  281. break;
  282. }
  283. // not enough rights to create conference
  284. case JitsiConferenceErrors.AUTHENTICATION_REQUIRED: {
  285. // Schedule reconnect to check if someone else created the room.
  286. this.reconnectTimeout = setTimeout(() => {
  287. APP.store.dispatch(conferenceWillJoin(room));
  288. room.join();
  289. }, 5000);
  290. const { password }
  291. = APP.store.getState()['features/base/conference'];
  292. AuthHandler.requireAuth(room, password);
  293. break;
  294. }
  295. case JitsiConferenceErrors.RESERVATION_ERROR: {
  296. const [ code, msg ] = params;
  297. APP.UI.notifyReservationError(code, msg);
  298. break;
  299. }
  300. case JitsiConferenceErrors.GRACEFUL_SHUTDOWN:
  301. APP.UI.notifyGracefulShutdown();
  302. break;
  303. case JitsiConferenceErrors.CONFERENCE_DESTROYED: {
  304. const [ reason ] = params;
  305. APP.UI.hideStats();
  306. APP.UI.notifyConferenceDestroyed(reason);
  307. break;
  308. }
  309. // FIXME FOCUS_DISCONNECTED is a confusing event name.
  310. // What really happens there is that the library is not ready yet,
  311. // because Jicofo is not available, but it is going to give it another
  312. // try.
  313. case JitsiConferenceErrors.FOCUS_DISCONNECTED: {
  314. const [ focus, retrySec ] = params;
  315. APP.UI.notifyFocusDisconnected(focus, retrySec);
  316. break;
  317. }
  318. case JitsiConferenceErrors.FOCUS_LEFT:
  319. case JitsiConferenceErrors.ICE_FAILED:
  320. case JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE:
  321. case JitsiConferenceErrors.OFFER_ANSWER_FAILED:
  322. APP.store.dispatch(conferenceWillLeave(room));
  323. // FIXME the conference should be stopped by the library and not by
  324. // the app. Both the errors above are unrecoverable from the library
  325. // perspective.
  326. room.leave().then(() => connection.disconnect());
  327. break;
  328. case JitsiConferenceErrors.CONFERENCE_MAX_USERS:
  329. connection.disconnect();
  330. APP.UI.notifyMaxUsersLimitReached();
  331. break;
  332. case JitsiConferenceErrors.INCOMPATIBLE_SERVER_VERSIONS:
  333. APP.store.dispatch(reloadWithStoredParams());
  334. break;
  335. default:
  336. this._handleConferenceFailed(err, ...params);
  337. }
  338. }
  339. /**
  340. *
  341. */
  342. _unsubscribe() {
  343. room.off(
  344. JitsiConferenceEvents.CONFERENCE_JOINED,
  345. this._handleConferenceJoined);
  346. room.off(
  347. JitsiConferenceEvents.CONFERENCE_FAILED,
  348. this._onConferenceFailed);
  349. if (this.reconnectTimeout !== null) {
  350. clearTimeout(this.reconnectTimeout);
  351. }
  352. AuthHandler.closeAuth();
  353. }
  354. /**
  355. *
  356. */
  357. _handleConferenceJoined() {
  358. this._unsubscribe();
  359. this._resolve();
  360. }
  361. /**
  362. *
  363. */
  364. connect() {
  365. room.join();
  366. }
  367. }
  368. /**
  369. * Disconnects the connection.
  370. * @returns resolved Promise. We need this in order to make the Promise.all
  371. * call in hangup() to resolve when all operations are finished.
  372. */
  373. function disconnect() {
  374. const onDisconnected = () => {
  375. APP.API.notifyConferenceLeft(APP.conference.roomName);
  376. return Promise.resolve();
  377. };
  378. return connection.disconnect().then(onDisconnected, onDisconnected);
  379. }
  380. /**
  381. * Handles CONNECTION_FAILED events from lib-jitsi-meet.
  382. *
  383. * @param {JitsiConnectionError} error - The reported error.
  384. * @returns {void}
  385. * @private
  386. */
  387. function _connectionFailedHandler(error) {
  388. if (isFatalJitsiConnectionError(error)) {
  389. APP.connection.removeEventListener(
  390. JitsiConnectionEvents.CONNECTION_FAILED,
  391. _connectionFailedHandler);
  392. if (room) {
  393. APP.store.dispatch(conferenceWillLeave(room));
  394. room.leave();
  395. }
  396. }
  397. }
  398. export default {
  399. /**
  400. * Flag used to delay modification of the muted status of local media tracks
  401. * until those are created (or not, but at that point it's certain that
  402. * the tracks won't exist).
  403. */
  404. _localTracksInitialized: false,
  405. isSharingScreen: false,
  406. /**
  407. * Indicates if the desktop sharing functionality has been enabled.
  408. * It takes into consideration the status returned by
  409. * {@link JitsiMeetJS.isDesktopSharingEnabled()}. The latter can be false
  410. * either if the desktop sharing is not supported by the current browser
  411. * or if it was disabled through lib-jitsi-meet specific options (check
  412. * config.js for listed options).
  413. */
  414. isDesktopSharingEnabled: false,
  415. /**
  416. * The local audio track (if any).
  417. * FIXME tracks from redux store should be the single source of truth
  418. * @type {JitsiLocalTrack|null}
  419. */
  420. localAudio: null,
  421. /**
  422. * The local presenter video track (if any).
  423. * @type {JitsiLocalTrack|null}
  424. */
  425. localPresenterVideo: null,
  426. /**
  427. * The local video track (if any).
  428. * FIXME tracks from redux store should be the single source of truth, but
  429. * more refactoring is required around screen sharing ('localVideo' usages).
  430. * @type {JitsiLocalTrack|null}
  431. */
  432. localVideo: null,
  433. /**
  434. * Returns an object containing a promise which resolves with the created tracks &
  435. * the errors resulting from that process.
  436. *
  437. * @returns {Promise<JitsiLocalTrack[]>, Object}
  438. */
  439. createInitialLocalTracks(options = {}) {
  440. const errors = {};
  441. const initialDevices = [ 'audio' ];
  442. const requestedAudio = true;
  443. let requestedVideo = false;
  444. // Always get a handle on the audio input device so that we have statistics even if the user joins the
  445. // conference muted. Previous implementation would only acquire the handle when the user first unmuted,
  446. // which would results in statistics ( such as "No audio input" or "Are you trying to speak?") being available
  447. // only after that point.
  448. if (options.startWithAudioMuted) {
  449. this.muteAudio(true, true);
  450. }
  451. if (!options.startWithVideoMuted
  452. && !options.startAudioOnly
  453. && !options.startScreenSharing) {
  454. initialDevices.push('video');
  455. requestedVideo = true;
  456. }
  457. JitsiMeetJS.mediaDevices.addEventListener(
  458. JitsiMediaDevicesEvents.PERMISSION_PROMPT_IS_SHOWN,
  459. browser =>
  460. APP.store.dispatch(
  461. mediaPermissionPromptVisibilityChanged(true, browser))
  462. );
  463. let tryCreateLocalTracks;
  464. // FIXME is there any simpler way to rewrite this spaghetti below ?
  465. if (options.startScreenSharing) {
  466. tryCreateLocalTracks = this._createDesktopTrack()
  467. .then(([ desktopStream ]) => {
  468. if (!requestedAudio) {
  469. return [ desktopStream ];
  470. }
  471. return createLocalTracksF({ devices: [ 'audio' ] }, true)
  472. .then(([ audioStream ]) =>
  473. [ desktopStream, audioStream ])
  474. .catch(error => {
  475. errors.audioOnlyError = error;
  476. return [ desktopStream ];
  477. });
  478. })
  479. .catch(error => {
  480. logger.error('Failed to obtain desktop stream', error);
  481. errors.screenSharingError = error;
  482. return requestedAudio
  483. ? createLocalTracksF({ devices: [ 'audio' ] }, true)
  484. : [];
  485. })
  486. .catch(error => {
  487. errors.audioOnlyError = error;
  488. return [];
  489. });
  490. } else if (!requestedAudio && !requestedVideo) {
  491. // Resolve with no tracks
  492. tryCreateLocalTracks = Promise.resolve([]);
  493. } else {
  494. tryCreateLocalTracks = createLocalTracksF({ devices: initialDevices }, true)
  495. .catch(err => {
  496. if (requestedAudio && requestedVideo) {
  497. // Try audio only...
  498. errors.audioAndVideoError = err;
  499. return (
  500. createLocalTracksF({ devices: [ 'audio' ] }, true));
  501. } else if (requestedAudio && !requestedVideo) {
  502. errors.audioOnlyError = err;
  503. return [];
  504. } else if (requestedVideo && !requestedAudio) {
  505. errors.videoOnlyError = err;
  506. return [];
  507. }
  508. logger.error('Should never happen');
  509. })
  510. .catch(err => {
  511. // Log this just in case...
  512. if (!requestedAudio) {
  513. logger.error('The impossible just happened', err);
  514. }
  515. errors.audioOnlyError = err;
  516. // Try video only...
  517. return requestedVideo
  518. ? createLocalTracksF({ devices: [ 'video' ] }, true)
  519. : [];
  520. })
  521. .catch(err => {
  522. // Log this just in case...
  523. if (!requestedVideo) {
  524. logger.error('The impossible just happened', err);
  525. }
  526. errors.videoOnlyError = err;
  527. return [];
  528. });
  529. }
  530. // Hide the permissions prompt/overlay as soon as the tracks are
  531. // created. Don't wait for the connection to be made, since in some
  532. // cases, when auth is rquired, for instance, that won't happen until
  533. // the user inputs their credentials, but the dialog would be
  534. // overshadowed by the overlay.
  535. tryCreateLocalTracks.then(tracks => {
  536. APP.store.dispatch(mediaPermissionPromptVisibilityChanged(false));
  537. return tracks;
  538. });
  539. return {
  540. tryCreateLocalTracks,
  541. errors
  542. };
  543. },
  544. /**
  545. * Creates local media tracks and connects to a room. Will show error
  546. * dialogs in case accessing the local microphone and/or camera failed. Will
  547. * show guidance overlay for users on how to give access to camera and/or
  548. * microphone.
  549. * @param {string} roomName
  550. * @param {object} options
  551. * @param {boolean} options.startAudioOnly=false - if <tt>true</tt> then
  552. * only audio track will be created and the audio only mode will be turned
  553. * on.
  554. * @param {boolean} options.startScreenSharing=false - if <tt>true</tt>
  555. * should start with screensharing instead of camera video.
  556. * @param {boolean} options.startWithAudioMuted - will start the conference
  557. * without any audio tracks.
  558. * @param {boolean} options.startWithVideoMuted - will start the conference
  559. * without any video tracks.
  560. * @returns {Promise.<JitsiLocalTrack[], JitsiConnection>}
  561. */
  562. createInitialLocalTracksAndConnect(roomName, options = {}) {
  563. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(options);
  564. const {
  565. audioAndVideoError,
  566. audioOnlyError,
  567. screenSharingError,
  568. videoOnlyError
  569. } = errors;
  570. return Promise.all([ tryCreateLocalTracks, connect(roomName) ])
  571. .then(([ tracks, con ]) => {
  572. // FIXME If there will be microphone error it will cover any
  573. // screensharing dialog, but it's still better than in
  574. // the reverse order where the screensharing dialog will
  575. // sometimes be closing the microphone alert ($.prompt.close();
  576. // is called). Need to figure out dialogs chaining to fix that.
  577. if (screenSharingError) {
  578. this._handleScreenSharingError(screenSharingError);
  579. }
  580. if (audioAndVideoError || audioOnlyError) {
  581. if (audioOnlyError || videoOnlyError) {
  582. // If both requests for 'audio' + 'video' and 'audio'
  583. // only failed, we assume that there are some problems
  584. // with user's microphone and show corresponding dialog.
  585. APP.store.dispatch(notifyMicError(audioOnlyError));
  586. APP.store.dispatch(notifyCameraError(videoOnlyError));
  587. } else {
  588. // If request for 'audio' + 'video' failed, but request
  589. // for 'audio' only was OK, we assume that we had
  590. // problems with camera and show corresponding dialog.
  591. APP.store.dispatch(
  592. notifyCameraError(audioAndVideoError));
  593. }
  594. }
  595. return [ tracks, con ];
  596. });
  597. },
  598. startConference(con, tracks) {
  599. tracks.forEach(track => {
  600. if ((track.isAudioTrack() && this.isLocalAudioMuted())
  601. || (track.isVideoTrack() && this.isLocalVideoMuted())) {
  602. const mediaType = track.getType();
  603. sendAnalytics(
  604. createTrackMutedEvent(mediaType, 'initial mute'));
  605. logger.log(`${mediaType} mute: initially muted.`);
  606. track.mute();
  607. }
  608. });
  609. logger.log(`Initialized with ${tracks.length} local tracks`);
  610. this._localTracksInitialized = true;
  611. con.addEventListener(JitsiConnectionEvents.CONNECTION_FAILED, _connectionFailedHandler);
  612. APP.connection = connection = con;
  613. // Desktop sharing related stuff:
  614. this.isDesktopSharingEnabled
  615. = JitsiMeetJS.isDesktopSharingEnabled();
  616. eventEmitter.emit(JitsiMeetConferenceEvents.DESKTOP_SHARING_ENABLED_CHANGED, this.isDesktopSharingEnabled);
  617. APP.store.dispatch(
  618. setDesktopSharingEnabled(this.isDesktopSharingEnabled));
  619. this._createRoom(tracks);
  620. APP.remoteControl.init();
  621. // if user didn't give access to mic or camera or doesn't have
  622. // them at all, we mark corresponding toolbar buttons as muted,
  623. // so that the user can try unmute later on and add audio/video
  624. // to the conference
  625. if (!tracks.find(t => t.isAudioTrack())) {
  626. this.setAudioMuteStatus(true);
  627. }
  628. if (!tracks.find(t => t.isVideoTrack())) {
  629. this.setVideoMuteStatus(true);
  630. }
  631. if (config.iAmRecorder) {
  632. this.recorder = new Recorder();
  633. }
  634. if (config.startSilent) {
  635. sendAnalytics(createStartSilentEvent());
  636. APP.store.dispatch(showNotification({
  637. descriptionKey: 'notify.startSilentDescription',
  638. titleKey: 'notify.startSilentTitle'
  639. }));
  640. }
  641. // XXX The API will take care of disconnecting from the XMPP
  642. // server (and, thus, leaving the room) on unload.
  643. return new Promise((resolve, reject) => {
  644. (new ConferenceConnector(resolve, reject)).connect();
  645. });
  646. },
  647. /**
  648. * Open new connection and join the conference when prejoin page is not enabled.
  649. * If prejoin page is enabled open an new connection in the background
  650. * and create local tracks.
  651. *
  652. * @param {{ roomName: string }} options
  653. * @returns {Promise}
  654. */
  655. async init({ roomName }) {
  656. const initialOptions = {
  657. startAudioOnly: config.startAudioOnly,
  658. startScreenSharing: config.startScreenSharing,
  659. startWithAudioMuted: config.startWithAudioMuted
  660. || config.startSilent
  661. || isUserInteractionRequiredForUnmute(APP.store.getState()),
  662. startWithVideoMuted: config.startWithVideoMuted
  663. || isUserInteractionRequiredForUnmute(APP.store.getState())
  664. };
  665. this.roomName = roomName;
  666. window.addEventListener('hashchange', this.onHashChange.bind(this), false);
  667. try {
  668. // Initialize the device list first. This way, when creating tracks
  669. // based on preferred devices, loose label matching can be done in
  670. // cases where the exact ID match is no longer available, such as
  671. // when the camera device has switched USB ports.
  672. // when in startSilent mode we want to start with audio muted
  673. await this._initDeviceList();
  674. } catch (error) {
  675. logger.warn('initial device list initialization failed', error);
  676. }
  677. if (isPrejoinPageEnabled(APP.store.getState())) {
  678. _connectionPromise = connect(roomName);
  679. const { tryCreateLocalTracks, errors } = this.createInitialLocalTracks(initialOptions);
  680. const tracks = await tryCreateLocalTracks;
  681. // Initialize device list a second time to ensure device labels
  682. // get populated in case of an initial gUM acceptance; otherwise
  683. // they may remain as empty strings.
  684. this._initDeviceList(true);
  685. return APP.store.dispatch(initPrejoin(tracks, errors));
  686. }
  687. const [ tracks, con ] = await this.createInitialLocalTracksAndConnect(
  688. roomName, initialOptions);
  689. this._initDeviceList(true);
  690. return this.startConference(con, tracks);
  691. },
  692. /**
  693. * Joins conference after the tracks have been configured in the prejoin screen.
  694. *
  695. * @param {Object[]} tracks - An array with the configured tracks
  696. * @returns {Promise}
  697. */
  698. async prejoinStart(tracks) {
  699. const con = await _connectionPromise;
  700. return this.startConference(con, tracks);
  701. },
  702. /**
  703. * Check if id is id of the local user.
  704. * @param {string} id id to check
  705. * @returns {boolean}
  706. */
  707. isLocalId(id) {
  708. return this.getMyUserId() === id;
  709. },
  710. /**
  711. * Tells whether the local video is muted or not.
  712. * @return {boolean}
  713. */
  714. isLocalVideoMuted() {
  715. // If the tracks are not ready, read from base/media state
  716. return this._localTracksInitialized
  717. ? isLocalVideoTrackMuted(
  718. APP.store.getState()['features/base/tracks'])
  719. : isVideoMutedByUser(APP.store);
  720. },
  721. /**
  722. * Simulates toolbar button click for audio mute. Used by shortcuts and API.
  723. * @param {boolean} mute true for mute and false for unmute.
  724. * @param {boolean} [showUI] when set to false will not display any error
  725. * dialogs in case of media permissions error.
  726. */
  727. muteAudio(mute, showUI = true) {
  728. if (!mute
  729. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  730. logger.error('Unmuting audio requires user interaction');
  731. return;
  732. }
  733. // Not ready to modify track's state yet
  734. if (!this._localTracksInitialized) {
  735. // This will only modify base/media.audio.muted which is then synced
  736. // up with the track at the end of local tracks initialization.
  737. muteLocalAudio(mute);
  738. this.setAudioMuteStatus(mute);
  739. return;
  740. } else if (this.isLocalAudioMuted() === mute) {
  741. // NO-OP
  742. return;
  743. }
  744. if (!this.localAudio && !mute) {
  745. const maybeShowErrorDialog = error => {
  746. showUI && APP.store.dispatch(notifyMicError(error));
  747. };
  748. createLocalTracksF({ devices: [ 'audio' ] }, false)
  749. .then(([ audioTrack ]) => audioTrack)
  750. .catch(error => {
  751. maybeShowErrorDialog(error);
  752. // Rollback the audio muted status by using null track
  753. return null;
  754. })
  755. .then(audioTrack => this.useAudioStream(audioTrack));
  756. } else {
  757. muteLocalAudio(mute);
  758. }
  759. },
  760. /**
  761. * Returns whether local audio is muted or not.
  762. * @returns {boolean}
  763. */
  764. isLocalAudioMuted() {
  765. // If the tracks are not ready, read from base/media state
  766. return this._localTracksInitialized
  767. ? isLocalTrackMuted(
  768. APP.store.getState()['features/base/tracks'],
  769. MEDIA_TYPE.AUDIO)
  770. : Boolean(
  771. APP.store.getState()['features/base/media'].audio.muted);
  772. },
  773. /**
  774. * Simulates toolbar button click for audio mute. Used by shortcuts
  775. * and API.
  776. * @param {boolean} [showUI] when set to false will not display any error
  777. * dialogs in case of media permissions error.
  778. */
  779. toggleAudioMuted(showUI = true) {
  780. this.muteAudio(!this.isLocalAudioMuted(), showUI);
  781. },
  782. /**
  783. * Simulates toolbar button click for presenter video mute. Used by
  784. * shortcuts and API.
  785. * @param mute true for mute and false for unmute.
  786. * @param {boolean} [showUI] when set to false will not display any error
  787. * dialogs in case of media permissions error.
  788. */
  789. async mutePresenter(mute, showUI = true) {
  790. const maybeShowErrorDialog = error => {
  791. showUI && APP.store.dispatch(notifyCameraError(error));
  792. };
  793. if (mute) {
  794. try {
  795. await this.localVideo.setEffect(undefined);
  796. } catch (err) {
  797. logger.error('Failed to remove the presenter effect', err);
  798. maybeShowErrorDialog(err);
  799. }
  800. } else {
  801. try {
  802. await this.localVideo.setEffect(await this._createPresenterStreamEffect());
  803. } catch (err) {
  804. logger.error('Failed to apply the presenter effect', err);
  805. maybeShowErrorDialog(err);
  806. }
  807. }
  808. },
  809. /**
  810. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  811. * @param mute true for mute and false for unmute.
  812. * @param {boolean} [showUI] when set to false will not display any error
  813. * dialogs in case of media permissions error.
  814. */
  815. muteVideo(mute, showUI = true) {
  816. if (!mute
  817. && isUserInteractionRequiredForUnmute(APP.store.getState())) {
  818. logger.error('Unmuting video requires user interaction');
  819. return;
  820. }
  821. if (this.isSharingScreen) {
  822. // Chain _mutePresenterVideo calls
  823. _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => this._mutePresenterVideo(mute));
  824. return;
  825. }
  826. // If not ready to modify track's state yet adjust the base/media
  827. if (!this._localTracksInitialized) {
  828. // This will only modify base/media.video.muted which is then synced
  829. // up with the track at the end of local tracks initialization.
  830. muteLocalVideo(mute);
  831. this.setVideoMuteStatus(mute);
  832. return;
  833. } else if (this.isLocalVideoMuted() === mute) {
  834. // NO-OP
  835. return;
  836. }
  837. if (!this.localVideo && !mute) {
  838. const maybeShowErrorDialog = error => {
  839. showUI && APP.store.dispatch(notifyCameraError(error));
  840. };
  841. // Try to create local video if there wasn't any.
  842. // This handles the case when user joined with no video
  843. // (dismissed screen sharing screen or in audio only mode), but
  844. // decided to add it later on by clicking on muted video icon or
  845. // turning off the audio only mode.
  846. //
  847. // FIXME when local track creation is moved to react/redux
  848. // it should take care of the use case described above
  849. createLocalTracksF({ devices: [ 'video' ] }, false)
  850. .then(([ videoTrack ]) => videoTrack)
  851. .catch(error => {
  852. // FIXME should send some feedback to the API on error ?
  853. maybeShowErrorDialog(error);
  854. // Rollback the video muted status by using null track
  855. return null;
  856. })
  857. .then(videoTrack => this.useVideoStream(videoTrack));
  858. } else {
  859. // FIXME show error dialog if it fails (should be handled by react)
  860. muteLocalVideo(mute);
  861. }
  862. },
  863. /**
  864. * Simulates toolbar button click for video mute. Used by shortcuts and API.
  865. * @param {boolean} [showUI] when set to false will not display any error
  866. * dialogs in case of media permissions error.
  867. */
  868. toggleVideoMuted(showUI = true) {
  869. this.muteVideo(!this.isLocalVideoMuted(), showUI);
  870. },
  871. /**
  872. * Retrieve list of ids of conference participants (without local user).
  873. * @returns {string[]}
  874. */
  875. listMembersIds() {
  876. return room.getParticipants().map(p => p.getId());
  877. },
  878. /**
  879. * Checks whether the participant identified by id is a moderator.
  880. * @id id to search for participant
  881. * @return {boolean} whether the participant is moderator
  882. */
  883. isParticipantModerator(id) {
  884. const user = room.getParticipantById(id);
  885. return user && user.isModerator();
  886. },
  887. /**
  888. * Retrieve list of conference participants (without local user).
  889. * @returns {JitsiParticipant[]}
  890. *
  891. * NOTE: Used by jitsi-meet-torture!
  892. */
  893. listMembers() {
  894. return room.getParticipants();
  895. },
  896. get membersCount() {
  897. return room.getParticipants().length + 1;
  898. },
  899. /**
  900. * Returns true if the callstats integration is enabled, otherwise returns
  901. * false.
  902. *
  903. * @returns true if the callstats integration is enabled, otherwise returns
  904. * false.
  905. */
  906. isCallstatsEnabled() {
  907. return room && room.isCallstatsEnabled();
  908. },
  909. /**
  910. * Sends the given feedback through CallStats if enabled.
  911. *
  912. * @param overallFeedback an integer between 1 and 5 indicating the
  913. * user feedback
  914. * @param detailedFeedback detailed feedback from the user. Not yet used
  915. */
  916. sendFeedback(overallFeedback, detailedFeedback) {
  917. return room.sendFeedback(overallFeedback, detailedFeedback);
  918. },
  919. /**
  920. * Get speaker stats that track total dominant speaker time.
  921. *
  922. * @returns {object} A hash with keys being user ids and values being the
  923. * library's SpeakerStats model used for calculating time as dominant
  924. * speaker.
  925. */
  926. getSpeakerStats() {
  927. return room.getSpeakerStats();
  928. },
  929. /**
  930. * Returns the connection times stored in the library.
  931. */
  932. getConnectionTimes() {
  933. return room.getConnectionTimes();
  934. },
  935. // used by torture currently
  936. isJoined() {
  937. return room && room.isJoined();
  938. },
  939. getConnectionState() {
  940. return room && room.getConnectionState();
  941. },
  942. /**
  943. * Obtains current P2P ICE connection state.
  944. * @return {string|null} ICE connection state or <tt>null</tt> if there's no
  945. * P2P connection
  946. */
  947. getP2PConnectionState() {
  948. return room && room.getP2PConnectionState();
  949. },
  950. /**
  951. * Starts P2P (for tests only)
  952. * @private
  953. */
  954. _startP2P() {
  955. try {
  956. room && room.startP2PSession();
  957. } catch (error) {
  958. logger.error('Start P2P failed', error);
  959. throw error;
  960. }
  961. },
  962. /**
  963. * Stops P2P (for tests only)
  964. * @private
  965. */
  966. _stopP2P() {
  967. try {
  968. room && room.stopP2PSession();
  969. } catch (error) {
  970. logger.error('Stop P2P failed', error);
  971. throw error;
  972. }
  973. },
  974. /**
  975. * Checks whether or not our connection is currently in interrupted and
  976. * reconnect attempts are in progress.
  977. *
  978. * @returns {boolean} true if the connection is in interrupted state or
  979. * false otherwise.
  980. */
  981. isConnectionInterrupted() {
  982. return room.isConnectionInterrupted();
  983. },
  984. /**
  985. * Obtains the local display name.
  986. * @returns {string|undefined}
  987. */
  988. getLocalDisplayName() {
  989. return getDisplayName(this.getMyUserId());
  990. },
  991. /**
  992. * Finds JitsiParticipant for given id.
  993. *
  994. * @param {string} id participant's identifier(MUC nickname).
  995. *
  996. * @returns {JitsiParticipant|null} participant instance for given id or
  997. * null if not found.
  998. */
  999. getParticipantById(id) {
  1000. return room ? room.getParticipantById(id) : null;
  1001. },
  1002. /**
  1003. * Get participant connection status for the participant.
  1004. *
  1005. * @param {string} id participant's identifier(MUC nickname)
  1006. *
  1007. * @returns {ParticipantConnectionStatus|null} the status of the participant
  1008. * or null if no such participant is found or participant is the local user.
  1009. */
  1010. getParticipantConnectionStatus(id) {
  1011. const participant = this.getParticipantById(id);
  1012. return participant ? participant.getConnectionStatus() : null;
  1013. },
  1014. /**
  1015. * Gets the display name foe the <tt>JitsiParticipant</tt> identified by
  1016. * the given <tt>id</tt>.
  1017. *
  1018. * @param id {string} the participant's id(MUC nickname/JVB endpoint id)
  1019. *
  1020. * @return {string} the participant's display name or the default string if
  1021. * absent.
  1022. */
  1023. getParticipantDisplayName(id) {
  1024. const displayName = getDisplayName(id);
  1025. if (displayName) {
  1026. return displayName;
  1027. }
  1028. if (APP.conference.isLocalId(id)) {
  1029. return APP.translation.generateTranslationHTML(
  1030. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  1031. }
  1032. return interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  1033. },
  1034. getMyUserId() {
  1035. return room && room.myUserId();
  1036. },
  1037. /**
  1038. * Will be filled with values only when config.debug is enabled.
  1039. * Its used by torture to check audio levels.
  1040. */
  1041. audioLevelsMap: {},
  1042. /**
  1043. * Returns the stored audio level (stored only if config.debug is enabled)
  1044. * @param id the id for the user audio level to return (the id value is
  1045. * returned for the participant using getMyUserId() method)
  1046. */
  1047. getPeerSSRCAudioLevel(id) {
  1048. return this.audioLevelsMap[id];
  1049. },
  1050. /**
  1051. * @return {number} the number of participants in the conference with at
  1052. * least one track.
  1053. */
  1054. getNumberOfParticipantsWithTracks() {
  1055. return room.getParticipants()
  1056. .filter(p => p.getTracks().length > 0)
  1057. .length;
  1058. },
  1059. /**
  1060. * Returns the stats.
  1061. */
  1062. getStats() {
  1063. return room.connectionQuality.getStats();
  1064. },
  1065. // end used by torture
  1066. getLogs() {
  1067. return room.getLogs();
  1068. },
  1069. /**
  1070. * Download logs, a function that can be called from console while
  1071. * debugging.
  1072. * @param filename (optional) specify target filename
  1073. */
  1074. saveLogs(filename = 'meetlog.json') {
  1075. // this can be called from console and will not have reference to this
  1076. // that's why we reference the global var
  1077. const logs = APP.conference.getLogs();
  1078. const data = encodeURIComponent(JSON.stringify(logs, null, ' '));
  1079. const elem = document.createElement('a');
  1080. elem.download = filename;
  1081. elem.href = `data:application/json;charset=utf-8,\n${data}`;
  1082. elem.dataset.downloadurl
  1083. = [ 'text/json', elem.download, elem.href ].join(':');
  1084. elem.dispatchEvent(new MouseEvent('click', {
  1085. view: window,
  1086. bubbles: true,
  1087. cancelable: false
  1088. }));
  1089. },
  1090. /**
  1091. * Handled location hash change events.
  1092. */
  1093. onHashChange() {
  1094. const items = {};
  1095. const parts = window.location.hash.substr(1).split('&');
  1096. for (const part of parts) {
  1097. const param = part.split('=');
  1098. const key = param[0];
  1099. if (!key) {
  1100. continue; // eslint-disable-line no-continue
  1101. }
  1102. items[key] = param[1];
  1103. }
  1104. if (typeof items.e2eekey !== undefined) {
  1105. APP.store.dispatch(setE2EEKey(items.e2eekey));
  1106. // Clean URL in browser history.
  1107. const cleanUrl = window.location.href.split('#')[0];
  1108. history.replaceState(history.state, document.title, cleanUrl);
  1109. }
  1110. },
  1111. /**
  1112. * Exposes a Command(s) API on this instance. It is necessitated by (1) the
  1113. * desire to keep room private to this instance and (2) the need of other
  1114. * modules to send and receive commands to and from participants.
  1115. * Eventually, this instance remains in control with respect to the
  1116. * decision whether the Command(s) API of room (i.e. lib-jitsi-meet's
  1117. * JitsiConference) is to be used in the implementation of the Command(s)
  1118. * API of this instance.
  1119. */
  1120. commands: {
  1121. /**
  1122. * Known custom conference commands.
  1123. */
  1124. defaults: commands,
  1125. /**
  1126. * Receives notifications from other participants about commands aka
  1127. * custom events (sent by sendCommand or sendCommandOnce methods).
  1128. * @param command {String} the name of the command
  1129. * @param handler {Function} handler for the command
  1130. */
  1131. addCommandListener() {
  1132. // eslint-disable-next-line prefer-rest-params
  1133. room.addCommandListener(...arguments);
  1134. },
  1135. /**
  1136. * Removes command.
  1137. * @param name {String} the name of the command.
  1138. */
  1139. removeCommand() {
  1140. // eslint-disable-next-line prefer-rest-params
  1141. room.removeCommand(...arguments);
  1142. },
  1143. /**
  1144. * Sends command.
  1145. * @param name {String} the name of the command.
  1146. * @param values {Object} with keys and values that will be sent.
  1147. */
  1148. sendCommand() {
  1149. // eslint-disable-next-line prefer-rest-params
  1150. room.sendCommand(...arguments);
  1151. },
  1152. /**
  1153. * Sends command one time.
  1154. * @param name {String} the name of the command.
  1155. * @param values {Object} with keys and values that will be sent.
  1156. */
  1157. sendCommandOnce() {
  1158. // eslint-disable-next-line prefer-rest-params
  1159. room.sendCommandOnce(...arguments);
  1160. }
  1161. },
  1162. _createRoom(localTracks) {
  1163. room
  1164. = connection.initJitsiConference(
  1165. APP.conference.roomName,
  1166. this._getConferenceOptions());
  1167. APP.store.dispatch(conferenceWillJoin(room));
  1168. this._setLocalAudioVideoStreams(localTracks);
  1169. this._room = room; // FIXME do not use this
  1170. sendLocalParticipant(APP.store, room);
  1171. this._setupListeners();
  1172. },
  1173. /**
  1174. * Sets local video and audio streams.
  1175. * @param {JitsiLocalTrack[]} tracks=[]
  1176. * @returns {Promise[]}
  1177. * @private
  1178. */
  1179. _setLocalAudioVideoStreams(tracks = []) {
  1180. return tracks.map(track => {
  1181. if (track.isAudioTrack()) {
  1182. return this.useAudioStream(track);
  1183. } else if (track.isVideoTrack()) {
  1184. return this.useVideoStream(track);
  1185. }
  1186. logger.error(
  1187. 'Ignored not an audio nor a video track: ', track);
  1188. return Promise.resolve();
  1189. });
  1190. },
  1191. _getConferenceOptions() {
  1192. const options = config;
  1193. const { email, name: nick } = getLocalParticipant(APP.store.getState());
  1194. const { locationURL } = APP.store.getState()['features/base/connection'];
  1195. if (options.enableDisplayNameInStats && nick) {
  1196. options.statisticsDisplayName = nick;
  1197. }
  1198. if (options.enableEmailInStats && email) {
  1199. options.statisticsId = email;
  1200. }
  1201. options.applicationName = interfaceConfig.APP_NAME;
  1202. options.getWiFiStatsMethod = this._getWiFiStatsMethod;
  1203. options.confID = `${locationURL.host}${locationURL.pathname}`;
  1204. options.createVADProcessor = createRnnoiseProcessorPromise;
  1205. // Disable CallStats, if requessted.
  1206. if (options.disableThirdPartyRequests) {
  1207. delete options.callStatsID;
  1208. delete options.callStatsSecret;
  1209. delete options.getWiFiStatsMethod;
  1210. }
  1211. return options;
  1212. },
  1213. /**
  1214. * Returns the result of getWiFiStats from the global NS or does nothing
  1215. * (returns empty result).
  1216. * Fixes a concurrency problem where we need to pass a function when creating
  1217. * JitsiConference, but that method is added to the context later.
  1218. *
  1219. * @returns {Promise}
  1220. * @private
  1221. */
  1222. _getWiFiStatsMethod() {
  1223. const gloabalNS = getJitsiMeetGlobalNS();
  1224. return gloabalNS.getWiFiStats ? gloabalNS.getWiFiStats() : Promise.resolve('{}');
  1225. },
  1226. /**
  1227. * Start using provided video stream.
  1228. * Stops previous video stream.
  1229. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1230. * @returns {Promise}
  1231. */
  1232. useVideoStream(newStream) {
  1233. return new Promise((resolve, reject) => {
  1234. _replaceLocalVideoTrackQueue.enqueue(onFinish => {
  1235. /**
  1236. * When the prejoin page is visible there is no conference object
  1237. * created. The prejoin tracks are managed separately,
  1238. * so this updates the prejoin video track.
  1239. */
  1240. if (isPrejoinPageVisible(APP.store.getState())) {
  1241. return APP.store.dispatch(replacePrejoinVideoTrack(newStream))
  1242. .then(resolve)
  1243. .catch(reject)
  1244. .then(onFinish);
  1245. }
  1246. APP.store.dispatch(
  1247. replaceLocalTrack(this.localVideo, newStream, room))
  1248. .then(() => {
  1249. this.localVideo = newStream;
  1250. this._setSharingScreen(newStream);
  1251. if (newStream) {
  1252. APP.UI.addLocalVideoStream(newStream);
  1253. }
  1254. this.setVideoMuteStatus(this.isLocalVideoMuted());
  1255. })
  1256. .then(resolve)
  1257. .catch(reject)
  1258. .then(onFinish);
  1259. });
  1260. });
  1261. },
  1262. /**
  1263. * Sets `this.isSharingScreen` depending on provided video stream.
  1264. * In case new screen sharing status is not equal previous one
  1265. * it updates desktop sharing buttons in UI
  1266. * and notifies external application.
  1267. *
  1268. * @param {JitsiLocalTrack} [newStream] new stream to use or null
  1269. * @private
  1270. * @returns {void}
  1271. */
  1272. _setSharingScreen(newStream) {
  1273. const wasSharingScreen = this.isSharingScreen;
  1274. this.isSharingScreen = newStream && newStream.videoType === 'desktop';
  1275. if (wasSharingScreen !== this.isSharingScreen) {
  1276. const details = {};
  1277. if (this.isSharingScreen) {
  1278. details.sourceType = newStream.sourceType;
  1279. }
  1280. APP.API.notifyScreenSharingStatusChanged(
  1281. this.isSharingScreen, details);
  1282. }
  1283. },
  1284. /**
  1285. * Start using provided audio stream.
  1286. * Stops previous audio stream.
  1287. * @param {JitsiLocalTrack} [stream] new stream to use or null
  1288. * @returns {Promise}
  1289. */
  1290. useAudioStream(newStream) {
  1291. return new Promise((resolve, reject) => {
  1292. _replaceLocalAudioTrackQueue.enqueue(onFinish => {
  1293. /**
  1294. * When the prejoin page is visible there is no conference object
  1295. * created. The prejoin tracks are managed separately,
  1296. * so this updates the prejoin audio stream.
  1297. */
  1298. if (isPrejoinPageVisible(APP.store.getState())) {
  1299. return APP.store.dispatch(replacePrejoinAudioTrack(newStream))
  1300. .then(resolve)
  1301. .catch(reject)
  1302. .then(onFinish);
  1303. }
  1304. APP.store.dispatch(
  1305. replaceLocalTrack(this.localAudio, newStream, room))
  1306. .then(() => {
  1307. this.localAudio = newStream;
  1308. this.setAudioMuteStatus(this.isLocalAudioMuted());
  1309. })
  1310. .then(resolve)
  1311. .catch(reject)
  1312. .then(onFinish);
  1313. });
  1314. });
  1315. },
  1316. /**
  1317. * Returns whether or not the conference is currently in audio only mode.
  1318. *
  1319. * @returns {boolean}
  1320. */
  1321. isAudioOnly() {
  1322. return Boolean(APP.store.getState()['features/base/audio-only'].enabled);
  1323. },
  1324. videoSwitchInProgress: false,
  1325. /**
  1326. * This fields stores a handler which will create a Promise which turns off
  1327. * the screen sharing and restores the previous video state (was there
  1328. * any video, before switching to screen sharing ? was it muted ?).
  1329. *
  1330. * Once called this fields is cleared to <tt>null</tt>.
  1331. * @type {Function|null}
  1332. */
  1333. _untoggleScreenSharing: null,
  1334. /**
  1335. * Creates a Promise which turns off the screen sharing and restores
  1336. * the previous state described by the arguments.
  1337. *
  1338. * This method is bound to the appropriate values, after switching to screen
  1339. * sharing and stored in {@link _untoggleScreenSharing}.
  1340. *
  1341. * @param {boolean} didHaveVideo indicates if there was a camera video being
  1342. * used, before switching to screen sharing.
  1343. * @param {boolean} wasVideoMuted indicates if the video was muted, before
  1344. * switching to screen sharing.
  1345. * @return {Promise} resolved after the screen sharing is turned off, or
  1346. * rejected with some error (no idea what kind of error, possible GUM error)
  1347. * in case it fails.
  1348. * @private
  1349. */
  1350. async _turnScreenSharingOff(didHaveVideo) {
  1351. this._untoggleScreenSharing = null;
  1352. this.videoSwitchInProgress = true;
  1353. const { receiver } = APP.remoteControl;
  1354. if (receiver) {
  1355. receiver.stop();
  1356. }
  1357. this._stopProxyConnection();
  1358. if (config.enableScreenshotCapture) {
  1359. APP.store.dispatch(toggleScreenshotCaptureEffect(false));
  1360. }
  1361. // It can happen that presenter GUM is in progress while screensharing is being turned off. Here it needs to
  1362. // wait for that GUM to be resolved in order to prevent leaking the presenter track(this.localPresenterVideo
  1363. // will be null when SS is being turned off, but it will initialize once GUM resolves).
  1364. let promise = _prevMutePresenterVideo = _prevMutePresenterVideo.then(() => {
  1365. // mute the presenter track if it exists.
  1366. if (this.localPresenterVideo) {
  1367. APP.store.dispatch(setVideoMuted(true, MEDIA_TYPE.PRESENTER));
  1368. return this.localPresenterVideo.dispose().then(() => {
  1369. APP.store.dispatch(trackRemoved(this.localPresenterVideo));
  1370. this.localPresenterVideo = null;
  1371. });
  1372. }
  1373. });
  1374. // If system audio was also shared stop the AudioMixerEffect and dispose of the desktop audio track.
  1375. if (this._mixerEffect) {
  1376. await this.localAudio.setEffect(undefined);
  1377. await this._desktopAudioStream.dispose();
  1378. this._mixerEffect = undefined;
  1379. this._desktopAudioStream = undefined;
  1380. // In case there was no local audio when screen sharing was started the fact that we set the audio stream to
  1381. // null will take care of the desktop audio stream cleanup.
  1382. } else if (this._desktopAudioStream) {
  1383. await this.useAudioStream(null);
  1384. this._desktopAudioStream = undefined;
  1385. }
  1386. if (didHaveVideo) {
  1387. promise = promise.then(() => createLocalTracksF({ devices: [ 'video' ] }))
  1388. .then(([ stream ]) => this.useVideoStream(stream))
  1389. .then(() => {
  1390. sendAnalytics(createScreenSharingEvent('stopped'));
  1391. logger.log('Screen sharing stopped.');
  1392. })
  1393. .catch(error => {
  1394. logger.error('failed to switch back to local video', error);
  1395. return this.useVideoStream(null).then(() =>
  1396. // Still fail with the original err
  1397. Promise.reject(error)
  1398. );
  1399. });
  1400. } else {
  1401. promise = promise.then(() => this.useVideoStream(null));
  1402. }
  1403. return promise.then(
  1404. () => {
  1405. this.videoSwitchInProgress = false;
  1406. },
  1407. error => {
  1408. this.videoSwitchInProgress = false;
  1409. throw error;
  1410. });
  1411. },
  1412. /**
  1413. * Toggles between screen sharing and camera video if the toggle parameter
  1414. * is not specified and starts the procedure for obtaining new screen
  1415. * sharing/video track otherwise.
  1416. *
  1417. * @param {boolean} [toggle] - If true - new screen sharing track will be
  1418. * obtained. If false - new video track will be obtain. If not specified -
  1419. * toggles between screen sharing and camera video.
  1420. * @param {Object} [options] - Screen sharing options that will be passed to
  1421. * createLocalTracks.
  1422. * @param {Array<string>} [options.desktopSharingSources] - Array with the
  1423. * sources that have to be displayed in the desktop picker window ('screen',
  1424. * 'window', etc.).
  1425. * @return {Promise.<T>}
  1426. */
  1427. async toggleScreenSharing(toggle = !this._untoggleScreenSharing, options = {}) {
  1428. if (this.videoSwitchInProgress) {
  1429. return Promise.reject('Switch in progress.');
  1430. }
  1431. if (!this.isDesktopSharingEnabled) {
  1432. return Promise.reject(
  1433. 'Cannot toggle screen sharing: not supported.');
  1434. }
  1435. if (this.isAudioOnly()) {
  1436. return Promise.reject('No screensharing in audio only mode');
  1437. }
  1438. if (toggle) {
  1439. try {
  1440. await this._switchToScreenSharing(options);
  1441. return;
  1442. } catch (err) {
  1443. logger.error('Failed to switch to screensharing', err);
  1444. return;
  1445. }
  1446. }
  1447. return this._untoggleScreenSharing
  1448. ? this._untoggleScreenSharing()
  1449. : Promise.resolve();
  1450. },
  1451. /**
  1452. * Creates desktop (screensharing) {@link JitsiLocalTrack}
  1453. *
  1454. * @param {Object} [options] - Screen sharing options that will be passed to
  1455. * createLocalTracks.
  1456. * @param {Object} [options.desktopSharing]
  1457. * @param {Object} [options.desktopStream] - An existing desktop stream to
  1458. * use instead of creating a new desktop stream.
  1459. * @return {Promise.<JitsiLocalTrack>} - A Promise resolved with
  1460. * {@link JitsiLocalTrack} for the screensharing or rejected with
  1461. * {@link JitsiTrackError}.
  1462. *
  1463. * @private
  1464. */
  1465. _createDesktopTrack(options = {}) {
  1466. let externalInstallation = false;
  1467. let DSExternalInstallationInProgress = false;
  1468. const didHaveVideo = !this.isLocalVideoMuted();
  1469. const getDesktopStreamPromise = options.desktopStream
  1470. ? Promise.resolve([ options.desktopStream ])
  1471. : createLocalTracksF({
  1472. desktopSharingSourceDevice: options.desktopSharingSources
  1473. ? null : config._desktopSharingSourceDevice,
  1474. desktopSharingSources: options.desktopSharingSources,
  1475. devices: [ 'desktop' ],
  1476. desktopSharingExtensionExternalInstallation: {
  1477. interval: 500,
  1478. checkAgain: () => DSExternalInstallationInProgress,
  1479. listener: (status, url) => {
  1480. switch (status) {
  1481. case 'waitingForExtension': {
  1482. DSExternalInstallationInProgress = true;
  1483. externalInstallation = true;
  1484. const listener = () => {
  1485. // Wait a little bit more just to be sure that
  1486. // we won't miss the extension installation
  1487. setTimeout(() => {
  1488. DSExternalInstallationInProgress = false;
  1489. },
  1490. 500);
  1491. APP.UI.removeListener(
  1492. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1493. listener);
  1494. };
  1495. APP.UI.addListener(
  1496. UIEvents.EXTERNAL_INSTALLATION_CANCELED,
  1497. listener);
  1498. APP.UI.showExtensionExternalInstallationDialog(url);
  1499. break;
  1500. }
  1501. case 'extensionFound':
  1502. // Close the dialog.
  1503. externalInstallation && $.prompt.close();
  1504. break;
  1505. default:
  1506. // Unknown status
  1507. }
  1508. }
  1509. }
  1510. });
  1511. return getDesktopStreamPromise.then(desktopStreams => {
  1512. // Stores the "untoggle" handler which remembers whether was
  1513. // there any video before and whether was it muted.
  1514. this._untoggleScreenSharing
  1515. = this._turnScreenSharingOff.bind(this, didHaveVideo);
  1516. const desktopVideoStream = desktopStreams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1517. if (desktopVideoStream) {
  1518. desktopVideoStream.on(
  1519. JitsiTrackEvents.LOCAL_TRACK_STOPPED,
  1520. () => {
  1521. // If the stream was stopped during screen sharing
  1522. // session then we should switch back to video.
  1523. this.isSharingScreen
  1524. && this._untoggleScreenSharing
  1525. && this._untoggleScreenSharing();
  1526. }
  1527. );
  1528. }
  1529. // close external installation dialog on success.
  1530. externalInstallation && $.prompt.close();
  1531. return desktopStreams;
  1532. }, error => {
  1533. DSExternalInstallationInProgress = false;
  1534. // close external installation dialog on success.
  1535. externalInstallation && $.prompt.close();
  1536. throw error;
  1537. });
  1538. },
  1539. /**
  1540. * Creates a new instance of presenter effect. A new video track is created
  1541. * using the new set of constraints that are calculated based on
  1542. * the height of the desktop that is being currently shared.
  1543. *
  1544. * @param {number} height - The height of the desktop stream that is being
  1545. * currently shared.
  1546. * @param {string} cameraDeviceId - The device id of the camera to be used.
  1547. * @return {Promise<JitsiStreamPresenterEffect>} - A promise resolved with
  1548. * {@link JitsiStreamPresenterEffect} if it succeeds.
  1549. */
  1550. async _createPresenterStreamEffect(height = null, cameraDeviceId = null) {
  1551. if (!this.localPresenterVideo) {
  1552. try {
  1553. this.localPresenterVideo = await createLocalPresenterTrack({ cameraDeviceId }, height);
  1554. } catch (err) {
  1555. logger.error('Failed to create a camera track for presenter', err);
  1556. return;
  1557. }
  1558. APP.store.dispatch(trackAdded(this.localPresenterVideo));
  1559. }
  1560. try {
  1561. const effect = await createPresenterEffect(this.localPresenterVideo.stream);
  1562. return effect;
  1563. } catch (err) {
  1564. logger.error('Failed to create the presenter effect', err);
  1565. }
  1566. },
  1567. /**
  1568. * Tries to turn the presenter video track on or off. If a presenter track
  1569. * doesn't exist, a new video track is created.
  1570. *
  1571. * @param mute - true for mute and false for unmute.
  1572. *
  1573. * @private
  1574. */
  1575. async _mutePresenterVideo(mute) {
  1576. const maybeShowErrorDialog = error => {
  1577. APP.store.dispatch(notifyCameraError(error));
  1578. };
  1579. // Check for NO-OP
  1580. if (mute && (!this.localPresenterVideo || this.localPresenterVideo.isMuted())) {
  1581. return;
  1582. } else if (!mute && this.localPresenterVideo && !this.localPresenterVideo.isMuted()) {
  1583. return;
  1584. }
  1585. // Create a new presenter track and apply the presenter effect.
  1586. if (!this.localPresenterVideo && !mute) {
  1587. let { aspectRatio, height } = this.localVideo.track.getSettings();
  1588. const { width } = this.localVideo.track.getSettings();
  1589. let desktopResizeConstraints = {};
  1590. let resizeDesktopStream = false;
  1591. const DESKTOP_STREAM_CAP = 720;
  1592. // Determine the constraints if the desktop track needs to be resized.
  1593. // Resizing is needed when the resolution cannot be determined or when
  1594. // the window is bigger than 720p.
  1595. if (height && width) {
  1596. aspectRatio = aspectRatio ?? (width / height).toPrecision(4);
  1597. const advancedConstraints = [ { aspectRatio } ];
  1598. const isPortrait = height >= width;
  1599. // Determine which dimension needs resizing and resize only that side
  1600. // keeping the aspect ratio same as before.
  1601. if (isPortrait && width > DESKTOP_STREAM_CAP) {
  1602. resizeDesktopStream = true;
  1603. advancedConstraints.push({ width: DESKTOP_STREAM_CAP });
  1604. } else if (!isPortrait && height > DESKTOP_STREAM_CAP) {
  1605. resizeDesktopStream = true;
  1606. advancedConstraints.push({ height: DESKTOP_STREAM_CAP });
  1607. }
  1608. desktopResizeConstraints.advanced = advancedConstraints;
  1609. } else {
  1610. resizeDesktopStream = true;
  1611. desktopResizeConstraints = {
  1612. width: 1280,
  1613. height: 720
  1614. };
  1615. }
  1616. if (resizeDesktopStream) {
  1617. try {
  1618. await this.localVideo.track.applyConstraints(desktopResizeConstraints);
  1619. } catch (err) {
  1620. logger.error('Failed to apply constraints on the desktop stream for presenter mode', err);
  1621. return;
  1622. }
  1623. height = this.localVideo.track.getSettings().height ?? DESKTOP_STREAM_CAP;
  1624. }
  1625. const defaultCamera = getUserSelectedCameraDeviceId(APP.store.getState());
  1626. let effect;
  1627. try {
  1628. effect = await this._createPresenterStreamEffect(height,
  1629. defaultCamera);
  1630. } catch (err) {
  1631. logger.error('Failed to unmute Presenter Video');
  1632. maybeShowErrorDialog(err);
  1633. return;
  1634. }
  1635. try {
  1636. await this.localVideo.setEffect(effect);
  1637. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1638. this.setVideoMuteStatus(mute);
  1639. } catch (err) {
  1640. logger.error('Failed to apply the Presenter effect', err);
  1641. }
  1642. } else {
  1643. APP.store.dispatch(setVideoMuted(mute, MEDIA_TYPE.PRESENTER));
  1644. }
  1645. },
  1646. /**
  1647. * Tries to switch to the screensharing mode by disposing camera stream and
  1648. * replacing it with a desktop one.
  1649. *
  1650. * @param {Object} [options] - Screen sharing options that will be passed to
  1651. * createLocalTracks.
  1652. *
  1653. * @return {Promise} - A Promise resolved if the operation succeeds or
  1654. * rejected with some unknown type of error in case it fails. Promise will
  1655. * be rejected immediately if {@link videoSwitchInProgress} is true.
  1656. *
  1657. * @private
  1658. */
  1659. _switchToScreenSharing(options = {}) {
  1660. if (this.videoSwitchInProgress) {
  1661. return Promise.reject('Switch in progress.');
  1662. }
  1663. this.videoSwitchInProgress = true;
  1664. return this._createDesktopTrack(options)
  1665. .then(async streams => {
  1666. const desktopVideoStream = streams.find(stream => stream.getType() === MEDIA_TYPE.VIDEO);
  1667. if (desktopVideoStream) {
  1668. await this.useVideoStream(desktopVideoStream);
  1669. }
  1670. this._desktopAudioStream = streams.find(stream => stream.getType() === MEDIA_TYPE.AUDIO);
  1671. if (this._desktopAudioStream) {
  1672. // If there is a localAudio stream, mix in the desktop audio stream captured by the screen sharing
  1673. // api.
  1674. if (this.localAudio) {
  1675. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  1676. await this.localAudio.setEffect(this._mixerEffect);
  1677. } else {
  1678. // If no local stream is present ( i.e. no input audio devices) we use the screen share audio
  1679. // stream as we would use a regular stream.
  1680. await this.useAudioStream(this._desktopAudioStream);
  1681. }
  1682. }
  1683. })
  1684. .then(() => {
  1685. this.videoSwitchInProgress = false;
  1686. if (config.enableScreenshotCapture) {
  1687. APP.store.dispatch(toggleScreenshotCaptureEffect(true));
  1688. }
  1689. sendAnalytics(createScreenSharingEvent('started'));
  1690. logger.log('Screen sharing started');
  1691. })
  1692. .catch(error => {
  1693. this.videoSwitchInProgress = false;
  1694. // Pawel: With this call I'm trying to preserve the original
  1695. // behaviour although it is not clear why would we "untoggle"
  1696. // on failure. I suppose it was to restore video in case there
  1697. // was some problem during "this.useVideoStream(desktopStream)".
  1698. // It's important to note that the handler will not be available
  1699. // if we fail early on trying to get desktop media (which makes
  1700. // sense, because the camera video is still being used, so
  1701. // nothing to "untoggle").
  1702. if (this._untoggleScreenSharing) {
  1703. this._untoggleScreenSharing();
  1704. }
  1705. // FIXME the code inside of _handleScreenSharingError is
  1706. // asynchronous, but does not return a Promise and is not part
  1707. // of the current Promise chain.
  1708. this._handleScreenSharingError(error);
  1709. return Promise.reject(error);
  1710. });
  1711. },
  1712. /**
  1713. * Handles {@link JitsiTrackError} returned by the lib-jitsi-meet when
  1714. * trying to create screensharing track. It will either do nothing if
  1715. * the dialog was canceled on user's request or display inline installation
  1716. * dialog and ask the user to install the extension, once the extension is
  1717. * installed it will switch the conference to screensharing. The last option
  1718. * is that an unrecoverable error dialog will be displayed.
  1719. * @param {JitsiTrackError} error - The error returned by
  1720. * {@link _createDesktopTrack} Promise.
  1721. * @private
  1722. */
  1723. _handleScreenSharingError(error) {
  1724. if (error.name === JitsiTrackErrors.CHROME_EXTENSION_USER_CANCELED) {
  1725. return;
  1726. }
  1727. logger.error('failed to share local desktop', error);
  1728. if (error.name
  1729. === JitsiTrackErrors.CHROME_EXTENSION_USER_GESTURE_REQUIRED) {
  1730. // If start with screen sharing the extension will fail to install
  1731. // (if not found), because the request has been triggered by the
  1732. // script. Show a dialog which asks user to click "install" and try
  1733. // again switching to the screen sharing.
  1734. APP.UI.showExtensionInlineInstallationDialog(
  1735. () => {
  1736. // eslint-disable-next-line no-empty-function
  1737. this.toggleScreenSharing().catch(() => {});
  1738. }
  1739. );
  1740. return;
  1741. }
  1742. // Handling:
  1743. // JitsiTrackErrors.PERMISSION_DENIED
  1744. // JitsiTrackErrors.CHROME_EXTENSION_INSTALLATION_ERROR
  1745. // JitsiTrackErrors.CONSTRAINT_FAILED
  1746. // JitsiTrackErrors.GENERAL
  1747. // and any other
  1748. let descriptionKey;
  1749. let titleKey;
  1750. if (error.name === JitsiTrackErrors.PERMISSION_DENIED) {
  1751. // in FF the only option for user is to deny access temporary or
  1752. // permanently and we only receive permission_denied
  1753. // we always show some info cause in case of permanently, no info
  1754. // shown will be bad experience
  1755. //
  1756. // TODO: detect interval between requesting permissions and received
  1757. // error, this way we can detect user interaction which will have
  1758. // longer delay
  1759. if (JitsiMeetJS.util.browser.isFirefox()) {
  1760. descriptionKey
  1761. = 'dialog.screenSharingFirefoxPermissionDeniedError';
  1762. titleKey = 'dialog.screenSharingFirefoxPermissionDeniedTitle';
  1763. } else {
  1764. descriptionKey = 'dialog.screenSharingPermissionDeniedError';
  1765. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1766. }
  1767. } else if (error.name === JitsiTrackErrors.CONSTRAINT_FAILED) {
  1768. descriptionKey = 'dialog.cameraConstraintFailedError';
  1769. titleKey = 'deviceError.cameraError';
  1770. } else {
  1771. descriptionKey = 'dialog.screenSharingFailedToInstall';
  1772. titleKey = 'dialog.screenSharingFailedToInstallTitle';
  1773. }
  1774. APP.UI.messageHandler.showError({
  1775. descriptionKey,
  1776. titleKey
  1777. });
  1778. },
  1779. /**
  1780. * Setup interaction between conference and UI.
  1781. */
  1782. _setupListeners() {
  1783. // add local streams when joined to the conference
  1784. room.on(JitsiConferenceEvents.CONFERENCE_JOINED, () => {
  1785. this._onConferenceJoined();
  1786. });
  1787. room.on(
  1788. JitsiConferenceEvents.CONFERENCE_LEFT,
  1789. (...args) => {
  1790. APP.store.dispatch(conferenceTimestampChanged(0));
  1791. APP.store.dispatch(conferenceLeft(room, ...args));
  1792. });
  1793. room.on(
  1794. JitsiConferenceEvents.AUTH_STATUS_CHANGED,
  1795. (authEnabled, authLogin) =>
  1796. APP.store.dispatch(authStatusChanged(authEnabled, authLogin)));
  1797. room.on(JitsiConferenceEvents.PARTCIPANT_FEATURES_CHANGED,
  1798. user => APP.UI.onUserFeaturesChanged(user));
  1799. room.on(JitsiConferenceEvents.USER_JOINED, (id, user) => {
  1800. // The logic shared between RN and web.
  1801. commonUserJoinedHandling(APP.store, room, user);
  1802. if (user.isHidden()) {
  1803. return;
  1804. }
  1805. logger.log(`USER ${id} connnected:`, user);
  1806. APP.UI.addUser(user);
  1807. });
  1808. room.on(JitsiConferenceEvents.USER_LEFT, (id, user) => {
  1809. // The logic shared between RN and web.
  1810. commonUserLeftHandling(APP.store, room, user);
  1811. if (user.isHidden()) {
  1812. return;
  1813. }
  1814. logger.log(`USER ${id} LEFT:`, user);
  1815. APP.UI.onSharedVideoStop(id);
  1816. });
  1817. room.on(JitsiConferenceEvents.USER_STATUS_CHANGED, (id, status) => {
  1818. APP.store.dispatch(participantPresenceChanged(id, status));
  1819. const user = room.getParticipantById(id);
  1820. if (user) {
  1821. APP.UI.updateUserStatus(user, status);
  1822. }
  1823. });
  1824. room.on(JitsiConferenceEvents.USER_ROLE_CHANGED, (id, role) => {
  1825. if (this.isLocalId(id)) {
  1826. logger.info(`My role changed, new role: ${role}`);
  1827. APP.store.dispatch(localParticipantRoleChanged(role));
  1828. APP.API.notifyUserRoleChanged(id, role);
  1829. } else {
  1830. APP.store.dispatch(participantRoleChanged(id, role));
  1831. }
  1832. });
  1833. room.on(JitsiConferenceEvents.TRACK_ADDED, track => {
  1834. if (!track || track.isLocal()) {
  1835. return;
  1836. }
  1837. APP.store.dispatch(trackAdded(track));
  1838. });
  1839. room.on(JitsiConferenceEvents.TRACK_REMOVED, track => {
  1840. if (!track || track.isLocal()) {
  1841. return;
  1842. }
  1843. APP.store.dispatch(trackRemoved(track));
  1844. });
  1845. room.on(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, (id, lvl) => {
  1846. let newLvl = lvl;
  1847. if (this.isLocalId(id)
  1848. && this.localAudio && this.localAudio.isMuted()) {
  1849. newLvl = 0;
  1850. }
  1851. if (config.debug) {
  1852. this.audioLevelsMap[id] = newLvl;
  1853. if (config.debugAudioLevels) {
  1854. logger.log(`AudioLevel:${id}/${newLvl}`);
  1855. }
  1856. }
  1857. APP.UI.setAudioLevel(id, newLvl);
  1858. });
  1859. room.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED, (track, participantThatMutedUs) => {
  1860. if (participantThatMutedUs) {
  1861. APP.store.dispatch(participantMutedUs(participantThatMutedUs));
  1862. }
  1863. });
  1864. room.on(JitsiConferenceEvents.SUBJECT_CHANGED,
  1865. subject => APP.store.dispatch(conferenceSubjectChanged(subject)));
  1866. room.on(
  1867. JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  1868. (leavingIds, enteringIds) =>
  1869. APP.UI.handleLastNEndpoints(leavingIds, enteringIds));
  1870. room.on(
  1871. JitsiConferenceEvents.P2P_STATUS,
  1872. (jitsiConference, p2p) =>
  1873. APP.store.dispatch(p2pStatusChanged(p2p)));
  1874. room.on(
  1875. JitsiConferenceEvents.PARTICIPANT_CONN_STATUS_CHANGED,
  1876. (id, connectionStatus) => APP.store.dispatch(
  1877. participantConnectionStatusChanged(id, connectionStatus)));
  1878. room.on(
  1879. JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED,
  1880. id => APP.store.dispatch(dominantSpeakerChanged(id, room)));
  1881. room.on(
  1882. JitsiConferenceEvents.CONFERENCE_CREATED_TIMESTAMP,
  1883. conferenceTimestamp => APP.store.dispatch(conferenceTimestampChanged(conferenceTimestamp)));
  1884. room.on(JitsiConferenceEvents.CONNECTION_INTERRUPTED, () => {
  1885. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1886. JitsiParticipantConnectionStatus.INTERRUPTED));
  1887. });
  1888. room.on(JitsiConferenceEvents.CONNECTION_RESTORED, () => {
  1889. APP.store.dispatch(localParticipantConnectionStatusChanged(
  1890. JitsiParticipantConnectionStatus.ACTIVE));
  1891. });
  1892. room.on(
  1893. JitsiConferenceEvents.DISPLAY_NAME_CHANGED,
  1894. (id, displayName) => {
  1895. const formattedDisplayName
  1896. = getNormalizedDisplayName(displayName);
  1897. APP.store.dispatch(participantUpdated({
  1898. conference: room,
  1899. id,
  1900. name: formattedDisplayName
  1901. }));
  1902. APP.API.notifyDisplayNameChanged(id, {
  1903. displayName: formattedDisplayName,
  1904. formattedDisplayName:
  1905. appendSuffix(
  1906. formattedDisplayName
  1907. || interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME)
  1908. });
  1909. APP.UI.changeDisplayName(id, formattedDisplayName);
  1910. }
  1911. );
  1912. room.on(
  1913. JitsiConferenceEvents.BOT_TYPE_CHANGED,
  1914. (id, botType) => {
  1915. APP.store.dispatch(participantUpdated({
  1916. conference: room,
  1917. id,
  1918. botType
  1919. }));
  1920. }
  1921. );
  1922. room.on(
  1923. JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED,
  1924. (...args) => {
  1925. APP.store.dispatch(endpointMessageReceived(...args));
  1926. if (args && args.length >= 2) {
  1927. const [ sender, eventData ] = args;
  1928. if (eventData.name === ENDPOINT_TEXT_MESSAGE_NAME) {
  1929. APP.API.notifyEndpointTextMessageReceived({
  1930. senderInfo: {
  1931. jid: sender._jid,
  1932. id: sender._id
  1933. },
  1934. eventData
  1935. });
  1936. }
  1937. }
  1938. });
  1939. room.on(
  1940. JitsiConferenceEvents.LOCK_STATE_CHANGED,
  1941. (...args) => APP.store.dispatch(lockStateChanged(room, ...args)));
  1942. APP.remoteControl.on(RemoteControlEvents.ACTIVE_CHANGED, isActive => {
  1943. room.setLocalParticipantProperty(
  1944. 'remoteControlSessionStatus',
  1945. isActive
  1946. );
  1947. APP.UI.setLocalRemoteControlActiveChanged();
  1948. });
  1949. /* eslint-disable max-params */
  1950. room.on(
  1951. JitsiConferenceEvents.PARTICIPANT_PROPERTY_CHANGED,
  1952. (participant, name, oldValue, newValue) => {
  1953. switch (name) {
  1954. case 'remoteControlSessionStatus':
  1955. APP.UI.setRemoteControlActiveStatus(
  1956. participant.getId(),
  1957. newValue);
  1958. break;
  1959. default:
  1960. // ignore
  1961. }
  1962. });
  1963. room.on(JitsiConferenceEvents.KICKED, participant => {
  1964. APP.UI.hideStats();
  1965. APP.store.dispatch(kickedOut(room, participant));
  1966. // FIXME close
  1967. });
  1968. room.on(JitsiConferenceEvents.PARTICIPANT_KICKED, (kicker, kicked) => {
  1969. APP.store.dispatch(participantKicked(kicker, kicked));
  1970. });
  1971. room.on(JitsiConferenceEvents.SUSPEND_DETECTED, () => {
  1972. APP.store.dispatch(suspendDetected());
  1973. });
  1974. APP.UI.addListener(UIEvents.AUDIO_MUTED, muted => {
  1975. this.muteAudio(muted);
  1976. });
  1977. APP.UI.addListener(UIEvents.VIDEO_MUTED, muted => {
  1978. this.muteVideo(muted);
  1979. });
  1980. room.addCommandListener(this.commands.defaults.ETHERPAD,
  1981. ({ value }) => {
  1982. APP.UI.initEtherpad(value);
  1983. }
  1984. );
  1985. APP.UI.addListener(UIEvents.EMAIL_CHANGED,
  1986. this.changeLocalEmail.bind(this));
  1987. room.addCommandListener(this.commands.defaults.EMAIL, (data, from) => {
  1988. APP.store.dispatch(participantUpdated({
  1989. conference: room,
  1990. id: from,
  1991. email: data.value
  1992. }));
  1993. });
  1994. room.addCommandListener(
  1995. this.commands.defaults.AVATAR_URL,
  1996. (data, from) => {
  1997. APP.store.dispatch(
  1998. participantUpdated({
  1999. conference: room,
  2000. id: from,
  2001. avatarURL: data.value
  2002. }));
  2003. });
  2004. room.addCommandListener(this.commands.defaults.AVATAR_ID,
  2005. (data, from) => {
  2006. APP.store.dispatch(
  2007. participantUpdated({
  2008. conference: room,
  2009. id: from,
  2010. avatarID: data.value
  2011. }));
  2012. });
  2013. APP.UI.addListener(UIEvents.NICKNAME_CHANGED,
  2014. this.changeLocalDisplayName.bind(this));
  2015. room.on(
  2016. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  2017. ({ audio, video }) => {
  2018. APP.store.dispatch(
  2019. onStartMutedPolicyChanged(audio, video));
  2020. }
  2021. );
  2022. room.on(JitsiConferenceEvents.STARTED_MUTED, () => {
  2023. (room.isStartAudioMuted() || room.isStartVideoMuted())
  2024. && APP.UI.notifyInitiallyMuted();
  2025. });
  2026. room.on(
  2027. JitsiConferenceEvents.DATA_CHANNEL_OPENED, () => {
  2028. APP.store.dispatch(dataChannelOpened());
  2029. }
  2030. );
  2031. // call hangup
  2032. APP.UI.addListener(UIEvents.HANGUP, () => {
  2033. this.hangup(true);
  2034. });
  2035. // logout
  2036. APP.UI.addListener(UIEvents.LOGOUT, () => {
  2037. AuthHandler.logout(room).then(url => {
  2038. if (url) {
  2039. UIUtil.redirect(url);
  2040. } else {
  2041. this.hangup(true);
  2042. }
  2043. });
  2044. });
  2045. APP.UI.addListener(UIEvents.AUTH_CLICKED, () => {
  2046. AuthHandler.authenticate(room);
  2047. });
  2048. APP.UI.addListener(
  2049. UIEvents.VIDEO_DEVICE_CHANGED,
  2050. cameraDeviceId => {
  2051. const videoWasMuted = this.isLocalVideoMuted();
  2052. sendAnalytics(createDeviceChangedEvent('video', 'input'));
  2053. // If both screenshare and video are in progress, restart the
  2054. // presenter mode with the new camera device.
  2055. if (this.isSharingScreen && !videoWasMuted) {
  2056. const { height } = this.localVideo.track.getSettings();
  2057. // dispose the existing presenter track and create a new
  2058. // camera track.
  2059. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2060. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2061. this.localPresenterVideo = null;
  2062. return this._createPresenterStreamEffect(height, cameraDeviceId)
  2063. .then(effect => this.localVideo.setEffect(effect))
  2064. .then(() => {
  2065. this.setVideoMuteStatus(false);
  2066. logger.log('switched local video device');
  2067. this._updateVideoDeviceId();
  2068. })
  2069. .catch(err => APP.store.dispatch(notifyCameraError(err)));
  2070. // If screenshare is in progress but video is muted, update the default device
  2071. // id for video, dispose the existing presenter track and create a new effect
  2072. // that can be applied on un-mute.
  2073. } else if (this.isSharingScreen && videoWasMuted) {
  2074. logger.log('switched local video device');
  2075. const { height } = this.localVideo.track.getSettings();
  2076. this._updateVideoDeviceId();
  2077. // FIXME JitsiLocalTrack.dispose is async and should be waited for
  2078. this.localPresenterVideo && this.localPresenterVideo.dispose();
  2079. this.localPresenterVideo = null;
  2080. this._createPresenterStreamEffect(height, cameraDeviceId);
  2081. // if there is only video, switch to the new camera stream.
  2082. } else {
  2083. createLocalTracksF({
  2084. devices: [ 'video' ],
  2085. cameraDeviceId,
  2086. micDeviceId: null
  2087. })
  2088. .then(([ stream ]) => {
  2089. // if we are in audio only mode or video was muted before
  2090. // changing device, then mute
  2091. if (this.isAudioOnly() || videoWasMuted) {
  2092. return stream.mute()
  2093. .then(() => stream);
  2094. }
  2095. return stream;
  2096. })
  2097. .then(stream => this.useVideoStream(stream))
  2098. .then(() => {
  2099. logger.log('switched local video device');
  2100. this._updateVideoDeviceId();
  2101. })
  2102. .catch(err => APP.store.dispatch(notifyCameraError(err)));
  2103. }
  2104. }
  2105. );
  2106. APP.UI.addListener(
  2107. UIEvents.AUDIO_DEVICE_CHANGED,
  2108. micDeviceId => {
  2109. const audioWasMuted = this.isLocalAudioMuted();
  2110. sendAnalytics(createDeviceChangedEvent('audio', 'input'));
  2111. createLocalTracksF({
  2112. devices: [ 'audio' ],
  2113. cameraDeviceId: null,
  2114. micDeviceId
  2115. })
  2116. .then(([ stream ]) => {
  2117. // if audio was muted before changing the device, mute
  2118. // with the new device
  2119. if (audioWasMuted) {
  2120. return stream.mute()
  2121. .then(() => stream);
  2122. }
  2123. return stream;
  2124. })
  2125. .then(async stream => {
  2126. // In case screen sharing audio is also shared we mix it with new input stream. The old _mixerEffect
  2127. // will be cleaned up when the existing track is replaced.
  2128. if (this._mixerEffect) {
  2129. this._mixerEffect = new AudioMixerEffect(this._desktopAudioStream);
  2130. await stream.setEffect(this._mixerEffect);
  2131. }
  2132. return this.useAudioStream(stream);
  2133. })
  2134. .then(() => {
  2135. logger.log(`switched local audio device: ${this.localAudio?.getDeviceId()}`);
  2136. this._updateAudioDeviceId();
  2137. })
  2138. .catch(err => {
  2139. APP.store.dispatch(notifyMicError(err));
  2140. });
  2141. }
  2142. );
  2143. APP.UI.addListener(UIEvents.TOGGLE_AUDIO_ONLY, audioOnly => {
  2144. // FIXME On web video track is stored both in redux and in
  2145. // 'localVideo' field, video is attempted to be unmuted twice when
  2146. // turning off the audio only mode. This will crash the app with
  2147. // 'unmute operation is already in progress'.
  2148. // Because there's no logic in redux about creating new track in
  2149. // case unmute when not track exists the things have to go through
  2150. // muteVideo logic in such case.
  2151. const tracks = APP.store.getState()['features/base/tracks'];
  2152. const isTrackInRedux
  2153. = Boolean(
  2154. tracks.find(
  2155. track => track.jitsiTrack
  2156. && track.jitsiTrack.getType() === 'video'));
  2157. if (!isTrackInRedux) {
  2158. this.muteVideo(audioOnly);
  2159. }
  2160. // Immediately update the UI by having remote videos and the large
  2161. // video update themselves instead of waiting for some other event
  2162. // to cause the update, usually PARTICIPANT_CONN_STATUS_CHANGED.
  2163. // There is no guarantee another event will trigger the update
  2164. // immediately and in all situations, for example because a remote
  2165. // participant is having connection trouble so no status changes.
  2166. APP.UI.updateAllVideos();
  2167. });
  2168. APP.UI.addListener(
  2169. UIEvents.TOGGLE_SCREENSHARING, this.toggleScreenSharing.bind(this)
  2170. );
  2171. /* eslint-disable max-params */
  2172. APP.UI.addListener(
  2173. UIEvents.UPDATE_SHARED_VIDEO,
  2174. (url, state, time, isMuted, volume) => {
  2175. /* eslint-enable max-params */
  2176. // send start and stop commands once, and remove any updates
  2177. // that had left
  2178. if (state === 'stop'
  2179. || state === 'start'
  2180. || state === 'playing') {
  2181. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  2182. room.sendCommandOnce(this.commands.defaults.SHARED_VIDEO, {
  2183. value: url,
  2184. attributes: {
  2185. state,
  2186. time,
  2187. muted: isMuted,
  2188. volume
  2189. }
  2190. });
  2191. } else {
  2192. // in case of paused, in order to allow late users to join
  2193. // paused
  2194. room.removeCommand(this.commands.defaults.SHARED_VIDEO);
  2195. room.sendCommand(this.commands.defaults.SHARED_VIDEO, {
  2196. value: url,
  2197. attributes: {
  2198. state,
  2199. time,
  2200. muted: isMuted,
  2201. volume
  2202. }
  2203. });
  2204. }
  2205. APP.store.dispatch(setSharedVideoStatus(state));
  2206. });
  2207. room.addCommandListener(
  2208. this.commands.defaults.SHARED_VIDEO,
  2209. ({ value, attributes }, id) => {
  2210. if (attributes.state === 'stop') {
  2211. APP.UI.onSharedVideoStop(id, attributes);
  2212. } else if (attributes.state === 'start') {
  2213. APP.UI.onSharedVideoStart(id, value, attributes);
  2214. } else if (attributes.state === 'playing'
  2215. || attributes.state === 'pause') {
  2216. APP.UI.onSharedVideoUpdate(id, value, attributes);
  2217. }
  2218. });
  2219. },
  2220. /**
  2221. * Cleanups local conference on suspend.
  2222. */
  2223. onSuspendDetected() {
  2224. // After wake up, we will be in a state where conference is left
  2225. // there will be dialog shown to user.
  2226. // We do not want video/audio as we show an overlay and after it
  2227. // user need to rejoin or close, while waking up we can detect
  2228. // camera wakeup as a problem with device.
  2229. // We also do not care about device change, which happens
  2230. // on resume after suspending PC.
  2231. if (this.deviceChangeListener) {
  2232. JitsiMeetJS.mediaDevices.removeEventListener(
  2233. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2234. this.deviceChangeListener);
  2235. }
  2236. this.localVideo = null;
  2237. this.localAudio = null;
  2238. },
  2239. /**
  2240. * Callback invoked when the conference has been successfully joined.
  2241. * Initializes the UI and various other features.
  2242. *
  2243. * @private
  2244. * @returns {void}
  2245. */
  2246. _onConferenceJoined() {
  2247. APP.UI.initConference();
  2248. APP.keyboardshortcut.init();
  2249. APP.store.dispatch(conferenceJoined(room));
  2250. const displayName
  2251. = APP.store.getState()['features/base/settings'].displayName;
  2252. APP.UI.changeDisplayName('localVideoContainer', displayName);
  2253. },
  2254. /**
  2255. * Adds any room listener.
  2256. * @param {string} eventName one of the JitsiConferenceEvents
  2257. * @param {Function} listener the function to be called when the event
  2258. * occurs
  2259. */
  2260. addConferenceListener(eventName, listener) {
  2261. room.on(eventName, listener);
  2262. },
  2263. /**
  2264. * Removes any room listener.
  2265. * @param {string} eventName one of the JitsiConferenceEvents
  2266. * @param {Function} listener the listener to be removed.
  2267. */
  2268. removeConferenceListener(eventName, listener) {
  2269. room.off(eventName, listener);
  2270. },
  2271. /**
  2272. * Updates the list of current devices.
  2273. * @param {boolean} setDeviceListChangeHandler - Whether to add the deviceList change handlers.
  2274. * @private
  2275. * @returns {Promise}
  2276. */
  2277. _initDeviceList(setDeviceListChangeHandler = false) {
  2278. const { mediaDevices } = JitsiMeetJS;
  2279. if (mediaDevices.isDeviceListAvailable()
  2280. && mediaDevices.isDeviceChangeAvailable()) {
  2281. if (setDeviceListChangeHandler) {
  2282. this.deviceChangeListener = devices =>
  2283. window.setTimeout(() => this._onDeviceListChanged(devices), 0);
  2284. mediaDevices.addEventListener(
  2285. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2286. this.deviceChangeListener);
  2287. }
  2288. const { dispatch } = APP.store;
  2289. return dispatch(getAvailableDevices())
  2290. .then(devices => {
  2291. // Ugly way to synchronize real device IDs with local
  2292. // storage and settings menu. This is a workaround until
  2293. // getConstraints() method will be implemented in browsers.
  2294. this._updateAudioDeviceId();
  2295. this._updateVideoDeviceId();
  2296. APP.UI.onAvailableDevicesChanged(devices);
  2297. });
  2298. }
  2299. return Promise.resolve();
  2300. },
  2301. /**
  2302. * Updates the settings for the currently used video device, extracting
  2303. * the device id from the used track.
  2304. * @private
  2305. */
  2306. _updateVideoDeviceId() {
  2307. if (this.localVideo
  2308. && this.localVideo.videoType === 'camera') {
  2309. APP.store.dispatch(updateSettings({
  2310. cameraDeviceId: this.localVideo.getDeviceId()
  2311. }));
  2312. }
  2313. // If screenshare is in progress, get the device id from the presenter track.
  2314. if (this.localPresenterVideo) {
  2315. APP.store.dispatch(updateSettings({
  2316. cameraDeviceId: this.localPresenterVideo.getDeviceId()
  2317. }));
  2318. }
  2319. },
  2320. /**
  2321. * Updates the settings for the currently used audio device, extracting
  2322. * the device id from the used track.
  2323. * @private
  2324. */
  2325. _updateAudioDeviceId() {
  2326. if (this.localAudio) {
  2327. APP.store.dispatch(updateSettings({
  2328. micDeviceId: this.localAudio.getDeviceId()
  2329. }));
  2330. }
  2331. },
  2332. /**
  2333. * Event listener for JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED to
  2334. * handle change of available media devices.
  2335. * @private
  2336. * @param {MediaDeviceInfo[]} devices
  2337. * @returns {Promise}
  2338. */
  2339. _onDeviceListChanged(devices) {
  2340. const oldDevices = APP.store.getState()['features/base/devices'].availableDevices;
  2341. APP.store.dispatch(updateDeviceList(devices));
  2342. const newDevices
  2343. = mediaDeviceHelper.getNewMediaDevicesAfterDeviceListChanged(
  2344. devices,
  2345. this.isSharingScreen,
  2346. this.localVideo,
  2347. this.localAudio);
  2348. const promises = [];
  2349. const audioWasMuted = this.isLocalAudioMuted();
  2350. const videoWasMuted = this.isLocalVideoMuted();
  2351. const requestedInput = {
  2352. audio: Boolean(newDevices.audioinput),
  2353. video: Boolean(newDevices.videoinput)
  2354. };
  2355. if (typeof newDevices.audiooutput !== 'undefined') {
  2356. const { dispatch } = APP.store;
  2357. const setAudioOutputPromise
  2358. = setAudioOutputDeviceId(newDevices.audiooutput, dispatch)
  2359. .catch(); // Just ignore any errors in catch block.
  2360. promises.push(setAudioOutputPromise);
  2361. }
  2362. // Handles the use case when the default device is changed (we are always stopping the streams because it's
  2363. // simpler):
  2364. // If the default device is changed we need to first stop the local streams and then call GUM. Otherwise GUM
  2365. // will return a stream using the old default device.
  2366. if (requestedInput.audio && this.localAudio) {
  2367. this.localAudio.stopStream();
  2368. }
  2369. if (requestedInput.video && this.localVideo) {
  2370. this.localVideo.stopStream();
  2371. }
  2372. // Let's handle unknown/non-preferred devices
  2373. const newAvailDevices
  2374. = APP.store.getState()['features/base/devices'].availableDevices;
  2375. let newAudioDevices = [];
  2376. let oldAudioDevices = [];
  2377. if (typeof newDevices.audiooutput === 'undefined') {
  2378. newAudioDevices = newAvailDevices.audioOutput;
  2379. oldAudioDevices = oldDevices.audioOutput;
  2380. }
  2381. if (!requestedInput.audio) {
  2382. newAudioDevices = newAudioDevices.concat(newAvailDevices.audioInput);
  2383. oldAudioDevices = oldAudioDevices.concat(oldDevices.audioInput);
  2384. }
  2385. // check for audio
  2386. if (newAudioDevices.length > 0) {
  2387. APP.store.dispatch(
  2388. checkAndNotifyForNewDevice(newAudioDevices, oldAudioDevices));
  2389. }
  2390. // check for video
  2391. if (!requestedInput.video) {
  2392. APP.store.dispatch(
  2393. checkAndNotifyForNewDevice(newAvailDevices.videoInput, oldDevices.videoInput));
  2394. }
  2395. promises.push(
  2396. mediaDeviceHelper.createLocalTracksAfterDeviceListChanged(
  2397. createLocalTracksF,
  2398. newDevices.videoinput,
  2399. newDevices.audioinput)
  2400. .then(tracks => {
  2401. // If audio or video muted before, or we unplugged current
  2402. // device and selected new one, then mute new track.
  2403. const muteSyncPromises = tracks.map(track => {
  2404. if ((track.isVideoTrack() && videoWasMuted)
  2405. || (track.isAudioTrack() && audioWasMuted)) {
  2406. return track.mute();
  2407. }
  2408. return Promise.resolve();
  2409. });
  2410. return Promise.all(muteSyncPromises)
  2411. .then(() =>
  2412. Promise.all(Object.keys(requestedInput).map(mediaType => {
  2413. if (requestedInput[mediaType]) {
  2414. const useStream
  2415. = mediaType === 'audio'
  2416. ? this.useAudioStream.bind(this)
  2417. : this.useVideoStream.bind(this);
  2418. // Use the new stream or null if we failed to obtain it.
  2419. return useStream(tracks.find(track => track.getType() === mediaType) || null)
  2420. .then(() => {
  2421. mediaType === 'audio'
  2422. ? this._updateAudioDeviceId()
  2423. : this._updateVideoDeviceId();
  2424. });
  2425. }
  2426. return Promise.resolve();
  2427. })));
  2428. })
  2429. .then(() => {
  2430. // Log and sync known mute state.
  2431. if (audioWasMuted) {
  2432. sendAnalytics(createTrackMutedEvent(
  2433. 'audio',
  2434. 'device list changed'));
  2435. logger.log('Audio mute: device list changed');
  2436. muteLocalAudio(true);
  2437. }
  2438. if (!this.isSharingScreen && videoWasMuted) {
  2439. sendAnalytics(createTrackMutedEvent(
  2440. 'video',
  2441. 'device list changed'));
  2442. logger.log('Video mute: device list changed');
  2443. muteLocalVideo(true);
  2444. }
  2445. }));
  2446. return Promise.all(promises)
  2447. .then(() => {
  2448. APP.UI.onAvailableDevicesChanged(devices);
  2449. });
  2450. },
  2451. /**
  2452. * Determines whether or not the audio button should be enabled.
  2453. */
  2454. updateAudioIconEnabled() {
  2455. const audioMediaDevices
  2456. = APP.store.getState()['features/base/devices'].availableDevices.audioInput;
  2457. const audioDeviceCount
  2458. = audioMediaDevices ? audioMediaDevices.length : 0;
  2459. // The audio functionality is considered available if there are any
  2460. // audio devices detected or if the local audio stream already exists.
  2461. const available = audioDeviceCount > 0 || Boolean(this.localAudio);
  2462. APP.store.dispatch(setAudioAvailable(available));
  2463. APP.API.notifyAudioAvailabilityChanged(available);
  2464. },
  2465. /**
  2466. * Determines whether or not the video button should be enabled.
  2467. */
  2468. updateVideoIconEnabled() {
  2469. const videoMediaDevices
  2470. = APP.store.getState()['features/base/devices'].availableDevices.videoInput;
  2471. const videoDeviceCount
  2472. = videoMediaDevices ? videoMediaDevices.length : 0;
  2473. // The video functionality is considered available if there are any
  2474. // video devices detected or if there is local video stream already
  2475. // active which could be either screensharing stream or a video track
  2476. // created before the permissions were rejected (through browser
  2477. // config).
  2478. const available = videoDeviceCount > 0 || Boolean(this.localVideo);
  2479. APP.store.dispatch(setVideoAvailable(available));
  2480. APP.API.notifyVideoAvailabilityChanged(available);
  2481. },
  2482. /**
  2483. * Disconnect from the conference and optionally request user feedback.
  2484. * @param {boolean} [requestFeedback=false] if user feedback should be
  2485. * requested
  2486. */
  2487. hangup(requestFeedback = false) {
  2488. eventEmitter.emit(JitsiMeetConferenceEvents.BEFORE_HANGUP);
  2489. this._stopProxyConnection();
  2490. APP.store.dispatch(destroyLocalTracks());
  2491. this._localTracksInitialized = false;
  2492. this.localVideo = null;
  2493. this.localAudio = null;
  2494. // Remove unnecessary event listeners from firing callbacks.
  2495. if (this.deviceChangeListener) {
  2496. JitsiMeetJS.mediaDevices.removeEventListener(
  2497. JitsiMediaDevicesEvents.DEVICE_LIST_CHANGED,
  2498. this.deviceChangeListener);
  2499. }
  2500. APP.UI.removeAllListeners();
  2501. APP.remoteControl.removeAllListeners();
  2502. let requestFeedbackPromise;
  2503. if (requestFeedback) {
  2504. requestFeedbackPromise
  2505. = APP.store.dispatch(maybeOpenFeedbackDialog(room))
  2506. // false because the thank you dialog shouldn't be displayed
  2507. .catch(() => Promise.resolve(false));
  2508. } else {
  2509. requestFeedbackPromise = Promise.resolve(true);
  2510. }
  2511. // All promises are returning Promise.resolve to make Promise.all to
  2512. // be resolved when both Promises are finished. Otherwise Promise.all
  2513. // will reject on first rejected Promise and we can redirect the page
  2514. // before all operations are done.
  2515. Promise.all([
  2516. requestFeedbackPromise,
  2517. this.leaveRoomAndDisconnect()
  2518. ]).then(values => {
  2519. this._room = undefined;
  2520. room = undefined;
  2521. APP.API.notifyReadyToClose();
  2522. APP.store.dispatch(maybeRedirectToWelcomePage(values[0]));
  2523. });
  2524. },
  2525. /**
  2526. * Leaves the room and calls JitsiConnection.disconnect.
  2527. *
  2528. * @returns {Promise}
  2529. */
  2530. leaveRoomAndDisconnect() {
  2531. APP.store.dispatch(conferenceWillLeave(room));
  2532. if (room && room.isJoined()) {
  2533. return room.leave().then(disconnect, disconnect);
  2534. }
  2535. return disconnect();
  2536. },
  2537. /**
  2538. * Changes the email for the local user
  2539. * @param email {string} the new email
  2540. */
  2541. changeLocalEmail(email = '') {
  2542. const localParticipant = getLocalParticipant(APP.store.getState());
  2543. const formattedEmail = String(email).trim();
  2544. if (formattedEmail === localParticipant.email) {
  2545. return;
  2546. }
  2547. const localId = localParticipant.id;
  2548. APP.store.dispatch(participantUpdated({
  2549. // XXX Only the local participant is allowed to update without
  2550. // stating the JitsiConference instance (i.e. participant property
  2551. // `conference` for a remote participant) because the local
  2552. // participant is uniquely identified by the very fact that there is
  2553. // only one local participant.
  2554. id: localId,
  2555. local: true,
  2556. email: formattedEmail
  2557. }));
  2558. APP.store.dispatch(updateSettings({
  2559. email: formattedEmail
  2560. }));
  2561. APP.API.notifyEmailChanged(localId, {
  2562. email: formattedEmail
  2563. });
  2564. sendData(commands.EMAIL, formattedEmail);
  2565. },
  2566. /**
  2567. * Changes the avatar url for the local user
  2568. * @param url {string} the new url
  2569. */
  2570. changeLocalAvatarUrl(url = '') {
  2571. const { avatarURL, id } = getLocalParticipant(APP.store.getState());
  2572. const formattedUrl = String(url).trim();
  2573. if (formattedUrl === avatarURL) {
  2574. return;
  2575. }
  2576. APP.store.dispatch(participantUpdated({
  2577. // XXX Only the local participant is allowed to update without
  2578. // stating the JitsiConference instance (i.e. participant property
  2579. // `conference` for a remote participant) because the local
  2580. // participant is uniquely identified by the very fact that there is
  2581. // only one local participant.
  2582. id,
  2583. local: true,
  2584. avatarURL: formattedUrl
  2585. }));
  2586. APP.store.dispatch(updateSettings({
  2587. avatarURL: formattedUrl
  2588. }));
  2589. sendData(commands.AVATAR_URL, url);
  2590. },
  2591. /**
  2592. * Sends a message via the data channel.
  2593. * @param {string} to the id of the endpoint that should receive the
  2594. * message. If "" - the message will be sent to all participants.
  2595. * @param {object} payload the payload of the message.
  2596. * @throws NetworkError or InvalidStateError or Error if the operation
  2597. * fails.
  2598. */
  2599. sendEndpointMessage(to, payload) {
  2600. room.sendEndpointMessage(to, payload);
  2601. },
  2602. /**
  2603. * Adds new listener.
  2604. * @param {String} eventName the name of the event
  2605. * @param {Function} listener the listener.
  2606. */
  2607. addListener(eventName, listener) {
  2608. eventEmitter.addListener(eventName, listener);
  2609. },
  2610. /**
  2611. * Removes listener.
  2612. * @param {String} eventName the name of the event that triggers the
  2613. * listener
  2614. * @param {Function} listener the listener.
  2615. */
  2616. removeListener(eventName, listener) {
  2617. eventEmitter.removeListener(eventName, listener);
  2618. },
  2619. /**
  2620. * Changes the display name for the local user
  2621. * @param nickname {string} the new display name
  2622. */
  2623. changeLocalDisplayName(nickname = '') {
  2624. const formattedNickname = getNormalizedDisplayName(nickname);
  2625. const { id, name } = getLocalParticipant(APP.store.getState());
  2626. if (formattedNickname === name) {
  2627. return;
  2628. }
  2629. APP.store.dispatch(participantUpdated({
  2630. // XXX Only the local participant is allowed to update without
  2631. // stating the JitsiConference instance (i.e. participant property
  2632. // `conference` for a remote participant) because the local
  2633. // participant is uniquely identified by the very fact that there is
  2634. // only one local participant.
  2635. id,
  2636. local: true,
  2637. name: formattedNickname
  2638. }));
  2639. APP.store.dispatch(updateSettings({
  2640. displayName: formattedNickname
  2641. }));
  2642. if (room) {
  2643. APP.UI.changeDisplayName(id, formattedNickname);
  2644. }
  2645. },
  2646. /**
  2647. * Returns the desktop sharing source id or undefined if the desktop sharing
  2648. * is not active at the moment.
  2649. *
  2650. * @returns {string|undefined} - The source id. If the track is not desktop
  2651. * track or the source id is not available, undefined will be returned.
  2652. */
  2653. getDesktopSharingSourceId() {
  2654. return this.localVideo.sourceId;
  2655. },
  2656. /**
  2657. * Returns the desktop sharing source type or undefined if the desktop
  2658. * sharing is not active at the moment.
  2659. *
  2660. * @returns {'screen'|'window'|undefined} - The source type. If the track is
  2661. * not desktop track or the source type is not available, undefined will be
  2662. * returned.
  2663. */
  2664. getDesktopSharingSourceType() {
  2665. return this.localVideo.sourceType;
  2666. },
  2667. /**
  2668. * Callback invoked by the external api create or update a direct connection
  2669. * from the local client to an external client.
  2670. *
  2671. * @param {Object} event - The object containing information that should be
  2672. * passed to the {@code ProxyConnectionService}.
  2673. * @returns {void}
  2674. */
  2675. onProxyConnectionEvent(event) {
  2676. if (!this._proxyConnection) {
  2677. this._proxyConnection = new JitsiMeetJS.ProxyConnectionService({
  2678. /**
  2679. * Pass the {@code JitsiConnection} instance which will be used
  2680. * to fetch TURN credentials.
  2681. */
  2682. jitsiConnection: APP.connection,
  2683. /**
  2684. * The proxy connection feature is currently tailored towards
  2685. * taking a proxied video stream and showing it as a local
  2686. * desktop screen.
  2687. */
  2688. convertVideoToDesktop: true,
  2689. /**
  2690. * Callback invoked when the connection has been closed
  2691. * automatically. Triggers cleanup of screensharing if active.
  2692. *
  2693. * @returns {void}
  2694. */
  2695. onConnectionClosed: () => {
  2696. if (this._untoggleScreenSharing) {
  2697. this._untoggleScreenSharing();
  2698. }
  2699. },
  2700. /**
  2701. * Callback invoked to pass messages from the local client back
  2702. * out to the external client.
  2703. *
  2704. * @param {string} peerJid - The jid of the intended recipient
  2705. * of the message.
  2706. * @param {Object} data - The message that should be sent. For
  2707. * screensharing this is an iq.
  2708. * @returns {void}
  2709. */
  2710. onSendMessage: (peerJid, data) =>
  2711. APP.API.sendProxyConnectionEvent({
  2712. data,
  2713. to: peerJid
  2714. }),
  2715. /**
  2716. * Callback invoked when the remote peer of the proxy connection
  2717. * has provided a video stream, intended to be used as a local
  2718. * desktop stream.
  2719. *
  2720. * @param {JitsiLocalTrack} remoteProxyStream - The media
  2721. * stream to use as a local desktop stream.
  2722. * @returns {void}
  2723. */
  2724. onRemoteStream: desktopStream => {
  2725. if (desktopStream.videoType !== 'desktop') {
  2726. logger.warn('Received a non-desktop stream to proxy.');
  2727. desktopStream.dispose();
  2728. return;
  2729. }
  2730. this.toggleScreenSharing(undefined, { desktopStream });
  2731. }
  2732. });
  2733. }
  2734. this._proxyConnection.processMessage(event);
  2735. },
  2736. /**
  2737. * Sets the video muted status.
  2738. *
  2739. * @param {boolean} muted - New muted status.
  2740. */
  2741. setVideoMuteStatus(muted) {
  2742. APP.UI.setVideoMuted(this.getMyUserId(), muted);
  2743. APP.API.notifyVideoMutedStatusChanged(muted);
  2744. },
  2745. /**
  2746. * Sets the audio muted status.
  2747. *
  2748. * @param {boolean} muted - New muted status.
  2749. */
  2750. setAudioMuteStatus(muted) {
  2751. APP.UI.setAudioMuted(this.getMyUserId(), muted);
  2752. APP.API.notifyAudioMutedStatusChanged(muted);
  2753. },
  2754. /**
  2755. * Dispatches the passed in feedback for submission. The submitted score
  2756. * should be a number inclusively between 1 through 5, or -1 for no score.
  2757. *
  2758. * @param {number} score - a number between 1 and 5 (inclusive) or -1 for no
  2759. * score.
  2760. * @param {string} message - An optional message to attach to the feedback
  2761. * in addition to the score.
  2762. * @returns {void}
  2763. */
  2764. submitFeedback(score = -1, message = '') {
  2765. if (score === -1 || (score >= 1 && score <= 5)) {
  2766. APP.store.dispatch(submitFeedback(score, message, room));
  2767. }
  2768. },
  2769. /**
  2770. * Terminates any proxy screensharing connection that is active.
  2771. *
  2772. * @private
  2773. * @returns {void}
  2774. */
  2775. _stopProxyConnection() {
  2776. if (this._proxyConnection) {
  2777. this._proxyConnection.stop();
  2778. }
  2779. this._proxyConnection = null;
  2780. }
  2781. };