Update logging

This commit is contained in:
Kentai Radiquum 2025-01-23 06:29:43 +05:00
parent edf51ec0f7
commit 240396b506
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
4 changed files with 153 additions and 85 deletions

View file

@ -2,6 +2,6 @@ const config = {
stickerPacksDir: "./stickerpacks",
outDir: "./",
homeserverUrl: "https://synapse.wah.su/__thumbnail/"
}
};
module.exports = config

View file

@ -1,46 +1,73 @@
const config = require("./config");
const fs = require("fs");
const path = require("path");
const { log } = require("./utils");
const _CreatePackPage = require("./templates/pack");
const _CreatePacksIndex = require("./templates/index");
let PackIndex = null
let PackIndex = null;
let Packs = [];
const isDev = process.env.DEVMODE || false
const isDev = process.env.DEVMODE || false;
log("INFO", `DEV MODE ENABLED: ${isDev}`);
const dirents = fs.readdirSync(config.stickerPacksDir, { withFileTypes: true });
const InpPath = path
.join(__dirname, "../", config.stickerPacksDir, "./")
.trim();
const OutPath = path.join(__dirname, "../", config.outDir, "./").trim();
const ParPath = path.join(__dirname, "../", "./").trim();
log("INFO", `Sticker sets directory: ${InpPath}`);
log("INFO", `Output directory: ${OutPath}`);
log("INFO", `Working directory: ${ParPath}`);
const dirents = fs.readdirSync(InpPath, { withFileTypes: true });
const files = dirents
.filter(dirent => dirent.isFile())
.filter(dirent => (dirent.name.endsWith(".json") && dirent.name != "index.json"))
.map(dirent => dirent.name);
.filter((dirent) => dirent.isFile())
.filter(
(dirent) => dirent.name.endsWith(".json") && dirent.name != "index.json"
)
.map((dirent) => dirent.name);
if (files.length == 0) {
console.error("[ERROR] NO Sticker Packs Found!");
log("error", "No sticker sets found!");
process.exit(1);
}
console.log("[INFO] Found " + files.length + " sticker packs");
log("INFO", `Found: ${files.length} sticker sets`);
PackIndex = {
homeserver_url: config.homeserverUrl,
packs: files
}
fs.writeFileSync(config.stickerPacksDir + "/index.json", JSON.stringify(PackIndex));
packs: files,
};
fs.writeFileSync(
config.stickerPacksDir + "/index.json",
JSON.stringify(PackIndex)
);
log("INFO", `Updated "index.json" in sticker sets directory`, true);
if (!fs.existsSync(config.outDir)) fs.mkdirSync(config.outDir);
if (OutPath != ParPath) {
if (!fs.existsSync(OutPath)) fs.mkdirSync(OutPath);
fs.cpSync(`${ParPath}static`, `${OutPath}static`, { recursive: true });
log("INFO", `Copied static directory to output directory`);
}
PackIndex.packs.forEach((pack) => {
const packFile = JSON.parse(fs.readFileSync(config.stickerPacksDir + "/" + pack));
if (!fs.existsSync(config.outDir + "/" + packFile.id)) fs.mkdirSync(config.outDir + "/" + packFile.id);
fs.writeFileSync(config.outDir + "/" + packFile.id + "/index.html", _CreatePackPage(PackIndex, packFile, isDev));
const packFile = JSON.parse(
fs.readFileSync(`${InpPath}${pack}`)
);
if (!fs.existsSync(`${OutPath}${packFile.id}`)) fs.mkdirSync(`${OutPath}${packFile.id}`);
fs.writeFileSync(`${OutPath}${packFile.id}/index.html`, _CreatePackPage(PackIndex, packFile, isDev));
Packs.push({
id: packFile.id,
name: packFile.title,
image: packFile.stickers[0].id,
author: (packFile.hasOwnProperty("author") && packFile.author) ? packFile.author.name : null,
author:
packFile.hasOwnProperty("author") && packFile.author
? packFile.author.name
: null,
rating: packFile.hasOwnProperty("rating") ? packFile.rating : null,
stickers: packFile.stickers.length
})
console.log("preview for " + packFile.id + " created");
})
fs.writeFileSync(config.outDir + "/index.html", _CreatePacksIndex(PackIndex, Packs, isDev));
console.log("Generation complete");
stickers: packFile.stickers.length,
});
log("INFO", `Created preview for sticker set: ${packFile.title} (${packFile.id})`);
});
fs.writeFileSync(`${OutPath}index.html`, _CreatePacksIndex(PackIndex, Packs, isDev));
log("INFO", "Generation complete");

View file

@ -41,7 +41,34 @@ function InjectWSConnection() {
<!-- The following was injected by watch.js script, because we are in a dev mode -->
<script src="/src/hotreload.js"></script>
<!-- Dev mode: Enabled -->
`
`;
}
module.exports = {CreateImageURL, CreatePackDescription, InjectWSConnection};
function log(level = "INFO" | "ERROR" | "WARN" | "LOG", message, connected = false) {
const date = new Date;
const time = date.toLocaleTimeString()
if (connected) {
message = `${message}`
}
switch (level.toUpperCase()) {
case "INFO":
console.info(`${time}:${level} - ${message}`);
break;
case "ERROR":
console.error(`${time}:${level} - ${message}`);
break;
case "WARN":
console.warn(`${time}:${level} - ${message}`);
break;
default:
console.log(`${time}:LOG - ${message}`);
break;
}
}
module.exports = {
CreateImageURL,
CreatePackDescription,
InjectWSConnection,
log,
};

View file

@ -1,66 +1,80 @@
const chokidar = require("chokidar");
const exec = require("child_process");
const express = require('express');
const path = require('path');
const WebSocket = require('ws');
const express = require("express");
const path = require("path");
const WebSocket = require("ws");
const fs = require("fs");
const config = require("./config");
const { log } = require("./utils");
let triggered = 0
const delay = 1000
let SIGINTCount = 0
let triggered = 0;
const delay = 1000;
let SIGINTCount = 0;
const InpPath = path
.join(__dirname, "../", config.stickerPacksDir, "./")
.trim();
const OutPath = path.join(__dirname, "../", config.outDir, "./").trim();
const ParPath = path.join(__dirname, "../", "./").trim();
log("INFO", `Sticker sets directory: ${InpPath}`);
log("INFO", `Output directory: ${OutPath}`);
log("INFO", `Working directory: ${ParPath}`);
function onChange(wss) {
if (triggered != 0 && Date.now() - triggered < delay) {
console.log(` ↳[WARN] Rebuild was triggered less than a ${delay}ms ago!`)
return
log("WARN", `Rebuild was triggered less than a ${delay}ms ago!`, true);
return;
}
triggered = Date.now()
triggered = Date.now();
process.env.DEVMODE = true
process.env.DEVMODE = true;
exec.exec("npm run build", (error, stdout, stderr) => {
if (error) {
console.error(`error: ${error.message}`);
log("ERROR", error.message);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
log("ERROR", stderr);
return;
}
console.log(`stdout: ${stdout}`);
log("INFO", stdout);
if (wss) {
console.log('Reloading web page...');
wss.send("RELOAD")
log("INFO", "Reloading web page...");
wss.send("RELOAD");
}
});
}
function onExit() {
let folders = null
let folders = null;
if (fs.existsSync(config.stickerPacksDir + "/index.json")) {
folders = []
JSON.parse(fs.readFileSync(config.stickerPacksDir + "/index.json"))["packs"].map((pack) => folders.push(pack.replace(".json", "")))
if (fs.existsSync(`${InpPath}/index.json`)) {
folders = [];
JSON.parse(fs.readFileSync(`${InpPath}/index.json`))["packs"].map((pack) =>
folders.push(pack.replace(".json", ""))
);
folders.forEach(
(folder) => {
if (fs.existsSync(config.outDir + "/" + folder) ) fs.rmdirSync(config.outDir + "/" + folder, {recursive: true})
console.log(`Deleted generated folder: "${folder}"`)
}
)
folders.forEach((folder) => {
if (fs.existsSync(`${OutPath}${folder}`))
fs.rmdirSync(`${OutPath}${folder}`, { recursive: true });
log("INFO", `Deleted generated folder: "${folder}"`);
});
} else {
console.log("no index.json found, forgot to run build?")
log("WARN", `no "index.json" found, forgot to run build?`);
}
if (fs.existsSync(config.outDir + "/index.html")) fs.rmSync(config.outDir + "/index.html")
console.log(`Deleted "index.html" file`)
if (fs.existsSync(`${OutPath}index.html`)) fs.rmSync(`${OutPath}index.html`);
log("INFO", `Deleted "index.html" file`);
process.exit(0)
if (fs.existsSync(OutPath) && OutPath != ParPath) {
log("INFO", `Deleted output folder`);
}
process.exit(0);
}
const watcher = chokidar.watch(["./src/templates", "./stickerpacks"], {
ignored: (filePath, stats) =>
(stats?.isFile() && !(filePath.endsWith(".js") || filePath.endsWith(".json"))) || filePath.endsWith("index.json"),
const watcher = chokidar.watch(["./src", "./stickerpacks"], {
ignored: (filePath, stats) => filePath.endsWith("index.json"),
atomic: true,
awaitWriteFinish: true,
persistent: true,
@ -68,49 +82,49 @@ const watcher = chokidar.watch(["./src/templates", "./stickerpacks"], {
function startServerWithRebuild() {
const app = express();
const folder = path.join(__dirname, '..')
const folder = path.join(__dirname, "..");
const wss = new WebSocket.Server({ port: 3001 });
let WSclient = null
let WSclient = null;
wss.on('connection', (ws) => {
WSclient = ws
ws.send("CONNECTED")
wss.on("connection", (ws) => {
WSclient = ws;
ws.send("CONNECTED");
});
process.on("SIGINT", () => {
SIGINTCount += 1
SIGINTCount += 1;
if (WSclient) {
async function _closeWS() {
await WSclient.close()
await WSclient.close();
}
_closeWS()
_closeWS();
}
if (SIGINTCount == 1) {
console.log("Gracefully shutdown and cleanup...")
onExit()
log("LOG", "Gracefully shutdown and cleanup...");
onExit();
} else if (SIGINTCount >= 3) {
console.log("Received 3+ SIGINT signals. Force exit...")
process.exit(0)
log("LOG", "Received 3+ SIGINT signals. Force exit...");
process.exit(0);
}
})
});
app.use(express.static(folder));
app.listen(3000, () => {
console.log(`[INFO] Serving files from folder ${folder}`)
console.log('[INFO] Express server is running on port 3000');
log("INFO", `Serving files from folder ${folder}`);
log("INFO", "Express server is running on port 3000");
watcher
.on('add', (path) => {
console.log(`[INFO] File ${path} has been added, rebuilding...`);
.on("add", (path) => {
log("INFO", `File ${path} has been added, rebuilding...`);
onChange(WSclient);
})
.on('change', (path) => {
console.log(`[INFO] File ${path} has been changed, rebuilding...`);
.on("change", (path) => {
log("INFO", `File ${path} has been changed, rebuilding...`);
onChange(WSclient);
})
.on('unlink', (path) => {
console.log(`[INFO] File ${path} has been removed, rebuilding...`);
.on("unlink", (path) => {
log("INFO", `File ${path} has been removed, rebuilding...`);
onChange(WSclient);
});
});