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

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