mirror of
https://gitlab.w-hs.de/an14051/backerup-website.git
synced 2026-07-27 17:35:29 +00:00
68 lines
1.8 KiB
TypeScript
68 lines
1.8 KiB
TypeScript
import path from 'path'
|
|
import fs from 'fs/promises'
|
|
|
|
export type FileType = 'backerup' | 'config'
|
|
|
|
export interface FileRecord {
|
|
token: string
|
|
originalName: string
|
|
displayName?: string
|
|
size: number
|
|
type: FileType
|
|
uploadedAt: string
|
|
description?: string
|
|
group?: string
|
|
containerName?: string
|
|
image?: string
|
|
}
|
|
|
|
const DATA_DIR = path.join(process.cwd(), 'data')
|
|
const META_FILE = path.join(DATA_DIR, 'meta.json')
|
|
const UPLOADS_DIR = path.join(DATA_DIR, 'uploads')
|
|
|
|
async function ensureDirs() {
|
|
await fs.mkdir(UPLOADS_DIR, { recursive: true })
|
|
}
|
|
|
|
export async function readMeta(): Promise<FileRecord[]> {
|
|
try {
|
|
const text = await fs.readFile(META_FILE, 'utf-8')
|
|
return JSON.parse(text) as FileRecord[]
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
export async function listGroups(): Promise<string[]> {
|
|
const records = await readMeta()
|
|
const groups = new Set<string>()
|
|
for (const r of records) {
|
|
if (r.group) groups.add(r.group)
|
|
}
|
|
return Array.from(groups).sort()
|
|
}
|
|
|
|
async function writeMeta(records: FileRecord[]): Promise<void> {
|
|
await ensureDirs()
|
|
await fs.writeFile(META_FILE, JSON.stringify(records, null, 2), 'utf-8')
|
|
}
|
|
|
|
export async function addFile(record: FileRecord, buffer: Buffer): Promise<void> {
|
|
await ensureDirs()
|
|
const dir = path.join(UPLOADS_DIR, record.token)
|
|
await fs.mkdir(dir, { recursive: true })
|
|
await fs.writeFile(path.join(dir, record.originalName), buffer)
|
|
const records = await readMeta()
|
|
records.unshift(record)
|
|
await writeMeta(records)
|
|
}
|
|
|
|
export async function getFile(token: string): Promise<FileRecord | undefined> {
|
|
const records = await readMeta()
|
|
return records.find((r) => r.token === token)
|
|
}
|
|
|
|
export function getUploadPath(token: string, originalName: string): string {
|
|
return path.join(UPLOADS_DIR, token, originalName)
|
|
}
|