You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 109KB

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