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

conference.js 93KB

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