您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conference.js 92KB

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