| 1 | import { env } from "cloudflare:workers"; |
| 2 | import { data } from "react-router"; |
| 3 | |
| 4 | import { DOCS_VIEWER_HEADER, DOC_MAX_FILE_BYTES } from "@g1t/contracts"; |
| 5 | |
| 6 | import type { Route } from "./+types/upload"; |
| 7 | import { assertSameOrigin, requireUser, roleIn } from "../../../lib/session.server"; |
| 8 | |
| 9 | /** |
| 10 | * A file put in a page (an image, a PDF, an attachment): |
| 11 | * `POST <site>/<workspace>/-/docs/upload?page=<id>&name=<file name>` with |
| 12 | * the file as the body. The docs service checks the viewer can edit the |
| 13 | * page, keeps the file, and answers with its address on the usercontent |
| 14 | * origin, where it is served, never on the site. |
| 15 | */ |
| 16 | export async function action({ params, context, request }: Route.ActionArgs) { |
| 17 | assertSameOrigin(request); |
| 18 | const viewer = requireUser(context, request); |
| 19 | if (!roleIn(viewer, params.owner)) throw data(null, { status: 404 }); |
| 20 | const url = new URL(request.url); |
| 21 | const length = Number(request.headers.get("content-length") ?? "0"); |
| 22 | if (!length || length > DOC_MAX_FILE_BYTES) { |
| 23 | return Response.json({ ok: false, error: { code: "invalid", message: `Files can be up to ${DOC_MAX_FILE_BYTES / 1024 / 1024} MB.` } }); |
| 24 | } |
| 25 | const target = new URL("https://docs/files"); |
| 26 | target.searchParams.set("workspace", params.owner.toLowerCase()); |
| 27 | target.searchParams.set("page", url.searchParams.get("page") ?? ""); |
| 28 | target.searchParams.set("name", url.searchParams.get("name") ?? "file"); |
| 29 | try { |
| 30 | const answer = await env.DOCS.fetch(target.toString(), { |
| 31 | method: "PUT", |
| 32 | headers: { |
| 33 | "content-type": request.headers.get("content-type") ?? "application/octet-stream", |
| 34 | "content-length": String(length), |
| 35 | [DOCS_VIEWER_HEADER]: JSON.stringify(viewer), |
| 36 | }, |
| 37 | body: request.body, |
| 38 | }); |
| 39 | return new Response(answer.body, { headers: { "content-type": "application/json", "cache-control": "no-store" } }); |
| 40 | } catch (error) { |
| 41 | console.error("docs: upload", error); |
| 42 | return Response.json({ ok: false, error: { code: "conflict", message: "Docs didn't answer. Try again." } }); |
| 43 | } |
| 44 | } |