1
0
forked from noxious/server

refractor file to unfuck the logic

This commit is contained in:
Dennis Postma 2024-07-01 10:46:02 +02:00
parent 39e8f52595
commit d59608174d

View File

@ -1,12 +1,11 @@
import { Server } from "socket.io"; import { Server } from "socket.io";
import {TSocket} from "../../utilities/Types"; import { TSocket } from "../../utilities/Types";
import {writeFile} from "node:fs"; import { writeFile } from "node:fs/promises";
import {randomUUID} from "node:crypto";
import path from "path"; import path from "path";
import fs from "fs"; import fs from "fs/promises";
interface ITileData {
interface IPayload { [key: string]: Buffer;
} }
/** /**
@ -15,34 +14,44 @@ interface IPayload {
* @param io * @param io
*/ */
export default function (socket: TSocket, io: Server) { export default function (socket: TSocket, io: Server) {
socket.on('gm:tile:upload', async (data: any, callback: (response: boolean) => void) => { socket.on('gm:tile:upload', async (data: ITileData, callback: (response: boolean) => void) => {
try {
if (socket.character?.role !== 'gm') {
callback(false);
return;
}
if (socket.character?.role !== 'gm') { const public_folder = path.join(process.cwd(), 'public', 'tiles');
return;
}
// get root path // Ensure the folder exists
const public_folder = path.join(process.cwd(), 'public', 'tiles'); await fs.mkdir(public_folder, { recursive: true });
// check if folder exists or create it const files = await fs.readdir(public_folder);
if (!fs.existsSync(public_folder)) { let highestNumber = -1;
fs.mkdirSync(public_folder, { recursive: true });
}
for (const key in data) { // Find the highest number in existing filenames
// the files in the folder are named 0.png, 1.png, 2.png etc... check the last file name and add 1 for (const file of files) {
const files = fs.readdirSync(public_folder); const match = file.match(/^(\d+)\.png$/);
const lastFile = files.reduce((a, b) => a > b ? a : b, '0.png'); if (match) {
const lastFileName = lastFile?.split('.')[0]; const number = parseInt(match[1], 10);
const filename = `${parseInt(lastFileName ?? '0') + 1}.png`; if (number > highestNumber) {
const finalFilePath = path.join(public_folder, filename); highestNumber = number;
const tile = data[key]; }
}
}
// save the tile to the disk, for example const uploadPromises = Object.entries(data).map(async ([key, tileData], index) => {
writeFile(finalFilePath, tile, (err) => {}); const filename = `${highestNumber + index + 1}.png`;
const finalFilePath = path.join(public_folder, filename);
await writeFile(finalFilePath, tileData);
});
await Promise.all(uploadPromises);
// return true to the client
callback(true); callback(true);
} catch (error) {
console.error('Error uploading tiles:', error);
callback(false);
} }
}); });
} }