mirror of
https://github.com/ReVanced/revanced-bots.git
synced 2026-01-25 20:21:02 +00:00
chore: format and remove unneccessary code
This commit is contained in:
@@ -141,7 +141,7 @@ export default class Client {
|
||||
this.#emitter.emit('packet', packet)
|
||||
this.#emitter.emit(
|
||||
uncapitalize(ClientOperation[packet.op] as ClientEventName),
|
||||
// @ts-expect-error
|
||||
// @ts-expect-error TypeScript doesn't know that the above line will negate the type enough
|
||||
packet
|
||||
)
|
||||
} catch (e) {
|
||||
@@ -181,7 +181,7 @@ export default class Client {
|
||||
this.once('heartbeat', () => clearTimeout(interval))
|
||||
// This should never happen but it did in my testing so I'm adding this just in case
|
||||
this.once('disconnect', () => clearTimeout(interval))
|
||||
// Technically we don't have to do this, but JUST IN CASE!
|
||||
// Technically we don't have to do this, but JUST IN CASE!
|
||||
} else this.#hbTimeout.refresh()
|
||||
}, this.heartbeatInterval)
|
||||
}
|
||||
|
||||
@@ -8,10 +8,13 @@ import type { Worker as TesseractWorker } from 'tesseract.js'
|
||||
export { default as parseTextEventHandler } from './parseText.js'
|
||||
export { default as parseImageEventHandler } from './parseImage.js'
|
||||
|
||||
export type EventHandler<POp extends ClientOperation> = (packet: ClientPacketObject<POp>, context: EventContext) => void | Promise<void>
|
||||
export type EventHandler<POp extends ClientOperation> = (
|
||||
packet: ClientPacketObject<POp>,
|
||||
context: EventContext
|
||||
) => void | Promise<void>
|
||||
export type EventContext = {
|
||||
witClient: Wit
|
||||
tesseractWorker: TesseractWorker
|
||||
logger: Logger
|
||||
config: Config
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,150 +1,157 @@
|
||||
import { fastify } from 'fastify'
|
||||
import fastifyWebsocket from '@fastify/websocket'
|
||||
|
||||
import { createWorker as createTesseractWorker } from 'tesseract.js'
|
||||
import witPkg from 'node-wit'
|
||||
const { Wit } = witPkg
|
||||
|
||||
import { inspect as inspectObject } from 'node:util'
|
||||
|
||||
import Client from './classes/Client.js'
|
||||
|
||||
import {
|
||||
EventContext,
|
||||
parseImageEventHandler,
|
||||
parseTextEventHandler,
|
||||
} from './events/index.js'
|
||||
|
||||
import { getConfig, checkEnv, logger } from './utils/index.js'
|
||||
import { WebSocket } from 'ws'
|
||||
import { DisconnectReason, HumanizedDisconnectReason } from '@revanced/bot-shared'
|
||||
|
||||
// Load environment variables and config
|
||||
|
||||
(async () => {
|
||||
|
||||
const environment = checkEnv(logger)
|
||||
const config = getConfig()
|
||||
|
||||
if (!config.debugLogsInProduction && environment === 'production') logger.debug = () => {}
|
||||
|
||||
// Workers and API clients
|
||||
|
||||
const tesseractWorker = await createTesseractWorker('eng')
|
||||
const witClient = new Wit({
|
||||
accessToken: process.env['WIT_AI_TOKEN']!,
|
||||
})
|
||||
|
||||
process.on('beforeExit', () => tesseractWorker.terminate())
|
||||
|
||||
// Server logic
|
||||
|
||||
const clients = new Set<Client>()
|
||||
const clientSocketMap = new WeakMap<WebSocket, Client>()
|
||||
const eventContext: EventContext = {
|
||||
tesseractWorker,
|
||||
logger,
|
||||
witClient,
|
||||
config,
|
||||
}
|
||||
|
||||
const server = fastify()
|
||||
.register(fastifyWebsocket, {
|
||||
options: {
|
||||
// 16 KiB max payload
|
||||
// A Discord message can not be longer than 4000 characters
|
||||
// OCR should not be longer than 16000 characters
|
||||
maxPayload: 16 * 1024,
|
||||
},
|
||||
})
|
||||
.register(async instance => {
|
||||
instance.get('/', { websocket: true }, async (connection, request) => {
|
||||
try {
|
||||
const client = new Client({
|
||||
socket: connection.socket,
|
||||
id: request.hostname,
|
||||
heartbeatInterval: config.clientHeartbeatInterval,
|
||||
})
|
||||
|
||||
clientSocketMap.set(connection.socket, client)
|
||||
clients.add(client)
|
||||
|
||||
logger.debug(`Client ${client.id}'s instance has been added`)
|
||||
logger.info(
|
||||
`New client connected (now ${clients.size} clients) with ID:`,
|
||||
client.id
|
||||
)
|
||||
|
||||
client.on('disconnect', reason => {
|
||||
clients.delete(client)
|
||||
logger.info(
|
||||
`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`
|
||||
)
|
||||
})
|
||||
|
||||
client.on('parseText', async packet =>
|
||||
parseTextEventHandler(packet, eventContext)
|
||||
)
|
||||
|
||||
client.on('parseImage', async packet =>
|
||||
parseImageEventHandler(packet, eventContext)
|
||||
)
|
||||
|
||||
if (environment === 'development' && !config.debugLogsInProduction) {
|
||||
logger.debug('Running development mode or debug logs in production is enabled, attaching debug events...')
|
||||
client.on('packet', ({ client: _, ...rawPacket }) =>
|
||||
logger.debug(
|
||||
`Packet received from client ${client.id}:`,
|
||||
inspectObject(rawPacket)
|
||||
)
|
||||
)
|
||||
|
||||
client.on('heartbeat', () =>
|
||||
logger.debug('Heartbeat received from client', client.id)
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) logger.error(e.stack ?? e.message)
|
||||
else logger.error(inspectObject(e))
|
||||
|
||||
const client = clientSocketMap.get(connection.socket)
|
||||
|
||||
if (!client) {
|
||||
logger.error(
|
||||
'Missing client instance when encountering an error. If the instance still exists in memory, it will NOT be removed!'
|
||||
)
|
||||
return connection.socket.terminate()
|
||||
}
|
||||
|
||||
if (client.disconnected === false)
|
||||
client.disconnect(DisconnectReason.ServerError)
|
||||
else client.forceDisconnect()
|
||||
|
||||
clients.delete(client)
|
||||
|
||||
logger.debug(
|
||||
`Client ${client.id} disconnected because of an internal error`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Start the server
|
||||
|
||||
logger.debug('Starting with these configurations:', inspectObject(config))
|
||||
|
||||
await server.listen({
|
||||
host: config.address ?? '0.0.0.0',
|
||||
port: config.port ?? 80,
|
||||
})
|
||||
|
||||
const addressInfo = server.server.address()
|
||||
if (!addressInfo || typeof addressInfo !== 'object')
|
||||
logger.debug('Server started, but cannot determine address information')
|
||||
else
|
||||
logger.info(
|
||||
'Server started at:',
|
||||
`${addressInfo.address}:${addressInfo.port}`
|
||||
)
|
||||
|
||||
})()
|
||||
import { fastify } from 'fastify'
|
||||
import fastifyWebsocket from '@fastify/websocket'
|
||||
|
||||
import { createWorker as createTesseractWorker } from 'tesseract.js'
|
||||
import witPkg from 'node-wit'
|
||||
const { Wit } = witPkg
|
||||
|
||||
import { inspect as inspectObject } from 'node:util'
|
||||
|
||||
import Client from './classes/Client.js'
|
||||
|
||||
import {
|
||||
EventContext,
|
||||
parseImageEventHandler,
|
||||
parseTextEventHandler,
|
||||
} from './events/index.js'
|
||||
|
||||
import { getConfig, checkEnv, logger } from './utils/index.js'
|
||||
import { WebSocket } from 'ws'
|
||||
import {
|
||||
DisconnectReason,
|
||||
HumanizedDisconnectReason,
|
||||
} from '@revanced/bot-shared'
|
||||
|
||||
// Check environment variables and load config
|
||||
const environment = checkEnv(logger)
|
||||
const config = getConfig()
|
||||
|
||||
if (!config.debugLogsInProduction && environment === 'production')
|
||||
logger.debug = () => {}
|
||||
|
||||
// Workers and API clients
|
||||
|
||||
const tesseractWorker = await createTesseractWorker('eng')
|
||||
const witClient = new Wit({
|
||||
accessToken: process.env['WIT_AI_TOKEN']!,
|
||||
})
|
||||
|
||||
process.on('beforeExit', () => tesseractWorker.terminate())
|
||||
|
||||
// Server logic
|
||||
|
||||
const clients = new Set<Client>()
|
||||
const clientSocketMap = new WeakMap<WebSocket, Client>()
|
||||
const eventContext: EventContext = {
|
||||
tesseractWorker,
|
||||
logger,
|
||||
witClient,
|
||||
config,
|
||||
}
|
||||
|
||||
const server = fastify()
|
||||
.register(fastifyWebsocket, {
|
||||
options: {
|
||||
// 16 KiB max payload
|
||||
// A Discord message can not be longer than 4000 characters
|
||||
// OCR should not be longer than 16000 characters
|
||||
maxPayload: 16 * 1024,
|
||||
},
|
||||
})
|
||||
.register(async instance => {
|
||||
instance.get('/', { websocket: true }, async (connection, request) => {
|
||||
try {
|
||||
const client = new Client({
|
||||
socket: connection.socket,
|
||||
id: request.hostname,
|
||||
heartbeatInterval: config.clientHeartbeatInterval,
|
||||
})
|
||||
|
||||
clientSocketMap.set(connection.socket, client)
|
||||
clients.add(client)
|
||||
|
||||
logger.debug(`Client ${client.id}'s instance has been added`)
|
||||
logger.info(
|
||||
`New client connected (now ${clients.size} clients) with ID:`,
|
||||
client.id
|
||||
)
|
||||
|
||||
client.on('disconnect', reason => {
|
||||
clients.delete(client)
|
||||
logger.info(
|
||||
`Client ${client.id} disconnected because client ${HumanizedDisconnectReason[reason]}`
|
||||
)
|
||||
})
|
||||
|
||||
client.on('parseText', async packet =>
|
||||
parseTextEventHandler(packet, eventContext)
|
||||
)
|
||||
|
||||
client.on('parseImage', async packet =>
|
||||
parseImageEventHandler(packet, eventContext)
|
||||
)
|
||||
|
||||
if (
|
||||
environment === 'development' &&
|
||||
!config.debugLogsInProduction
|
||||
) {
|
||||
logger.debug(
|
||||
'Running development mode or debug logs in production is enabled, attaching debug events...'
|
||||
)
|
||||
client.on('packet', ({ client, ...rawPacket }) =>
|
||||
logger.debug(
|
||||
`Packet received from client ${client.id}:`,
|
||||
inspectObject(rawPacket)
|
||||
)
|
||||
)
|
||||
|
||||
client.on('heartbeat', () =>
|
||||
logger.debug(
|
||||
'Heartbeat received from client',
|
||||
client.id
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) logger.error(e.stack ?? e.message)
|
||||
else logger.error(inspectObject(e))
|
||||
|
||||
const client = clientSocketMap.get(connection.socket)
|
||||
|
||||
if (!client) {
|
||||
logger.error(
|
||||
'Missing client instance when encountering an error. If the instance still exists in memory, it will NOT be removed!'
|
||||
)
|
||||
return connection.socket.terminate()
|
||||
}
|
||||
|
||||
if (client.disconnected === false)
|
||||
client.disconnect(DisconnectReason.ServerError)
|
||||
else client.forceDisconnect()
|
||||
|
||||
clients.delete(client)
|
||||
|
||||
logger.debug(
|
||||
`Client ${client.id} disconnected because of an internal error`
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// Start the server
|
||||
|
||||
logger.debug('Starting with these configurations:', inspectObject(config))
|
||||
|
||||
await server.listen({
|
||||
host: config.address ?? '0.0.0.0',
|
||||
port: config.port ?? 80,
|
||||
})
|
||||
|
||||
const addressInfo = server.server.address()
|
||||
if (!addressInfo || typeof addressInfo !== 'object')
|
||||
logger.debug('Server started, but cannot determine address information')
|
||||
else
|
||||
logger.info(
|
||||
'Server started at:',
|
||||
`${addressInfo.address}:${addressInfo.port}`
|
||||
)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import type { Logger } from './logger.js'
|
||||
|
||||
export default function checkEnv(logger: Logger) {
|
||||
if (!process.env['NODE_ENV']) logger.warn('NODE_ENV not set, defaulting to `development`')
|
||||
if (!process.env['NODE_ENV'])
|
||||
logger.warn('NODE_ENV not set, defaulting to `development`')
|
||||
const environment = (process.env['NODE_ENV'] ??
|
||||
'development') as NodeEnvironment
|
||||
'development') as NodeEnvironment
|
||||
|
||||
if (!['development', 'production'].includes(environment)) {
|
||||
logger.error(
|
||||
@@ -16,7 +17,9 @@ export default function checkEnv(logger: Logger) {
|
||||
logger.info(`Running in ${environment} mode...`)
|
||||
|
||||
if (environment === 'production' && process.env['IS_USING_DOT_ENV']) {
|
||||
logger.warn('You seem to be using .env files, this is generally not a good idea in production...')
|
||||
logger.warn(
|
||||
'You seem to be using .env files, this is generally not a good idea in production...'
|
||||
)
|
||||
}
|
||||
|
||||
if (!process.env['WIT_AI_TOKEN']) {
|
||||
|
||||
@@ -2,28 +2,31 @@ import { existsSync } from 'node:fs'
|
||||
import { resolve as resolvePath } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
const configPath = resolvePath(
|
||||
process.cwd(),
|
||||
'config.json'
|
||||
)
|
||||
const configPath = resolvePath(process.cwd(), 'config.json')
|
||||
|
||||
const userConfig: Partial<Config> = existsSync(configPath)
|
||||
? (await import(pathToFileURL(configPath).href, {
|
||||
assert: {
|
||||
type: 'json',
|
||||
},
|
||||
})).default
|
||||
? (
|
||||
await import(pathToFileURL(configPath).href, {
|
||||
assert: {
|
||||
type: 'json',
|
||||
},
|
||||
})
|
||||
).default
|
||||
: {}
|
||||
|
||||
type BaseTypeOf<T> = T extends (infer U)[]
|
||||
? U[]
|
||||
: T extends (...args: any[]) => infer U
|
||||
? (...args: any[]) => U
|
||||
: T extends object
|
||||
? { [K in keyof T]: T[K] }
|
||||
: T
|
||||
: T extends (...args: unknown[]) => infer U
|
||||
? (...args: unknown[]) => U
|
||||
: T extends object
|
||||
? { [K in keyof T]: T[K] }
|
||||
: T
|
||||
|
||||
export type Config = Omit<
|
||||
BaseTypeOf<typeof import('../../config.json')>,
|
||||
'$schema'
|
||||
>
|
||||
|
||||
export type Config = Omit<BaseTypeOf<typeof import('../../config.json')>, '$schema'> & {}
|
||||
export const defaultConfig: Config = {
|
||||
address: '127.0.0.1',
|
||||
port: 80,
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
export { default as getConfig } from './getConfig.js'
|
||||
export { default as checkEnv } from './checkEnv.js'
|
||||
export { default as logger } from './logger.js'
|
||||
export { default as logger } from './logger.js'
|
||||
|
||||
@@ -3,14 +3,23 @@ import { Chalk } from 'chalk'
|
||||
const chalk = new Chalk()
|
||||
const logger = {
|
||||
debug: (...args) => console.debug(chalk.gray('DEBUG:', ...args)),
|
||||
info: (...args) => console.info(chalk.bgBlue.whiteBright(' INFO '), ...args),
|
||||
warn: (...args) => console.warn(chalk.bgYellow.blackBright.bold(' WARN '), chalk.yellowBright(...args)),
|
||||
error: (...args) => console.error(chalk.bgRed.whiteBright.bold(' ERROR '), chalk.redBright(...args)),
|
||||
info: (...args) =>
|
||||
console.info(chalk.bgBlue.whiteBright(' INFO '), ...args),
|
||||
warn: (...args) =>
|
||||
console.warn(
|
||||
chalk.bgYellow.blackBright.bold(' WARN '),
|
||||
chalk.yellowBright(...args)
|
||||
),
|
||||
error: (...args) =>
|
||||
console.error(
|
||||
chalk.bgRed.whiteBright.bold(' ERROR '),
|
||||
chalk.redBright(...args)
|
||||
),
|
||||
log: console.log,
|
||||
} satisfies Logger
|
||||
|
||||
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'log'
|
||||
export type LogFunction = (...x: any[]) => void
|
||||
export type LogFunction = (...x: unknown[]) => void
|
||||
export type Logger = Record<LogLevel, LogFunction>
|
||||
|
||||
export default logger
|
||||
export default logger
|
||||
|
||||
Reference in New Issue
Block a user