From 494639a28289fac90e0898cf2d443ba7a2c5c41d Mon Sep 17 00:00:00 2001 From: Derick M <58572875+TurtIeSocks@users.noreply.github.com> Date: Thu, 8 Feb 2024 11:35:30 -0500 Subject: [PATCH] fix: config getters --- server/src/routes/api/v1/config.js | 16 +++-- server/src/routes/rootRouter.js | 45 +++++++------ server/src/services/api/scannerApi.js | 64 +++++-------------- .../services/functions/getServerSettings.js | 38 ++++++----- 4 files changed, 70 insertions(+), 93 deletions(-) diff --git a/server/src/routes/api/v1/config.js b/server/src/routes/api/v1/config.js index 372209d88..b246f21cd 100644 --- a/server/src/routes/api/v1/config.js +++ b/server/src/routes/api/v1/config.js @@ -1,29 +1,31 @@ +// @ts-check const path = require('path') const router = require('express').Router() const config = require('@rm/config') const { log, HELPERS } = require('@rm/logger') +const api = config.getSafe('api') + router.get('/', (req, res) => { try { if ( - config.api.reactMapSecret && - req.headers['react-map-secret'] === config.api.reactMapSecret + api.reactMapSecret && + req.headers['react-map-secret'] === api.reactMapSecret ) { res.status(200).json({ + ...config, api: { - ...config.api, + ...api, reactMapSecret: undefined, }, ...config, database: { ...config.database, - schemas: config.api.showSchemasInConfigApi - ? config.database.schemas - : [], + schemas: api.showSchemasInConfigApi ? config.database.schemas : [], }, authentication: { ...config.authentication, - strategies: config.api.showStrategiesInConfigApi + strategies: api.showStrategiesInConfigApi ? config.authentication.strategies : [], }, diff --git a/server/src/routes/rootRouter.js b/server/src/routes/rootRouter.js index 4cafdaac2..98f08a54c 100644 --- a/server/src/routes/rootRouter.js +++ b/server/src/routes/rootRouter.js @@ -11,6 +11,9 @@ const { version } = require('../../../package.json') const areaPerms = require('../services/functions/areaPerms') const getServerSettings = require('../services/functions/getServerSettings') +const scanner = config.getSafe('scanner') +const api = config.getSafe('api') + const rootRouter = express.Router() rootRouter.use('/', clientRouter) @@ -116,10 +119,7 @@ rootRouter.post('/api/error/client', async (req, res) => { rootRouter.get('/area/:area/:zoom?', (req, res) => { const { area, zoom } = req.params try { - const { scanAreas } = config.areas - const validScanAreas = scanAreas[req.headers.host.replaceAll('.', '_')] - ? scanAreas[req.headers.host.replaceAll('.', '_')] - : scanAreas.main + const validScanAreas = config.getAreas(req, 'scanAreas') if (validScanAreas.features.length) { const foundArea = validScanAreas.features.find( (a) => a.properties.name.toLowerCase() === area.toLowerCase(), @@ -137,30 +137,32 @@ rootRouter.get('/area/:area/:zoom?', (req, res) => { }) rootRouter.get('/api/settings', async (req, res, next) => { + const authentication = config.getSafe('authentication') + const mapConfig = config.getMapConfig(req) try { if ( - config.authentication.alwaysEnabledPerms.length || - !config.authentication.methods.length + authentication.alwaysEnabledPerms.length || + !authentication.methods.length ) { if (req.session.tutorial === undefined) { - req.session.tutorial = !config.map.forceTutorial + req.session.tutorial = !mapConfig.forceTutorial } req.session.perms = { ...Object.fromEntries( - Object.keys(config.authentication.perms).map((p) => [p, false]), + Object.keys(authentication.perms).map((p) => [p, false]), ), areaRestrictions: areaPerms(['none']), webhooks: [], - scanner: Object.keys(config.scanner).filter( + scanner: Object.keys(scanner).filter( (key) => key !== 'backendConfig' && - config.scanner[key].enabled && - !config.scanner[key].discordRoles.length && - !config.scanner[key].telegramGroups.length, + scanner[key].enabled && + !scanner[key].discordRoles.length && + !scanner[key].telegramGroups.length, ), } - config.authentication.alwaysEnabledPerms.forEach((perm) => { - if (config.authentication.perms[perm]) { + authentication.alwaysEnabledPerms.forEach((perm) => { + if (authentication.perms[perm]) { req.session.perms[perm] = true } else { log.warn( @@ -175,7 +177,7 @@ rootRouter.get('/api/settings', async (req, res, next) => { } req.session.save() - if (config.authentication.methods.length && req.user) { + if (authentication.methods.length && req.user) { try { const user = await Db.query('User', 'getOne', req.user.id) if (user) { @@ -202,20 +204,17 @@ rootRouter.get('/api/settings', async (req, res, next) => { const settings = getServerSettings(req) if ('perms' in settings.user) { - if ( - settings.user.perms.pokemon && - config.api.queryOnSessionInit.pokemon - ) { + if (settings.user.perms.pokemon && api.queryOnSessionInit.pokemon) { Event.setAvailable('pokemon', 'Pokemon', Db, false) } if ( - config.api.queryOnSessionInit.raids && + api.queryOnSessionInit.raids && (settings.user.perms.raids || settings.user.perms.gyms) ) { Event.setAvailable('gyms', 'Gym', Db, false) } if ( - config.api.queryOnSessionInit.quests && + api.queryOnSessionInit.quests && (settings.user.perms.quests || settings.user.perms.pokestops || settings.user.perms.invasions || @@ -223,10 +222,10 @@ rootRouter.get('/api/settings', async (req, res, next) => { ) { Event.setAvailable('pokestops', 'Pokestop', Db, false) } - if (settings.user.perms.nests && config.api.queryOnSessionInit.nests) { + if (settings.user.perms.nests && api.queryOnSessionInit.nests) { Event.setAvailable('nests', 'Nest', Db, false) } - if (Object.values(config.api.queryOnSessionInit).some(Boolean)) { + if (Object.values(api.queryOnSessionInit).some(Boolean)) { Event.addAvailable() } } diff --git a/server/src/services/api/scannerApi.js b/server/src/services/api/scannerApi.js index 38053d748..e72b8ae88 100644 --- a/server/src/services/api/scannerApi.js +++ b/server/src/services/api/scannerApi.js @@ -1,11 +1,10 @@ // @ts-check const { default: fetch } = require('node-fetch') -const NodeCache = require('node-cache') const config = require('@rm/config') const { log, HELPERS } = require('@rm/logger') -const { getCache, setCache } = require('../cache') +const { userCache } = require('../initialization') const Clients = require('../Clients') const TelegramClient = require('../TelegramClient') const DiscordClient = require('../DiscordClient') @@ -15,37 +14,7 @@ const scannerQueue = { scanZone: {}, } -const userCache = new NodeCache({ stdTTL: 60 * 60 * 24 }) - -const onShutdown = async () => { - const cacheObj = {} - userCache.keys().forEach((key) => { - cacheObj[key] = userCache.get(key) - }) - await setCache('scanUserHistory.json', cacheObj) -} -process.on('SIGINT', async () => { - await onShutdown() - process.exit(0) -}) -process.on('SIGTERM', async () => { - await onShutdown() - process.exit(0) -}) -process.on('SIGUSR1', async () => { - await onShutdown() - process.exit(0) -}) -process.on('SIGUSR2', async () => { - await onShutdown() - process.exit(0) -}) - -Object.entries(getCache('scanUserHistory.json', {})).forEach(([k, v]) => - userCache.set(k, v), -) - -const backendConfig = config.getSafe('scanner.backendConfig') +const { backendConfig, ...scanModes } = config.getSafe('scanner') const scanNextOptions = { routes: config.getSafe('scanner.scanNext.routes'), @@ -84,7 +53,7 @@ async function scannerApi( const timeout = setTimeout(() => { controller.abort() - }, config.api.fetchTimeoutMs) + }, config.getSafe('api.fetchTimeoutMs')) const coords = backendConfig.platform === 'mad' @@ -161,9 +130,9 @@ async function scannerApi( url: `${ backendConfig.apiEndpoint }/send_gps?origin=${encodeURIComponent( - config.scanner.scanNext.scanNextDevice, + scanModes.scanNext.scanNextDevice, )}&coords=${JSON.stringify(coords)}&sleeptime=${ - config.scanner.scanNext.scanNextSleeptime + scanModes.scanNext.scanNextSleeptime }`, options: { method, headers }, }) @@ -173,7 +142,7 @@ async function scannerApi( url: `${ backendConfig.apiEndpoint }/set_data?scan_next=true&instance=${encodeURIComponent( - config.scanner.scanNext.scanNextInstance, + scanModes.scanNext.scanNextInstance, )}&coords=${JSON.stringify(coords)}`, options: { method, headers }, }) @@ -249,7 +218,7 @@ async function scannerApi( url: `${ backendConfig.apiEndpoint }/set_data?scan_next=true&instance=${encodeURIComponent( - config.scanner.scanZone.scanZoneInstance, + scanModes.scanZone.scanZoneInstance, )}&coords=${JSON.stringify(coords)}`, options: { method, headers }, }) @@ -283,7 +252,7 @@ async function scannerApi( url: `${backendConfig.apiEndpoint}/get_data?${ data.type }=true&queue_size=true&instance=${encodeURIComponent( - config.scanner[data.typeName][`${data.typeName}Instance`], + scanModes[data.typeName][`${data.typeName}Instance`], )}`, options: { method, headers }, }) @@ -395,9 +364,10 @@ async function scannerApi( }, thumbnail: { url: - config.authentication.strategies.find( - (strategy) => strategy.name === user.rmStrategy, - )?.thumbnailUrl ?? + config + .getSafe('authentication.strategies') + .find((strategy) => strategy.name === user.rmStrategy) + ?.thumbnailUrl ?? `https://user-images.githubusercontent.com/58572875/167069223-745a139d-f485-45e3-a25c-93ec4d09779c.png`, }, description: `<@${user.discordId}>\n${capitalized} Size: ${data.scanSize}\nCoordinates: ${coords.length}\n`, @@ -413,10 +383,10 @@ async function scannerApi( name: 'Instance', value: `${ backendConfig.platform === 'mad' - ? `Device: ${config.scanner.scanNext.scanNextDevice}` + ? `Device: ${scanModes.scanNext.scanNextDevice}` : '' }\nName: ${ - config.scanner[category]?.[`${category}Instance`] || '-' + scanModes[category]?.[`${category}Instance`] || '-' }\nQueue: ${scannerQueue[category]?.queue || 0}`, inline: true, }, @@ -454,7 +424,7 @@ async function scannerApi( log.info( HELPERS.scanner, `Error: instance ${ - config.scanner[category]?.[`${category}Instance`] + scanModes[category]?.[`${category}Instance`] } does not exist`, ) return { status: 'error', message: 'scanner_no_instance' } @@ -462,7 +432,7 @@ async function scannerApi( log.info( HELPERS.scanner, `Error: instance ${ - config.scanner[category]?.[`${category}Instance`] + scanModes[category]?.[`${category}Instance`] } has no device assigned`, ) return { status: 'error', message: 'scanner_no_device_assigned' } @@ -470,7 +440,7 @@ async function scannerApi( log.info( HELPERS.scanner, `Error: device ${ - config.scanner[category]?.[`${category}Device`] + scanModes[category]?.[`${category}Device`] } does not exist`, ) return { status: 'error', message: 'scanner_no_device' } diff --git a/server/src/services/functions/getServerSettings.js b/server/src/services/functions/getServerSettings.js index 7acf10629..0761721e8 100644 --- a/server/src/services/functions/getServerSettings.js +++ b/server/src/services/functions/getServerSettings.js @@ -1,3 +1,4 @@ +// @ts-check const config = require('@rm/config') const clientOptions = require('../ui/clientOptions') @@ -17,43 +18,48 @@ function getServerSettings(req) { const { clientValues, clientMenus } = clientOptions(user.perms) - const validConfig = config.getMapConfig(req) + const mapConfig = config.getMapConfig(req) + const api = config.getSafe('api') + const authentication = config.getSafe('authentication') + const database = config.getSafe('database') + const serverSettings = { api: { - polling: config.api.polling, - gymValidDataLimit: - Date.now() / 1000 - config.api.gymValidDataLimit * 86400, + polling: api.polling, + gymValidDataLimit: Date.now() / 1000 - api.gymValidDataLimit * 86400, }, user, authReferences: { - areaRestrictions: config.authentication.areaRestrictions.length, - webhooks: config.webhooks.filter((w) => w.enabled).length, - scanner: Object.values(config.scanner).filter((s) => s.enabled).length, + areaRestrictions: authentication.areaRestrictions.length, + webhooks: config.getSafe('webhooks').filter((w) => w.enabled).length, + scanner: Object.values(config.getSafe('scanner')).filter( + (s) => 'enabled' in s && s.enabled, + ).length, }, map: { - ...validConfig, + ...mapConfig, general: { - ...validConfig.general, + ...mapConfig.general, geoJsonFileName: undefined, }, - loginPage: !!config.map.loginPage.components.length, + loginPage: !!mapConfig.loginPage.components.length, donationPage: undefined, messageOfTheDay: undefined, customFloatingIcons: undefined, }, authentication: { loggedIn: !!req.user, - excludeList: config.authentication.excludeFromTutorial, - methods: config.authentication.methods, + excludeList: authentication.excludeFromTutorial, + methods: authentication.methods, }, database: { settings: { - extraUserFields: config.database.settings.extraUserFields, - userBackupLimits: config.database.settings.userBackupLimits, + extraUserFields: database.settings.extraUserFields, + userBackupLimits: database.settings.userBackupLimits, }, }, - tileServers: config.tileServers, - navigation: config.navigation, + tileServers: config.getSafe('tileServers'), + navigation: config.getSafe('navigation'), menus: advMenus(), userSettings: clientValues, clientMenus,