forked from noxious/server
45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import fs from 'fs/promises'
|
|
import { writeFile } from 'node:fs/promises'
|
|
|
|
import { BaseEvent } from '#application/base/baseEvent'
|
|
import { SocketEvent } from '#application/enums'
|
|
import Storage from '#application/storage'
|
|
import { Tile } from '#entities/tile'
|
|
|
|
interface ITileData {
|
|
[key: string]: Buffer
|
|
}
|
|
|
|
export default class TileUploadEvent extends BaseEvent {
|
|
public listen(): void {
|
|
this.socket.on(SocketEvent.GM_TILE_UPLOAD, this.handleEvent.bind(this))
|
|
}
|
|
|
|
private async handleEvent(data: ITileData, callback: (response: boolean) => void): Promise<void> {
|
|
try {
|
|
if (!(await this.isCharacterGM())) return
|
|
|
|
const public_folder = Storage.getPublicPath('tiles')
|
|
|
|
// Ensure the folder exists
|
|
await fs.mkdir(public_folder, { recursive: true })
|
|
|
|
const uploadPromises = Object.entries(data).map(async ([key, tileData]) => {
|
|
const tile = new Tile()
|
|
await tile.setName('New tile').save()
|
|
const uuid = tile.getId()
|
|
const filename = `${uuid}.png`
|
|
const finalFilePath = Storage.getPublicPath('tiles', filename)
|
|
await writeFile(finalFilePath, tileData)
|
|
})
|
|
|
|
await Promise.all(uploadPromises)
|
|
|
|
return callback(true)
|
|
} catch (error) {
|
|
this.logger.error('Error uploading tile:', error)
|
|
return callback(false)
|
|
}
|
|
}
|
|
}
|