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 92KB

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