server/packages/media-manager/backends/local.ts

66 lines
2 KiB
TypeScript
Raw Normal View History

2024-04-07 07:30:49 +02:00
import type { Config } from "config-manager";
import { MediaBackend, MediaBackendType, MediaHasher } from "..";
2024-03-09 00:14:45 +01:00
import type { ConvertableMediaFormats } from "../media-converter";
import { MediaConverter } from "../media-converter";
export class LocalMediaBackend extends MediaBackend {
2024-04-07 07:30:49 +02:00
constructor(config: Config) {
super(config, MediaBackendType.LOCAL);
}
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
public async addFile(file: File) {
let convertedFile = file;
if (this.shouldConvertImages(this.config)) {
const fileExtension = file.name.split(".").pop();
const mediaConverter = new MediaConverter(
fileExtension as ConvertableMediaFormats,
this.config.media.conversion
.convert_to as ConvertableMediaFormats,
);
convertedFile = await mediaConverter.convert(file);
}
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
const hash = await new MediaHasher().getMediaHash(convertedFile);
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
const newFile = Bun.file(
`${this.config.media.local_uploads_folder}/${hash}`,
);
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
if (await newFile.exists()) {
throw new Error("File already exists");
}
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
await Bun.write(newFile, convertedFile);
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
return {
uploadedFile: convertedFile,
path: `./uploads/${convertedFile.name}`,
hash: hash,
};
}
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
public async getFileByHash(
hash: string,
databaseHashFetcher: (sha256: string) => Promise<string | null>,
): Promise<File | null> {
const filename = await databaseHashFetcher(hash);
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
if (!filename) return null;
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
return this.getFile(filename);
}
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
public async getFile(filename: string): Promise<File | null> {
const file = Bun.file(
`${this.config.media.local_uploads_folder}/${filename}`,
);
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
if (!(await file.exists())) return null;
2024-03-09 00:14:45 +01:00
2024-04-07 07:30:49 +02:00
return new File([await file.arrayBuffer()], filename, {
type: file.type,
lastModified: file.lastModified,
});
}
2024-03-09 00:14:45 +01:00
}