mirror of
https://github.com/versia-pub/server.git
synced 2025-12-06 08:28:19 +01:00
94 lines
2.5 KiB
TypeScript
94 lines
2.5 KiB
TypeScript
/**
|
|
* @packageDocumentation
|
|
* @module MediaManager/Drivers
|
|
*/
|
|
|
|
import { S3Client } from "@jsr/bradenmacdonald__s3-lite-client";
|
|
import type { Config } from "config-manager";
|
|
import { MediaHasher } from "../media-hasher";
|
|
import type { UploadedFileMetadata } from "../media-manager";
|
|
import type { MediaDriver } from "./media-driver";
|
|
|
|
/**
|
|
* Implements the MediaDriver interface for S3 storage.
|
|
*/
|
|
export class S3MediaDriver implements MediaDriver {
|
|
private s3Client: S3Client;
|
|
private mediaHasher: MediaHasher;
|
|
|
|
/**
|
|
* Creates a new S3MediaDriver instance.
|
|
* @param config - The configuration object.
|
|
*/
|
|
constructor(config: Config) {
|
|
this.s3Client = new S3Client({
|
|
endPoint: config.s3.endpoint,
|
|
useSSL: true,
|
|
region: config.s3.region || "auto",
|
|
bucket: config.s3.bucket_name,
|
|
accessKey: config.s3.access_key,
|
|
secretKey: config.s3.secret_access_key,
|
|
});
|
|
this.mediaHasher = new MediaHasher();
|
|
}
|
|
|
|
/**
|
|
* @inheritdoc
|
|
*/
|
|
public async addFile(
|
|
file: File,
|
|
): Promise<Omit<UploadedFileMetadata, "blurhash">> {
|
|
const hash = await this.mediaHasher.getMediaHash(file);
|
|
const path = `${hash}/${file.name}`;
|
|
|
|
await this.s3Client.putObject(path, file.stream(), {
|
|
size: file.size,
|
|
});
|
|
|
|
return {
|
|
uploadedFile: file,
|
|
path,
|
|
hash,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @inheritdoc
|
|
*/
|
|
public async getFileByHash(
|
|
hash: string,
|
|
databaseHashFetcher: (sha256: string) => Promise<string | null>,
|
|
): Promise<File | null> {
|
|
const filename = await databaseHashFetcher(hash);
|
|
if (!filename) {
|
|
return null;
|
|
}
|
|
return this.getFile(filename);
|
|
}
|
|
|
|
/**
|
|
* @inheritdoc
|
|
*/
|
|
public async getFile(filename: string): Promise<File | null> {
|
|
try {
|
|
await this.s3Client.statObject(filename);
|
|
const file = await this.s3Client.getObject(filename);
|
|
const arrayBuffer = await file.arrayBuffer();
|
|
return new File([arrayBuffer], filename, {
|
|
type: file.headers.get("Content-Type") || undefined,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @inheritdoc
|
|
*/
|
|
public async deleteFileByUrl(url: string): Promise<void> {
|
|
const urlObj = new URL(url);
|
|
const path = urlObj.pathname.slice(1); // Remove leading slash
|
|
await this.s3Client.deleteObject(path);
|
|
}
|
|
}
|