Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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