Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

conference.js 92KB

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