import path from 'path'; import express from 'express'; import cors from 'cors' import http from 'http' import chalk from 'chalk' import * as z from 'zod'; import forms from 'forms' import { initWebSocket } from './ws.js' import util from './util.js' export default class Server { store; registerRoutes(router) { router.get('/*', this.get) return router } index = async (req, res) => { let filePath = path.join(util.CAVE_PATH, "index.html"); res.sendFile(filePath) } get = async (req, res) => { let url = req.url let filePath; if(url.startsWith("/_")) { filePath = path.join(util.CAVE_PATH, url); } else if(url.includes("75820185")) { filePath = path.join(util.CAVE_PATH, url.split("75820185")[1]); } else { filePath = path.join(util.CAVE_PATH, "index.html"); } res.sendFile(filePath); } async connectToForms(spawnForms) { try { await this.store.connect() } catch(e) { try { await spawnForms() await this.store.connect() } catch(e) { try { let tryReconnect = async (attempts = 5, interval = 100) => { for (let i = 0; i < attempts; i++) { try { return await this.store.connect(); } catch (e) { if (i === attempts - 1) {throw e;} await new Promise(resolve => setTimeout(resolve, interval)); } } } await tryReconnect(5, 100) } catch(e) { console.error("Could not spawn forms: ", e) return } } } this.store.register("log", z.toJSONSchema(z.object({ time: z.string(), host: z.string(), ip: z.string(), path: z.string(), method: z.string() }))) this.store.add("log", { time: "0100", host: "parchment.page", ip: "0.0.0.1", path: "/asd", method: "GET" }) } constructor(spawnForms, port) { const app = express(); app.use(cors({ origin: '*' })); app.use(express.json()); app.use(util.logRequest); app.use(util.logResponse); let router = express.Router(); this.registerRoutes(router) app.use('/', router); this.store = new forms.client() this.connectToForms(spawnForms) const server = http.createServer(app); initWebSocket(server); server.listen(port, () => { console.log("\n") console.log(chalk.yellow("**************Parchment****************")) console.log(chalk.yellowBright(`Server is running on port ${port}: http://localhost`)); console.log(chalk.yellow("***************************************")) console.log("\n") }); process.on('SIGINT', async () => { console.log(chalk.red('Closing server...')); console.log(chalk.green('Database connection closed.')); process.exit(0); }); Object.preventExtensions(this); } }