displaying rudimentary logs

This commit is contained in:
metacryst
2025-12-26 06:55:32 -06:00
parent b4d0d77b91
commit a76e975601
15 changed files with 243 additions and 212 deletions

View File

@@ -20,7 +20,6 @@ export default class Database {
this.logs = dbJson
setInterval(() => {
console.log("saving db")
global.db.saveData()
}, 5000)
}

View File

@@ -7,13 +7,15 @@ import chalk from 'chalk'
import moment from 'moment'
import path from 'path'
import * as useragent from "express-useragent";
import forms from 'forms'
import "./util.js"
import Socket from './ws/ws.js'
import Clients from './ws/Clients.js'
import Database from "./db/db.js"
import AuthHandler from './auth.js';
export default class Server {
store;
db;
auth;
UIPath = path.join(global.__dirname, '../ui')
@@ -30,6 +32,10 @@ export default class Server {
return router
}
handleNewLog(log) {
global.Clients.broadcast(log)
}
verifyToken = (req, res, next) => {
const { token } = req.query;
if (!token) {
@@ -131,6 +137,10 @@ export default class Server {
this.db = new Database()
global.db = this.db
this.auth = new AuthHandler()
this.store = new forms.client()
this.store.connect()
this.store.watch("log", this.handleNewLog)
const app = express();
app.use(cors({ origin: '*' }));
app.use(express.json());
@@ -146,11 +156,11 @@ export default class Server {
app.use('/', router);
const server = http.createServer(app);
global.Socket = new Socket(server);
global.Clients = new Clients(server);
const PORT = 4001;
server.listen(PORT, () => {
console.log("\n")
console.log(chalk.yellow("*************** Hyperia ***************"))
console.log(chalk.yellow("*************** Console ***************"))
console.log(chalk.yellowBright(`Server is running on port ${PORT}: http://localhost`));
console.log(chalk.yellow("***************************************"))
console.log("\n")

View File

@@ -1,22 +1,21 @@
import { WebSocket, WebSocketServer } from 'ws'
import { z } from "zod"
import jwt from 'jsonwebtoken'
import ForumHandler from "./handlers/ForumHandler.js"
import MessagesHandler from "./handlers/MessagesHandler.js"
import handler from "./handler.js"
import chalk from 'chalk'
export default class Socket {
export default class Clients {
wss;
messageSchema = z.object({
id: z.string(),
app: z.string(),
operation: z.string().optional(),
op: z.string().optional(),
msg: z.union([
z.object({}).passthrough(), // allows any object
z.array(z.any()) // allows any array
]).optional()
})
.superRefine((data, ctx) => {
if (data.operation !== "GET" && data.msg === undefined) {
if (data.op !== "GET" && data.msg === undefined) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["msg"],
@@ -43,12 +42,17 @@ export default class Socket {
const cookies = parseCookies(req.headers.cookie);
const token = cookies.auth_token;
if (!token) throw new Error("No auth token");
if (!token) {
console.error("No auth token");
return
}
const payload = jwt.verify(token, process.env.JWT_SECRET);
ws.userEmail = payload.email;
ws.on('message', (msg) => {
this.handleMessage(msg, ws);
const text = msg.toString("utf8");
const data = JSON.parse(text);
this.handleMessage(data, ws);
});
ws.on('close', () => {
@@ -62,7 +66,12 @@ export default class Socket {
// Build a system where the ws obj is updated every time on navigate, so it already has context
// this way, we can only send broadcast messages to clients that actually have that app / subapp open
handleMessage = (msg, ws) => {
if(!this.messageSchema.safeParse(msg).success) {
console.log(chalk.red("Socket.handleMessage: Incoming ws message has incorrect format! ", this.messageSchema.safeParse(msg).error))
return
}
console.log("websocket message received: ", msg)
handler.handle(msg)
}
broadcast(event) {

14
server/ws/handler.js Normal file
View File

@@ -0,0 +1,14 @@
export default class handler {
static handleGet(msg) {
// let data = forms.get("log", 10)
// return data
}
static handle(msg, ws) {
switch(msg.op) {
case "GET":
return this.handleGet(msg)
}
}
}

View File

@@ -1,43 +0,0 @@
import { z } from "zod"
const sendSchema = z.object({
forum: z.string(),
text: z.string(),
})
.strict()
const getSchema = z.object({
forum: z.string(),
number: z.number()
})
.strict()
export default class ForumHandler {
static handleSend(msg, ws) {
try {
global.db.posts.add(msg.text, msg.forum, ws.userEmail)
global.Socket.broadcast({event: "new-post", app: "FORUM", forum: msg.forum, msg: this.handleGet({forum: msg.forum, number: 100})})
return {success: true}
} catch(e) {
console.error(e)
}
}
static handleGet(msg) {
let data = global.db.posts.get(msg.forum, msg.number)
return data
}
static handle(operation, msg, ws) {
switch(operation) {
case "SEND":
if(!sendSchema.safeParse(msg).success) throw new Error("Incorrectly formatted Forum ws message!")
return this.handleSend(msg, ws)
case "GET":
if(!getSchema.safeParse(msg).success) throw new Error("Incorrectly formatted Forum ws message!")
return this.handleGet(msg)
}
}
}

View File

@@ -1,40 +0,0 @@
import { z } from "zod"
const sendSchema = z.object({
conversation: z.string(),
text: z.string(),
})
.strict()
export default class MessagesHandler {
static handleSend(msg, ws) {
let user = global.db.members.getByEmail(ws.userEmail)
let convo = global.db.conversations.get(msg.conversation)
if(convo.between.includes(`MEMBER-${user.id}`)) {
global.db.messages.add(msg.conversation, msg.text, `MEMBER-${user.id}`)
global.Socket.broadcast({event: "new-message", app: "MESSAGES", msg: {conversationID: convo.id, messages: global.db.messages.getByConversation(`CONVERSATION-${msg.conversation}`)}})
} else {
throw new Error("Can't add to a conversation user is not a part of!")
}
return {success: true}
}
static handleGet(ws) {
let user = global.db.members.getByEmail(ws.userEmail)
let data = global.db.conversations.getByMember(`MEMBER-${user.id}`)
return data
}
static handle(operation, msg, ws) {
switch(operation) {
case "GET":
return this.handleGet(ws)
case "SEND":
if(!sendSchema.safeParse(msg).success) throw new Error("Incorrectly formatted Forum ws message!")
return this.handleSend(msg, ws)
}
}
}