Add photo attachments to parts

A bag falling apart after forty years still has the part number printed on it,
and the picture carries more than any field you could retype it into. Photos
attach from the part form; on a phone the picker opens the camera directly.

Files live beside the database in the same volume, with only metadata in SQLite
— blobs there bloat the database and complicate the VACUUM INTO backup. The
browser downscales to 2000px before uploading, honouring EXIF orientation via
createImageBitmap, which keeps an image library and its native dependencies out
of the server entirely.

Uploads are sniffed by content rather than trusted by their declared type, so a
file that merely claims to be a JPEG cannot be stored and served back from this
origin as something a browser will execute. SVG is refused for the same reason.
Reads are capped rather than trusting Content-Length, at most 12 photos per
part, and a row that fails to insert takes its file with it.

Deleting a photo or a part removes the files, not just the rows, and
`app.admin prune-images` sweeps anything a crash stranded. The README's backup
procedure now covers both halves; capturing only the database would have
silently lost every photo.

python-multipart returns for the upload, pinned at 0.0.32 — the version removed
earlier was 0.0.20, which carried advisories. Audit is clean.

Two frontend bugs surfaced while testing this in the browser: a photo count
changing left the list row stale, and the part form opened from the list's
cached copy rather than fetching current data.

Checks go from 197 to 271.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jay
2026-08-24 17:03:36 -04:00
parent 59949e91ca
commit 96d2a1a087
9 changed files with 742 additions and 26 deletions
+173 -5
View File
@@ -11,13 +11,15 @@ import hashlib
import json
import math
import os
import secrets
import sqlite3
from contextlib import asynccontextmanager
from typing import Annotated, Any, Literal
from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response
from fastapi import (Depends, FastAPI, File, Form, HTTPException, Query, Request,
Response, UploadFile)
from fastapi.exceptions import RequestValidationError
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import AfterValidator, BaseModel, Field
@@ -25,9 +27,15 @@ from . import auth, db
STATIC_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static")
# A downscaled phone photo lands around 300KB; the cap is generous enough for an
# un-resized original from a browser that couldn't downscale, and small enough
# that nothing can fill the volume by accident.
MAX_IMAGE_BYTES = 8 * 1024 * 1024
MAX_IMAGES_PER_PART = 12
CSP = (
"default-src 'self'; "
"img-src 'self' data:; "
"img-src 'self' data: blob:; "
"style-src 'self' 'unsafe-inline'; " # the UI sets inline style attributes
"script-src 'self'; "
"connect-src 'self'; "
@@ -110,6 +118,11 @@ PART_COLUMNS = [
]
class ImagePatch(BaseModel):
caption: Text | None = Field(default=None, max_length=300)
position: int | None = Field(default=None, ge=0)
class AdjustIn(BaseModel):
delta: float = Field(allow_inf_nan=False)
reason: Text = Field(default="", max_length=300)
@@ -165,12 +178,30 @@ def _tags_for(conn, part_ids: list[int]) -> dict[int, list[str]]:
return out
def _serialise(rows, specs, tags, cat_paths, loc_paths) -> list[dict]:
def _images_for(conn, part_ids: list[int]) -> dict[int, list[dict]]:
if not part_ids:
return {}
marks = ",".join("?" * len(part_ids))
rows = conn.execute(
f"""SELECT part_id, token, mime, bytes, caption, position
FROM part_images WHERE part_id IN ({marks})
ORDER BY position, id""",
part_ids,
).fetchall()
out: dict[int, list[dict]] = {}
for r in rows:
out.setdefault(r["part_id"], []).append(dict(r))
return out
def _serialise(rows, specs, tags, cat_paths, loc_paths, images=None) -> list[dict]:
images = images or {}
out = []
for r in rows:
d = dict(r)
d["specs"] = specs.get(r["id"], [])
d["tags"] = tags.get(r["id"], [])
d["images"] = images.get(r["id"], [])
d["category_path"] = cat_paths.get(r["category_id"]) if r["category_id"] else None
d["location_path"] = loc_paths.get(r["location_id"]) if r["location_id"] else None
d["low_stock"] = (
@@ -224,6 +255,7 @@ def _fetch_part(conn, part_id: int) -> dict:
return _serialise(
[row], _specs_for(conn, [part_id]), _tags_for(conn, [part_id]),
db.tree_paths(conn, "categories"), db.tree_paths(conn, "locations"),
_images_for(conn, [part_id]),
)[0]
@@ -295,7 +327,9 @@ async def security_headers(request: Request, call_next):
else:
headers["Cache-Control"] = "no-cache"
elif request.url.path.startswith("/api/"):
headers["Cache-Control"] = "no-store"
# setdefault, not assignment: the image route serves immutable,
# token-addressed files and sets its own caching.
headers.setdefault("Cache-Control", "no-store")
return response
@@ -483,6 +517,7 @@ def list_parts(
items = _serialise(
rows, _specs_for(conn, ids), _tags_for(conn, ids),
db.tree_paths(conn, "categories"), db.tree_paths(conn, "locations"),
_images_for(conn, ids),
)
return {"total": total, "limit": limit, "offset": offset, "items": items}
@@ -565,10 +600,16 @@ def update_part(part_id: int, body: PartPatch, conn=Depends(db.get_db)):
@app.delete("/api/parts/{part_id}", dependencies=[Depends(auth.require_auth)])
def delete_part(part_id: int, conn=Depends(db.get_db)):
# Collect the image rows first: the cascade removes them from the database,
# but the files on disk would be left behind as orphans.
images = conn.execute(
"SELECT token, mime FROM part_images WHERE part_id = ?", (part_id,)
).fetchall()
cur = conn.execute("DELETE FROM parts WHERE id = ?", (part_id,))
if cur.rowcount == 0:
raise HTTPException(404, "Part not found")
conn.execute("DELETE FROM parts_fts WHERE rowid = ?", (part_id,))
db.delete_image_files(images)
return {"deleted": part_id}
@@ -606,6 +647,133 @@ def part_history(part_id: int, conn=Depends(db.get_db), limit: int = Query(defau
return {"items": [dict(r) for r in rows]}
# --- part images ---------------------------------------------------------
#
# Photos of the bag a part came out of, the print on a chip, a wiring note. The
# file is written to the volume beside the database; only metadata is stored in
# SQLite.
def _image_row(conn, part_id: int, token: str):
row = conn.execute(
"SELECT * FROM part_images WHERE part_id = ? AND token = ?", (part_id, token)
).fetchone()
if row is None:
raise HTTPException(404, "Image not found")
return row
@app.get("/api/parts/{part_id}/images", dependencies=[Depends(auth.require_auth)])
def list_images(part_id: int, conn=Depends(db.get_db)):
if conn.execute("SELECT 1 FROM parts WHERE id = ?", (part_id,)).fetchone() is None:
raise HTTPException(404, "Part not found")
return {"items": _images_for(conn, [part_id]).get(part_id, [])}
@app.post("/api/parts/{part_id}/images", dependencies=[Depends(auth.require_auth)],
status_code=201)
async def upload_image(
part_id: int,
file: UploadFile = File(...),
caption: str = Form(default=""),
conn=Depends(db.get_db),
):
if conn.execute("SELECT 1 FROM parts WHERE id = ?", (part_id,)).fetchone() is None:
raise HTTPException(404, "Part not found")
existing = conn.execute(
"SELECT COUNT(*) AS n FROM part_images WHERE part_id = ?", (part_id,)
).fetchone()["n"]
if existing >= MAX_IMAGES_PER_PART:
raise HTTPException(409, f"A part can hold at most {MAX_IMAGES_PER_PART} images")
# Read with a ceiling rather than trusting Content-Length, which a client
# controls. One byte over the cap is enough to know it is too big.
data = b""
while len(data) <= MAX_IMAGE_BYTES:
chunk = await file.read(256 * 1024)
if not chunk:
break
data += chunk
if len(data) > MAX_IMAGE_BYTES:
raise HTTPException(413, f"Images must be {MAX_IMAGE_BYTES // (1024 * 1024)}MB or smaller")
if not data:
raise HTTPException(422, "Empty upload")
# The declared content type is ignored; the bytes decide. That is what stops
# an HTML or SVG payload being stored and later served back from this origin.
mime = db.sniff_image(data[:32])
if mime is None:
raise HTTPException(415, "Not a supported image (JPEG, PNG, WEBP or GIF)")
token = secrets.token_urlsafe(16)
path = db.image_path(token, mime)
with open(path, "wb") as fh:
fh.write(data)
try:
nxt = conn.execute(
"SELECT COALESCE(MAX(position), -1) + 1 AS n FROM part_images WHERE part_id = ?",
(part_id,),
).fetchone()["n"]
conn.execute(
"INSERT INTO part_images(part_id, token, mime, bytes, caption, position) "
"VALUES (?,?,?,?,?,?)",
(part_id, token, mime, len(data), caption.strip()[:300], nxt),
)
conn.execute(
"UPDATE parts SET updated_at = datetime('now') WHERE id = ?", (part_id,)
)
except Exception:
# Don't leave a file behind for a row that never landed.
db.delete_image_files([{"token": token, "mime": mime}])
raise
return {"token": token, "mime": mime, "bytes": len(data),
"caption": caption.strip()[:300], "position": nxt}
@app.get("/api/parts/{part_id}/images/{token}", dependencies=[Depends(auth.require_auth)])
def get_image(part_id: int, token: str, conn=Depends(db.get_db)):
row = _image_row(conn, part_id, token)
path = db.image_path(row["token"], row["mime"])
if not os.path.exists(path):
raise HTTPException(404, "Image file is missing")
return FileResponse(
path,
media_type=row["mime"],
headers={
# The token addresses exactly these bytes and never changes, so the
# browser may keep it. Private, because it sits behind the login.
"Cache-Control": "private, max-age=31536000, immutable",
"Content-Disposition": "inline",
},
)
@app.patch("/api/parts/{part_id}/images/{token}", dependencies=[Depends(auth.require_auth)])
def update_image(part_id: int, token: str, body: ImagePatch, conn=Depends(db.get_db)):
_image_row(conn, part_id, token)
if body.caption is not None:
conn.execute(
"UPDATE part_images SET caption = ? WHERE part_id = ? AND token = ?",
(body.caption, part_id, token),
)
if body.position is not None:
conn.execute(
"UPDATE part_images SET position = ? WHERE part_id = ? AND token = ?",
(body.position, part_id, token),
)
return {"token": token}
@app.delete("/api/parts/{part_id}/images/{token}", dependencies=[Depends(auth.require_auth)])
def delete_image(part_id: int, token: str, conn=Depends(db.get_db)):
row = _image_row(conn, part_id, token)
conn.execute("DELETE FROM part_images WHERE part_id = ? AND token = ?", (part_id, token))
conn.execute("UPDATE parts SET updated_at = datetime('now') WHERE id = ?", (part_id,))
db.delete_image_files([row])
return {"deleted": token}
# --- categories & locations -------------------------------------------------
def _node_payload(conn, table: str) -> list[dict]: