You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

conference.js 93KB

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