Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

conference.js 92KB

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