Initial commit

This commit is contained in:
makearmy 2025-09-22 10:37:53 -04:00
commit 78f8d225ee
21173 changed files with 2907774 additions and 0 deletions

View file

@ -0,0 +1,25 @@
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const BGBYE_URL =
process.env.BGBYE_URL ||
process.env.BG_BYE_URL ||
process.env.BGREMOVER_BASE_URL ||
"http://bgbye:7001";
export async function GET() {
try {
const r = await fetch(`${BGBYE_URL}/methods`, { cache: "no-store" });
const body = await r.text();
return new Response(body, {
status: r.status,
headers: { "content-type": r.headers.get("content-type") || "application/json" },
});
} catch {
return new Response(JSON.stringify({ methods: [] }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
}

43
app/api/bgremove/route.ts Normal file
View file

@ -0,0 +1,43 @@
// /app/api/bgremove/route.ts
import { NextResponse } from "next/server";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const BGBYE_URL =
process.env.BGBYE_URL ||
process.env.BG_BYE_URL ||
process.env.BGREMOVER_BASE_URL || // <-- support your existing env var
"http://bgbye:7001";
export async function POST(req: Request) {
try {
const inForm = await req.formData();
const method = String(inForm.get("method") || "");
const file = inForm.get("file") as any;
// Loosen the guard: some Node/undici builds return a File-like Blob from a different realm
if (!file || !method) {
return NextResponse.json({ error: "file and method are required" }, { status: 400 });
}
const outForm = new FormData();
const filename = (file as any).name || "upload";
outForm.set("method", method);
outForm.set("file", file, filename);
const res = await fetch(`${BGBYE_URL}/remove_background/`, { method: "POST", body: outForm });
const buf = await res.arrayBuffer();
return new NextResponse(buf, {
status: res.status,
headers: {
"content-type": res.headers.get("content-type") || "application/octet-stream",
"cache-control": "no-store",
},
});
} catch (err: any) {
return NextResponse.json({ error: String(err?.message || err) }, { status: 500 });
}
}

View file

@ -0,0 +1,48 @@
import { NextResponse } from 'next/server';
import path from 'node:path';
import fs from 'node:fs/promises';
const BASE_DIR = '/app/files';
export async function GET(req: Request) {
try {
const url = new URL(req.url);
const raw = url.searchParams.get('path');
if (!raw) {
return NextResponse.json({ error: 'Missing path' }, { status: 400 });
}
const safe = path.normalize('/' + raw).replace(/^\/+/, '/');
const target = path.resolve(BASE_DIR, '.' + safe);
if (!target.startsWith(BASE_DIR)) {
return NextResponse.json({ error: 'Invalid path' }, { status: 400 });
}
const st = await fs.stat(target).catch(() => null);
if (!st || !st.isFile()) {
return NextResponse.json({ error: 'Not a file' }, { status: 400 });
}
const data = await fs.readFile(target);
// naive content-type guess
const ext = path.extname(target).toLowerCase();
const ctype =
ext === '.pdf' ? 'application/pdf' :
ext === '.png' ? 'image/png' :
ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' :
ext === '.webp' ? 'image/webp' :
ext === '.txt' ? 'text/plain; charset=utf-8' :
'application/octet-stream';
return new Response(data, {
headers: {
'Content-Type': ctype,
'Content-Length': String(data.byteLength),
'Content-Disposition': `inline; filename="${path.basename(target)}"`,
'Cache-Control': 'no-store',
}
});
} catch (e: any) {
return NextResponse.json({ error: e?.message ?? 'Unknown error' }, { status: 500 });
}
}

View file

@ -0,0 +1,44 @@
import { stat } from "fs/promises";
import { createReadStream } from "fs";
import path from "path";
export const dynamic = "force-dynamic";
export const revalidate = 0;
const ROOT = process.env.FILES_ROOT || "/app/files";
function safeJoin(root: string, p: string) {
const raw = path.normalize("/" + (p || "/"));
const abs = path.resolve(root, "." + raw);
if (!abs.startsWith(path.resolve(root))) throw new Error("Invalid path");
return abs;
}
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const p = searchParams.get("path");
if (!p) return new Response(JSON.stringify({ error: "Missing path" }), { status: 400 });
const abs = safeJoin(ROOT, p);
const s = await stat(abs);
if (s.isDirectory()) {
return new Response(JSON.stringify({ error: "Is a directory" }), { status: 400 });
}
const stream = createReadStream(abs);
const fileName = path.basename(abs);
return new Response(stream as any, {
headers: {
"Content-Type": "application/octet-stream",
"Content-Length": String(s.size),
"Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
"Cache-Control": "no-store",
}
});
} catch (e: any) {
const msg = e?.message || "Not found";
const code = msg === "Invalid path" ? 400 : 404;
return new Response(JSON.stringify({ error: msg }), { status: code, headers: { "Cache-Control": "no-store" } });
}
}

View file

@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
import fs from "node:fs/promises";
import path from "node:path";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const BASE = "/app/files";
function safeJoin(base: string, reqPath: string) {
const rel = reqPath.startsWith("/") ? reqPath : `/${reqPath}`;
const full = path.resolve(base, "." + rel);
if (!full.startsWith(base)) throw new Error("Outside base");
return full;
}
const CONTENT_MAP: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".svg": "image/svg+xml",
".txt": "text/plain; charset=utf-8",
".json": "application/json; charset=utf-8",
".pdf": "application/pdf",
};
export async function GET(req: Request) {
try {
const url = new URL(req.url);
const reqPath = url.searchParams.get("path");
if (!reqPath) return NextResponse.json({ error: "Missing path" }, { status: 400 });
const full = safeJoin(BASE, reqPath);
const stat = await fs.stat(full);
if (!stat.isFile()) return NextResponse.json({ error: "Not a file" }, { status: 400 });
const data = await fs.readFile(full);
const ext = path.extname(full).toLowerCase();
const type = CONTENT_MAP[ext] ?? "application/octet-stream";
return new NextResponse(data, {
status: 200,
headers: { "Content-Type": type, "Cache-Control": "public, max-age=300" },
});
} catch (e: any) {
return NextResponse.json({ error: e?.message ?? "Unknown" }, { status: 400 });
}
}

View file

@ -0,0 +1,41 @@
import { NextResponse } from 'next/server';
import path from 'node:path';
import fs from 'node:fs/promises';
const BASE_DIR = '/app/files';
export async function GET(req: Request) {
try {
const url = new URL(req.url);
const raw = url.searchParams.get('path') ?? '/';
const safe = path.normalize('/' + raw).replace(/^\/+/, '/'); // normalize & ensure leading slash
const target = path.resolve(BASE_DIR, '.' + safe);
if (!target.startsWith(BASE_DIR)) {
return NextResponse.json({ error: 'Invalid path' }, { status: 400 });
}
const st = await fs.stat(target).catch(() => null);
if (!st || !st.isDirectory()) {
return NextResponse.json({ error: 'Not a directory' }, { status: 400 });
}
const entries = await fs.readdir(target, { withFileTypes: true });
const items = await Promise.all(entries.map(async (d) => {
const full = path.join(target, d.name);
const rel = path.posix.join(safe, d.name).replaceAll('\\', '/');
const s = await fs.stat(full);
return {
name: d.name,
path: rel,
type: d.isDirectory() ? 'dir' : 'file',
size: s.size,
mtime: s.mtimeMs,
};
}));
return NextResponse.json({ path: safe, items });
} catch (e: any) {
return NextResponse.json({ error: e?.message ?? 'Unknown error' }, { status: 500 });
}
}

View file

@ -0,0 +1,43 @@
// /var/www/makearmy.io/app/app/api/files/list/route.ts
import { NextResponse } from "next/server";
import { promises as fs } from "fs";
import { join, normalize } from "path";
const ROOT = "/app/files";
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const input = searchParams.get("path") || "/";
// Normalize and lock to ROOT to prevent traversal
const safeInput = input.startsWith("/") ? input : `/${input}`;
const fullPath = normalize(join(ROOT, `.${safeInput}`));
if (!fullPath.startsWith(ROOT)) {
return NextResponse.json({ error: "Invalid path" }, { status: 400 });
}
try {
const entries = await fs.readdir(fullPath, { withFileTypes: true });
const items = await Promise.all(
entries.map(async (d) => {
const p = join(fullPath, d.name);
const s = await fs.stat(p);
return {
name: d.name,
isDir: d.isDirectory(),
size: s.size,
mtime: s.mtimeMs,
};
})
);
return NextResponse.json({ path: safeInput, items });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message ?? String(err) },
{ status: 404 }
);
}
}

View file

@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import fssync from "node:fs";
import path from "node:path";
import mime from "mime";
const BASE = "/app/files";
function safeJoin(base: string, reqPath: string) {
const decoded = decodeURIComponent(reqPath || "/");
const normalized = path.posix.normalize("/" + decoded).replace(/^(\.\.(\/|\\|$))+/g, "");
const full = path.join(base, normalized);
if (!full.startsWith(base)) throw new Error("Invalid path");
return full;
}
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const p = searchParams.get("path");
if (!p) return NextResponse.json({ ok: false, error: "Missing path" }, { status: 400 });
const abs = safeJoin(BASE, p);
if (!fssync.existsSync(abs) || !fssync.statSync(abs).isFile()) {
return NextResponse.json({ ok: false, error: "Not found" }, { status: 404 });
}
const stream = fssync.createReadStream(abs);
const type = mime.getType(abs) || "application/octet-stream";
return new Response(stream as any, {
headers: {
"Content-Type": type,
"Cache-Control": "public, max-age=3600",
},
});
} catch (err: any) {
return NextResponse.json({ ok: false, error: err?.message || "Error" }, { status: 400 });
}
}

50
app/api/files/route.ts Normal file
View file

@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
import fs from "node:fs/promises";
import fssync from "node:fs";
import path from "node:path";
const BASE = "/app/files"; // this is /var/www/makearmy.io/app/files on the host
function safeJoin(base: string, reqPath: string) {
const decoded = decodeURIComponent(reqPath || "/");
// normalize, strip traversal, and join under BASE
const normalized = path.posix.normalize("/" + decoded).replace(/^(\.\.(\/|\\|$))+/g, "");
const full = path.join(base, normalized);
if (!full.startsWith(base)) throw new Error("Invalid path");
return full;
}
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const p = searchParams.get("path") || "/";
const abs = safeJoin(BASE, p);
const entries = await fs.readdir(abs, { withFileTypes: true });
const rows = await Promise.all(entries.map(async (ent) => {
const full = path.join(abs, ent.name);
const stat = await fs.stat(full);
const isDir = ent.isDirectory();
return {
name: ent.name,
type: isDir ? "dir" : "file",
size: isDir ? null : stat.size,
mtime: stat.mtime.toISOString(),
path: path.posix.join(p.endsWith("/") ? p : p + "/", ent.name),
// raw download/view URL (served by /api/files/raw)
url: isDir ? null : `/api/files/raw?path=${encodeURIComponent(path.posix.join(p, ent.name))}`,
};
}));
// Sort: directories first, then files alphabetically
rows.sort((a, b) => {
if (a.type !== b.type) return a.type === "dir" ? -1 : 1;
return a.name.localeCompare(b.name, undefined, { sensitivity: "base" });
});
return NextResponse.json({ ok: true, path: p, items: rows });
} catch (err: any) {
return NextResponse.json({ ok: false, error: err?.message || "Error" }, { status: 400 });
}
}

View file

@ -0,0 +1,111 @@
// app/api/options/[collection]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
const NM_FIELD = "nm"; // wavelength field in laser_source
// Parse wavelength that might be stored as "1064", "1064nm", "1,064", etc.
function parseNm(v: any): number | null {
const s = String(v ?? "").replace(/[^0-9.]/g, "");
if (!s) return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
// Target → wavelength range (nm)
function nmRangeForTarget(t?: string): [number, number] | null {
switch (t) {
case "settings_fiber": return [1000, 1100];
case "settings_uv": return [300, 400];
case "settings_co2gan":
case "settings_co2gal": return [10000, 11000];
default: return null;
}
}
// Generic lookups (request only fields we know exist)
const GENERIC: Record<
string,
{ path: string; fields: string[]; label: (x: any) => string }
> = {
material: { path: "/items/material", fields: ["id", "name"], label: (x) => x.name ?? String(x.id) },
material_coating: { path: "/items/material_coating", fields: ["id", "name"], label: (x) => x.name ?? String(x.id) },
material_color: { path: "/items/material_color", fields: ["id", "name"], label: (x) => x.name ?? String(x.id) },
material_opacity: { path: "/items/material_opacity", fields: ["id", "opacity"], label: (x) => String(x.opacity ?? x.id) },
laser_software: { path: "/items/laser_software", fields: ["id", "name"], label: (x) => x.name ?? String(x.id) },
};
async function fetchDirectus<T>(pathname: string, params: URLSearchParams) {
return directusFetch<T>(`${pathname}?${params.toString()}`);
}
export async function GET(req: NextRequest) {
try {
const url = new URL(req.url);
const collection = url.pathname.split("/").pop() || "";
const q = url.searchParams.get("q")?.trim() || "";
const limit = Number(url.searchParams.get("limit") || "400");
const target = url.searchParams.get("target") || undefined;
// ----- generic tables -----
const gen = GENERIC[collection];
if (gen) {
const params = new URLSearchParams();
params.set("fields", gen.fields.join(","));
params.set("limit", String(limit));
if (q) params.set("search", q);
const { data } = await fetchDirectus<{ data: any[] }>(gen.path, params);
const out = (data ?? [])
.map((x) => ({ id: String(x.id), label: gen.label(x) }))
.sort((a, b) => a.label.localeCompare(b.label));
return NextResponse.json({ data: out });
}
// ----- laser_source (uses submission_id as the key) -----
if (collection === "laser_source") {
const range = nmRangeForTarget(target);
if (!range) {
return NextResponse.json(
{ error: "missing/invalid target for laser_source" },
{ status: 400 }
);
}
const params = new URLSearchParams();
// IMPORTANT: request submission_id instead of id
params.set("fields", ["submission_id", "make", "model", NM_FIELD].join(","));
params.set("limit", String(limit));
if (q) params.set("search", q);
const { data } = await fetchDirectus<{ data: any[] }>("/items/laser_source", params);
const rows = data ?? [];
const [lo, hi] = range;
const filtered = rows.filter((x) => {
const nm = parseNm(x[NM_FIELD]);
return nm !== null && nm >= lo && nm <= hi;
});
const out = filtered
.map((x) => ({
id: String(x.submission_id), // <- use submission_id
label: [x.make, x.model].filter(Boolean).join(" ").trim() || String(x.submission_id),
sortKey: [(x.make ?? "").toLowerCase(), (x.model ?? "").toLowerCase()].join(" "),
}))
.filter((o) => o.id)
.sort((a, b) => a.sortKey.localeCompare(b.sortKey))
.map(({ id, label }) => ({ id, label }));
return NextResponse.json({ data: out });
}
return NextResponse.json({ error: "unsupported collection" }, { status: 400 });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message || "Unknown error" },
{ status: 500 }
);
}
}

View file

@ -0,0 +1,40 @@
// app/api/options/lens/route.ts
import { NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
/** pick a decent label from whatever fields are readable */
function pickLabel(it: any) {
const mm = [it?.make, it?.model].filter(Boolean).join(" ").trim();
if (mm) return mm;
if (it?.name) return String(it.name);
const f = it?.focal_length ?? it?.f ?? it?.fl;
if (f != null) return `${mm ? mm + " " : ""}${f} mm`.trim();
return String(it?.label ?? it?.title ?? it?.id ?? "");
}
export async function GET(req: Request) {
const { searchParams } = new URL(req.url);
const target = searchParams.get("target") || ""; // required
const q = (searchParams.get("q") || "").toLowerCase();
const limit = Number(searchParams.get("limit") || "500");
// Fiber / CO2 Galvo / UV -> scan lens ; CO2 Gantry -> focus lens
const isGantry = target === "settings_co2gan";
const coll = isGantry ? "laser_focus_lens" : "laser_scan_lens";
// Avoid explicit fields -> prevents 403 on disallowed fields
const res = await directusFetch<{ data: any[] }>(`/items/${coll}?limit=${limit}`);
let items = res?.data ?? [];
let rows = items.map((it) => {
const label = pickLabel(it);
const search = Object.values(it ?? {}).join(" ").toLowerCase();
return { id: String(it?.id ?? ""), label, _search: search };
}).filter((r) => r.id);
if (q) rows = rows.filter((r) => r._search.includes(q));
rows.sort((a, b) => a.label.localeCompare(b.label));
return NextResponse.json({ data: rows.map(({ _search, ...r }) => r) });
}

View file

@ -0,0 +1,26 @@
import { NextRequest, NextResponse } from "next/server";
import { directusFetch } from "@/lib/directus";
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const target = searchParams.get("target") || "";
const group = searchParams.get("group") || "";
const field = searchParams.get("field") || "type";
if (!target || !group) return NextResponse.json({ error: "missing target/group" }, { status: 400 });
const meta = await directusFetch<any>(`/fields/${target}/${group}?fields=meta`);
const fields = meta?.data?.meta?.options?.fields ?? [];
const nested = fields.find((f: any) => (f?.field ?? f?.key) === field);
const choices = nested?.options?.choices ?? nested?.meta?.options?.choices ?? [];
const out = (choices as any[])
.map((c) => ({
id: String(c.value ?? c.text ?? c.label ?? ""),
label: String(c.text ?? c.label ?? c.value ?? ""),
}))
.filter((o) => o.id)
.sort((a, b) => a.label.localeCompare(b.label));
return NextResponse.json({ data: out });
}

View file

@ -0,0 +1,158 @@
// app/api/submit/project/route.ts
import { NextRequest, NextResponse } from "next/server";
import {
uploadFile,
createProjectRow,
patchProject,
bytesFromMB,
} from "@/lib/directus";
// Optional: tweak via env
const MAX_MB = Number(process.env.FILE_MAX_MB || 25);
const MAX_BYTES = bytesFromMB(MAX_MB);
// ultra-simple in-memory rate limiter (per server instance)
const BUCKET = new Map<string, { c: number; resetAt: number }>();
const WINDOW_MS = Number(process.env.RATE_LIMIT_WINDOW || 60) * 1000;
const MAX_REQ = Number(process.env.RATE_LIMIT_MAX || 15);
function rateLimitOk(ip: string) {
const now = Date.now();
const rec = BUCKET.get(ip);
if (!rec || now > rec.resetAt) {
BUCKET.set(ip, { c: 1, resetAt: now + WINDOW_MS });
return true;
}
if (rec.c >= MAX_REQ) return false;
rec.c += 1;
return true;
}
export const runtime = "nodejs";
export async function POST(req: NextRequest) {
try {
const ip =
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
"0.0.0.0";
if (!rateLimitOk(ip)) {
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
}
const ct = req.headers.get("content-type") || "";
if (!ct.includes("multipart/form-data")) {
return NextResponse.json(
{ error: "Expected multipart/form-data" },
{ status: 400 }
);
}
const form = await req.formData();
// Required read-side field names from your repo:
// title, body (markdown), uploader, category, tags[], p_image (file), p_files (M2M to files)
const title = String(form.get("title") || "").trim();
const uploader = String(form.get("uploader") || "").trim();
const category = String(form.get("category") || "").trim();
const body = String(form.get("body") || form.get("description") || "").trim();
if (!title || !uploader || !body) {
return NextResponse.json(
{ error: "Missing required fields: title, uploader, body" },
{ status: 400 }
);
}
// tags: allow comma-separated string or JSON array
let tags: string[] = [];
const rawTags = form.get("tags");
if (typeof rawTags === "string" && rawTags.trim()) {
try {
// Accept JSON array
const maybeArray = JSON.parse(rawTags);
if (Array.isArray(maybeArray)) {
tags = maybeArray.map((t) => String(t).trim()).filter(Boolean);
} else {
// Fallback: comma list
tags = rawTags
.split(",")
.map((t) => t.trim())
.filter(Boolean);
}
} catch {
// Comma-separated
tags = rawTags
.split(",")
.map((t) => t.trim())
.filter(Boolean);
}
}
// Optional license (not shown on read pages, but harmless to store)
const license =
(form.get("license") && String(form.get("license")).trim()) ||
undefined;
// Upload hero image (single)
const hero = form.get("image") as File | null; // input name="image"
let p_image_id: string | undefined;
if (hero && typeof hero === "object" && "size" in hero) {
if (hero.size > MAX_BYTES) {
return NextResponse.json(
{ error: `Hero image exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(hero, (hero as File).name || "project-image");
p_image_id = up.id;
}
// Upload attachments (multiple)
const fileBlobs = form.getAll("files").filter(Boolean) as File[];
const attachIds: string[] = [];
for (const f of fileBlobs.slice(0, 20)) {
if (f.size > MAX_BYTES) {
return NextResponse.json(
{ error: `One of the files exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(f, (f as File).name || "attachment");
attachIds.push(up.id);
}
// 1) Create the project row
const { data: created } = await createProjectRow({
title,
body, // you render `project.body` in detail page
uploader, // exact key used by your list/detail
category,
tags, // stored as array
...(license ? { license } : {}),
status: "pending",
submitted_via: "makearmy-app",
submitted_at: new Date().toISOString(),
});
// 2) Patch hero image + M2M attachments in one go
// For M2M (p_files), Directus accepts nested objects to create junction rows
// e.g. [{ directus_files_id: "<file-id>" }, ...]
const patch: Record<string, any> = {};
if (p_image_id) patch.p_image = p_image_id;
if (attachIds.length) {
patch.p_files = attachIds.map((id) => ({ directus_files_id: id }));
}
if (Object.keys(patch).length) {
await patchProject(created.id, patch);
}
return NextResponse.json({ ok: true, id: created.id });
} catch (err: any) {
return NextResponse.json(
{ error: err?.message || "Unknown error" },
{ status: 500 }
);
}
}

View file

@ -0,0 +1,391 @@
// app/api/submit/settings/route.ts
import { NextRequest, NextResponse } from "next/server";
import {
bytesFromMB,
createSettingsItem,
directusFetch,
uploadFile,
} from "@/lib/directus";
/**
* Accepts EITHER:
* - application/json (photo/screen can be data URLs: photo_data, screen_data)
* - multipart/form-data with:
* - "payload" = JSON string (same shape as JSON body)
* - "photo" = result image (REQUIRED)
* - "screen" = screenshot image (optional)
*
* Targets (collections):
* - settings_fiber (+ laser_soft, repeat_all)
* - settings_co2gan
* - settings_co2gal
* - settings_uv
* */
export const runtime = "nodejs";
const MAX_MB = Number(process.env.FILE_MAX_MB || 25);
const MAX_BYTES = bytesFromMB(MAX_MB);
// light in-memory rate limiter
const BUCKET = new Map<string, { c: number; resetAt: number }>();
const WINDOW_MS = Number(process.env.RATE_LIMIT_WINDOW || 60) * 1000;
const MAX_REQ = Number(process.env.RATE_LIMIT_MAX || 15);
function rateLimitOk(ip: string) {
const now = Date.now();
const rec = BUCKET.get(ip);
if (!rec || now > rec.resetAt) {
BUCKET.set(ip, { c: 1, resetAt: now + WINDOW_MS });
return true;
}
if (rec.c >= MAX_REQ) return false;
rec.c += 1;
return true;
}
type Target = "settings_fiber" | "settings_co2gan" | "settings_co2gal" | "settings_uv";
/** Map target + kind → Directus folder name */
function folderName(target: Target, kind: "photo" | "screen") {
const base =
target === "settings_fiber"
? "le_fiber_settings"
: target === "settings_uv"
? "le_uv_settings"
: target === "settings_co2gal"
? "le_co2gal_settings"
: "le_co2gan_settings";
return kind === "photo" ? `${base}_photos` : `${base}_screenshots`;
}
/** Lookup a folder id by name, returns null if not found */
async function findFolderIdByName(name: string): Promise<string | null> {
try {
const res = await directusFetch<{ data: Array<{ id: string }> }>(
`/folders?limit=1&fields=id&filter[name][_eq]=${encodeURIComponent(name)}`
);
const id = res?.data?.[0]?.id ?? null;
return id || null;
} catch {
return null;
}
}
/** Patch a file to move it into a folder (no-op if folderId is null) */
async function moveFileToFolder(fileId: string, folderId: string | null) {
if (!fileId || !folderId) return;
await directusFetch(`/files/${fileId}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ folder: folderId }),
});
}
// Whitelists for repeaters (matches your Directus repeater schemas)
const FILL_KEYS = new Set([
"name",
"power",
"speed",
"interval",
"pass",
"type",
"flood",
"air",
"frequency",
"pulse",
"angle",
"auto",
"increment",
"cross",
]);
const LINE_KEYS = new Set([
"name",
"power",
"speed",
"perf",
"cut",
"skip",
"pass",
"air",
"frequency",
"pulse",
"wobble",
"step",
"size",
]);
const RASTER_KEYS = new Set([
"name",
"power",
"speed",
"type",
"dither",
"halftone_cell",
"halftone_angle",
"inversion",
"interval",
"dot",
"pass",
"air",
"frequency",
"pulse",
"cross",
]);
function sanitizeNumber(n: any, fallback: number | null = null) {
if (n === null || n === undefined || n === "") return fallback;
const v = Number(n);
return Number.isFinite(v) ? v : fallback;
}
function sanitizeRepeaterRow(
row: Record<string, any>,
allowed: Set<string>
): Record<string, any> {
const out: Record<string, any> = {};
for (const k of Object.keys(row || {})) {
if (!allowed.has(k)) continue;
if (
[
"power",
"speed",
"interval",
"pass",
"halftone_cell",
"halftone_angle",
"dot",
"frequency",
"pulse",
"angle",
"increment",
"step",
"size",
].includes(k)
) {
out[k] = sanitizeNumber(row[k]);
} else if (["auto", "cross", "wobble", "perf", "air", "flood", "inversion"].includes(k)) {
out[k] = !!row[k];
} else {
out[k] = row[k];
}
}
return out;
}
async function readJsonOrMultipart(req: NextRequest) {
const ct = req.headers.get("content-type") || "";
if (ct.includes("multipart/form-data")) {
const form = await req.formData();
const payloadRaw = String(form.get("payload") || "{}");
let body: any = {};
try {
body = JSON.parse(payloadRaw);
} catch {
throw new Error("Invalid JSON in 'payload' field");
}
const files = {
photo: (form.get("photo") as File) || null,
screen: (form.get("screen") as File) || null,
};
return { mode: "multipart" as const, body, files };
}
if (ct.includes("application/json")) {
const body = await req.json();
return { mode: "json" as const, body, files: { photo: null as File | null, screen: null as File | null } };
}
throw new Error("Unsupported content-type. Use JSON or multipart/form-data.");
}
export async function POST(req: NextRequest) {
const started = Date.now();
try {
const ip =
req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
"0.0.0.0";
if (!rateLimitOk(ip)) {
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
}
const { mode, body, files } = await readJsonOrMultipart(req);
const target: Target = body?.target;
if (!["settings_fiber", "settings_co2gan", "settings_co2gal", "settings_uv"].includes(target as any)) {
return NextResponse.json({ error: "Invalid target" }, { status: 400 });
}
// Required base fields
const setting_title = String(body?.setting_title || body?.title || "").trim();
const uploader = String(body?.uploader || "").trim();
// Relations (required)
const mat = body?.mat ?? null;
const mat_coat = body?.mat_coat ?? null;
const mat_color = body?.mat_color ?? null;
const mat_opacity = body?.mat_opacity ?? null;
const source = body?.source ?? null;
const lens = body?.lens ?? null;
// Numbers
const mat_thickness = sanitizeNumber(body?.mat_thickness, null);
const focus = sanitizeNumber(body?.focus, null);
// Notes (optional)
const setting_notes = String(body?.setting_notes || body?.notes || "").trim() || "";
// Fiber-only (required)
const laser_soft =
target === "settings_fiber" ? (body?.laser_soft ?? null) : null;
const repeat_all =
target === "settings_fiber" ? sanitizeNumber(body?.repeat_all, null) : null;
// Validate requireds
const missing: string[] = [];
if (!setting_title) missing.push("setting_title");
if (!uploader) missing.push("uploader");
if (!source) missing.push("source");
if (!lens) missing.push("lens");
if (focus === null || !Number.isFinite(focus)) missing.push("focus");
if (!mat) missing.push("mat");
if (!mat_coat) missing.push("mat_coat");
if (!mat_color) missing.push("mat_color");
if (!mat_opacity) missing.push("mat_opacity");
if (target === "settings_fiber") {
if (!laser_soft) missing.push("laser_soft");
if (repeat_all === null || !Number.isFinite(repeat_all)) missing.push("repeat_all");
}
// Handle files (photo required)
let photo_id: string | null = null;
let screen_id: string | null = null;
// If multipart, use file objects. Else allow base64 in JSON: photo_data/screen_data
if (mode === "multipart") {
if (!files.photo) missing.push("photo");
if (files.photo) {
if (files.photo.size > MAX_BYTES) {
return NextResponse.json(
{ error: `Photo exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(files.photo, (files.photo as File).name || "photo");
photo_id = (up as any)?.id ?? null;
// after upload, move into appropriate folder
const folder = await findFolderIdByName(folderName(target, "photo"));
await moveFileToFolder(String(photo_id), folder);
}
if (files.screen) {
if (files.screen.size > MAX_BYTES) {
return NextResponse.json(
{ error: `Screenshot exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(files.screen, (files.screen as File).name || "screen");
screen_id = (up as any)?.id ?? null;
const folder = await findFolderIdByName(folderName(target, "screen"));
await moveFileToFolder(String(screen_id), folder);
}
} else {
// JSON mode with optional base64 strings
const pushBase64 = async (dataUrl: string, name: string) => {
const base64 = (dataUrl || "").split(",")[1] || "";
if (!base64) return null;
const raw = Buffer.from(base64, "base64");
if (raw.byteLength > MAX_BYTES) throw new Error(`${name} exceeds ${MAX_MB} MB`);
const blob = new Blob([raw]);
const up = await uploadFile(blob as any, name);
return (up as any)?.id ?? null;
};
if (body?.photo_data) {
photo_id = await pushBase64(body.photo_data, "photo");
const folder = await findFolderIdByName(folderName(target, "photo"));
await moveFileToFolder(String(photo_id), folder);
} else {
missing.push("photo");
}
if (body?.screen_data) {
screen_id = await pushBase64(body.screen_data, "screen");
const folder = await findFolderIdByName(folderName(target, "screen"));
await moveFileToFolder(String(screen_id), folder);
}
}
if (missing.length) {
return NextResponse.json(
{ error: `Missing required: ${missing.join(", ")}` },
{ status: 400 }
);
}
// Repeaters
const fillsRaw = Array.isArray(body?.fill_settings) ? body.fill_settings : body?.fills || [];
const linesRaw = Array.isArray(body?.line_settings) ? body.line_settings : body?.lines || [];
const rastersRaw = Array.isArray(body?.raster_settings) ? body.raster_settings : body?.rasters || [];
const fill_settings = (fillsRaw as any[]).map((r) => sanitizeRepeaterRow(r, FILL_KEYS));
const line_settings = (linesRaw as any[]).map((r) => sanitizeRepeaterRow(r, LINE_KEYS));
const raster_settings = (rastersRaw as any[]).map((r) => sanitizeRepeaterRow(r, RASTER_KEYS));
// Build record
const nowIso = new Date().toISOString();
const payload: Record<string, any> = {
setting_title,
uploader,
setting_notes,
// relations
mat,
mat_coat,
mat_color,
mat_opacity,
source,
lens,
// numbers
focus,
mat_thickness,
// files
photo: photo_id,
screen: screen_id,
// repeaters
fill_settings,
line_settings,
raster_settings,
// meta
submission_date: nowIso,
last_modified_date: nowIso,
status: "pending",
submitted_via: "makearmy-app",
submitted_at: nowIso,
};
if (target === "settings_fiber") {
payload.laser_soft = laser_soft;
payload.repeat_all = repeat_all;
}
const created = await createSettingsItem(target, payload);
// normalize PK to always provide "id" (your tables use submission_id)
const newId =
(created as any)?.submission_id ??
(created as any)?.data?.submission_id ??
(created as any)?.id ??
(created as any)?.data?.id ??
null;
return NextResponse.json({
ok: true,
id: newId,
submission_id: newId,
took_ms: Date.now() - started,
});
} catch (err: any) {
const msg = err?.message || "Unknown error";
return NextResponse.json({ error: msg }, { status: 500 });
}
}