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

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