Skip to content

Commit

Permalink
refactor: scan on demand backend
Browse files Browse the repository at this point in the history
  • Loading branch information
TurtIeSocks committed Jan 26, 2024
1 parent 72c6d52 commit 5b178b6
Show file tree
Hide file tree
Showing 12 changed files with 305 additions and 190 deletions.
17 changes: 17 additions & 0 deletions packages/types/lib/general.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,20 @@ export interface RMSliderProps {
values: number[]
handleChange: RMSliderHandleChange
}

export type ScanTypes = 'scanNext' | 'scanZone'

export interface ScanOnDemandData {
typeName: ScanTypes
type: 'scan_next'
scanCoords?: [number, number][]
scanLocation?: [number, number]
scanSize?: number
cooldown?: number
}

export interface ScanOnDemandReq {
category: ScanTypes | 'getQueue'
method: HttpMethod
data?: ScanOnDemandData
}
2 changes: 1 addition & 1 deletion packages/types/lib/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export interface GqlContext {
user: string
transaction: Transaction
operation: 'query' | 'mutation'
startTime: number
startTime?: number
}

export interface Permissions {
Expand Down
7 changes: 5 additions & 2 deletions server/src/configs/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -595,13 +595,14 @@
},
"scanner": {
"backendConfig": {
"platform": "rdm/mad",
"platform": "rdm/mad/custom",
"apiEndpoint": "http://ip:port/api/",
"headers": [],
"apiUsername": "username",
"apiPassword": "password",
"queueRefreshInterval": 5,
"sendDiscordMessage": true
"sendDiscordMessage": true,
"sendTelegramMessage": true
},
"scanNext": {
"enabled": false,
Expand Down Expand Up @@ -681,6 +682,8 @@
{
"name": "telegram",
"type": "telegram",
"scanNextLogChannelId": "",
"scanZoneLogChannelId": "",
"enabled": false,
"botToken": "",
"groups": [],
Expand Down
51 changes: 25 additions & 26 deletions server/src/graphql/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ const config = require('@rm/config')

const buildDefaultFilters = require('../services/filters/builder/base')
const filterComponents = require('../services/functions/filterComponents')
const { filterRTree } = require('../services/functions/filterRTree')
const validateSelectedWebhook = require('../services/functions/validateSelectedWebhook')
const PoracleAPI = require('../services/api/Poracle')
const { geocoder } = require('../services/geocoder')
const scannerApi = require('../services/api/scannerApi')
const getPolyVector = require('../services/functions/getPolyVector')
const getPlacementCells = require('../services/functions/getPlacementCells')
const getTypeCells = require('../services/functions/getTypeCells')
const { getValidCoords } = require('../services/functions/getValidCoords')

/** @type {import("@apollo/server").ApolloServerOptions<import("@rm/types").GqlContext>['resolvers']} */
const resolvers = {
Expand Down Expand Up @@ -106,22 +106,8 @@ const resolvers = {
return !!results.length
},
/** @param {unknown} _ @param {{ mode: 'scanNext' | 'scanZone' }} args */
checkValidScan: (_, { mode, points }, { perms }) => {
if (perms?.scanner.includes(mode)) {
const areaRestrictions =
config.getSafe(`scanner.${mode}.${mode}AreaRestriction`) || []

const validPoints = points.map((point) =>
filterRTree(
{ lat: point[0], lon: point[1] },
perms.areaRestrictions,
areaRestrictions,
),
)
return validPoints
}
return []
},
checkValidScan: (_, { mode, points }, { perms }) =>
getValidCoords(mode, points, perms),
/** @param {unknown} _ @param {{ component: 'loginPage' | 'donationPage' | 'messageOfTheDay' }} args */
customComponent: (_, { component }, { perms, req, user }) => {
switch (component) {
Expand Down Expand Up @@ -598,20 +584,33 @@ const resolvers = {
}
return {}
},
/** @param {unknown} _ @param {import('@rm/types').ScanOnDemandReq} args */
scanner: (_, args, { req, perms }) => {
const { category, method, data } = args
if (data?.cooldown) {
req.session.cooldown = Math.max(
req.session.cooldown || 0,
data.cooldown || 0,
)
req.session.save()
}
if (category === 'getQueue') {
return scannerApi(category, method, data, req?.user)
}
if (perms?.scanner?.includes(category)) {
return scannerApi(category, method, data, req?.user)
if (
perms?.scanner?.includes(category) &&
(!req.session.cooldown || req.session.cooldown < Date.now())
) {
const validCoords = getValidCoords(category, data?.scanCoords, perms)

const cooldown =
config.getSafe(`scanner.${category}.userCooldownSeconds`) *
validCoords.filter(Boolean).length *
1000 +
Date.now()
req.session.cooldown = cooldown
return scannerApi(
category,
method,
{
...data,
scanCoords: data.scanCoords?.filter((__, i) => validCoords[i]),
},
req?.user,
)
}
return {}
},
Expand Down
7 changes: 4 additions & 3 deletions server/src/graphql/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async function startApollo(httpServer) {
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
introspection: config.getSafe('devOptions.enabled'),
introspection: config.getSafe('devOptions.graphiql'),
formatError: (e) => {
let customMessage = ''
if (
Expand Down Expand Up @@ -80,8 +80,9 @@ async function startApollo(httpServer) {
{
async requestDidStart(requestContext) {
requestContext.contextValue.startTime = Date.now()

log.debug(requestContext.request?.variables?.filters)
if (requestContext.request?.variables?.filters) {
log.debug(requestContext.request?.variables?.filters)
}
return {
async willSendResponse(context) {
const filterCount = Object.keys(
Expand Down
9 changes: 4 additions & 5 deletions server/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,8 @@ if (sentry.enabled || process.env.SENTRY_DSN) {
...Sentry.autoDiscoverNodePerformanceMonitoringIntegrations(),
],
tracesSampleRate:
parseFloat(
process.env.SENTRY_TRACES_SAMPLE_RATE || sentry.tracesSampleRate,
) || 0.1,
+(process.env.SENTRY_TRACES_SAMPLE_RATE || sentry.tracesSampleRate) ||
0.1,
release: pkg.version,
})

Expand Down Expand Up @@ -215,10 +214,10 @@ app.use((err, req, res, next) => {
startApollo(httpServer).then((server) => {
app.use(
'/graphql',
cors(),
cors({ origin: '/' }),
json(),
expressMiddleware(server, {
context: ({ req, res }) => {
context: async ({ req, res }) => {
const perms = req.user ? req.user.perms : req.session.perms
const user = req?.user?.username || ''
const id = req?.user?.id || 0
Expand Down
5 changes: 4 additions & 1 deletion server/src/services/DiscordClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ class DiscordClient {
}
}

/** @param {import('discord.js').APIEmbed} embed @param {string} channel */
/**
* @param {import('discord.js').APIEmbed} embed
* @param {keyof DiscordClient['loggingChannels']} channel
*/
async sendMessage(embed, channel = 'main') {
const safeChannel = this.loggingChannels[channel]
if (!safeChannel || typeof embed !== 'object') {
Expand Down
45 changes: 45 additions & 0 deletions server/src/services/TelegramClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ class TelegramClient {
this.alwaysEnabledPerms = config.getSafe(
'authentication.alwaysEnabledPerms',
)
this.loggingChannels = {
main: strategy.logChannelId,
event: strategy.eventLogChannelId,
scanNext: strategy.scanNextLogChannelId,
scanZone: strategy.scanZoneLogChannelId,
}
}

/** @param {TGUser} user */
Expand Down Expand Up @@ -194,6 +200,45 @@ class TelegramClient {
}
}

/**
*
* @param {string} text
* @param {keyof TelegramClient['loggingChannels']} channel
*/
async sendMessage(text, channel = 'main') {
if (!this.loggingChannels[channel]) return
try {
const response = await fetch(
`https://api.telegram.org/bot${this.strategy.botToken}/sendMessage`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: this.loggingChannels[channel],
parse_mode: 'HTML',
disable_web_page_preview: true,
text,
}),
},
)
if (!response.ok) {
throw new Error(
`Telegram API error: ${response.status} ${response.statusText}`,
)
}
log.info(
HELPERS.custom(this.rmStrategy, '#26A8EA'),
`${channel} Log Sent`,
)
} catch (e) {
log.error(
HELPERS.custom(this.rmStrategy, '#26A8EA'),
`Error sending ${channel} Log`,
e,
)
}
}

initPassport() {
passport.use(
this.rmStrategy,
Expand Down
Loading

0 comments on commit 5b178b6

Please sign in to comment.