mike-backend / backend /src /lib /storage.ts
bardd's picture
Deploy Mike backend-only Space
06671aa verified
Raw History Blame Contribute Delete
4.15 kB
/**
* Local filesystem storage — replaces Cloudflare R2.
* Files are stored under LOCAL_STORAGE_PATH (default: /home/ubuntu/mike-storage).
*/
import fs from "fs";
import path from "path";
const BASE = process.env.LOCAL_STORAGE_PATH || "/home/ubuntu/mike-storage";
export const storageEnabled = true;
function fullPath(key: string): string {
return path.join(BASE, key);
}
async function ensureDir(filePath: string): Promise<void> {
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
}
// ---------------------------------------------------------------------------
// Upload
// ---------------------------------------------------------------------------
export async function uploadFile(
key: string,
content: ArrayBuffer,
_contentType: string,
): Promise<void> {
const fp = fullPath(key);
await ensureDir(fp);
await fs.promises.writeFile(fp, Buffer.from(content));
}
// ---------------------------------------------------------------------------
// Download
// ---------------------------------------------------------------------------
export async function downloadFile(key: string): Promise<ArrayBuffer | null> {
try {
const fp = fullPath(key);
const buf = await fs.promises.readFile(fp);
return buf.buffer as ArrayBuffer;
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// Delete
// ---------------------------------------------------------------------------
export async function deleteFile(key: string): Promise<void> {
try {
const fp = fullPath(key);
await fs.promises.unlink(fp);
} catch {}
}
// ---------------------------------------------------------------------------
// Signed URL — for local storage, return a direct /download/... path
// ---------------------------------------------------------------------------
export async function getSignedUrl(
key: string,
_expiresIn = 3600,
downloadFilename?: string,
): Promise<string | null> {
return `/download/${encodeURIComponent(key)}${downloadFilename ? `?filename=${encodeURIComponent(downloadFilename)}` : ""}`;
}
export function normalizeDownloadFilename(name: string): string {
const trimmed = name.trim();
const base = trimmed || "download";
return base.replace(/[\x00-\x1F\x7F]/g, "_").replace(/[\\/]/g, "_");
}
export function sanitizeDispositionFilename(name: string): string {
return normalizeDownloadFilename(name).replace(/["\\]/g, "_");
}
export function encodeRFC5987(str: string): string {
return encodeURIComponent(str).replace(
/['()*]/g,
(c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(),
);
}
export function buildContentDisposition(
kind: "inline" | "attachment",
filename: string,
): string {
const normalized = normalizeDownloadFilename(filename);
return `${kind}; filename="${sanitizeDispositionFilename(normalized)}"; filename*=UTF-8''${encodeRFC5987(normalized)}`;
}
// ---------------------------------------------------------------------------
// Storage key helpers
// ---------------------------------------------------------------------------
export function storageKey(
userId: string,
docId: string,
filename: string,
): string {
return `documents/${userId}/${docId}/source${storageExtension(filename, ".bin")}`;
}
export function pdfStorageKey(
userId: string,
docId: string,
stem: string,
): string {
return `documents/${userId}/${docId}/${stem}.pdf`;
}
export function generatedDocKey(
userId: string,
docId: string,
filename: string,
): string {
return `generated/${userId}/${docId}/generated${storageExtension(filename, ".docx")}`;
}
export function versionStorageKey(
userId: string,
docId: string,
versionSlug: string,
filename: string,
): string {
return `documents/${userId}/${docId}/versions/${versionSlug}${storageExtension(filename, ".bin")}`;
}
function storageExtension(filename: string, fallback: string): string {
const lastDot = filename.lastIndexOf(".");
if (lastDot < 0) return fallback;
const ext = filename.slice(lastDot).toLowerCase();
return /^\.[a-z0-9]{1,16}$/.test(ext) ? ext : fallback;
}