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

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