Skip to content

Commit

Permalink
fix: config getters
Browse files Browse the repository at this point in the history
  • Loading branch information
TurtIeSocks committed Feb 8, 2024
1 parent 56eb47e commit 494639a
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 93 deletions.
16 changes: 9 additions & 7 deletions server/src/routes/api/v1/config.js
Original file line number Diff line number Diff line change
@@ -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
: [],
},
Expand Down
45 changes: 22 additions & 23 deletions server/src/routes/rootRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(),
Expand All @@ -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(
Expand All @@ -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) {
Expand All @@ -202,31 +204,28 @@ 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 ||
settings.user.perms.lures)
) {
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()
}
}
Expand Down
64 changes: 17 additions & 47 deletions server/src/services/api/scannerApi.js
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -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'),
Expand Down Expand Up @@ -84,7 +53,7 @@ async function scannerApi(

const timeout = setTimeout(() => {
controller.abort()
}, config.api.fetchTimeoutMs)
}, config.getSafe('api.fetchTimeoutMs'))

const coords =
backendConfig.platform === 'mad'
Expand Down Expand Up @@ -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 },
})
Expand All @@ -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 },
})
Expand Down Expand Up @@ -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 },
})
Expand Down Expand Up @@ -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 },
})
Expand Down Expand Up @@ -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`,
Expand All @@ -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,
},
Expand Down Expand Up @@ -454,23 +424,23 @@ 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' }
case 416:
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' }
case 500:
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' }
Expand Down
38 changes: 22 additions & 16 deletions server/src/services/functions/getServerSettings.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-check
const config = require('@rm/config')

const clientOptions = require('../ui/clientOptions')
Expand All @@ -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,
Expand Down

0 comments on commit 494639a

Please sign in to comment.