M2 attachments: image upload + owner-scoped media serving
- Migration 0007: note_attachments (path/mime/size). Upload POST /api/notes/<id>/attachments (multipart, png/jpeg/gif/webp, 12MB cap via MAX_CONTENT_LENGTH) stored under Config.media_root() (first use of DATA_DIR); owner/ACL-scoped GET serves the file (nosniff); DELETE removes row + file. Note responses include attachments[]. - Frontend: notes store uploadAttachment (FormData)/deleteAttachment; editor image button + paste-to-upload + thumbnail grid with remove; card shows the first image as a cover. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FRgehjoz7Yv8LkUfADxACm
This commit is contained in:
@@ -28,6 +28,7 @@ def create_app() -> Quart:
|
||||
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
||||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
||||
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(days=30)
|
||||
app.config["MAX_CONTENT_LENGTH"] = 12 * 1024 * 1024 # image-upload body cap
|
||||
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(notes_bp)
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
Imported for side effects only (model registration on Base.metadata).
|
||||
"""
|
||||
|
||||
from . import group, label, note, note_item, settings, share, user # noqa: F401
|
||||
from . import group, label, note, note_attachment, note_item, settings, share, user # noqa: F401
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from . import Base
|
||||
|
||||
|
||||
class NoteAttachment(Base):
|
||||
"""An image uploaded onto a note. Bytes live under Config.media_root(); this
|
||||
row records the relative path + metadata."""
|
||||
|
||||
__tablename__ = "note_attachments"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
note_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("notes.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
path: Mapped[str] = mapped_column(Text(), nullable=False) # relative to media_root
|
||||
mime: Mapped[str] = mapped_column(Text(), nullable=False)
|
||||
size: Mapped[int] = mapped_column(BigInteger(), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())
|
||||
+108
-1
@@ -1,18 +1,23 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from quart import Blueprint, g, jsonify, request
|
||||
from quart import Blueprint, g, jsonify, request, send_file
|
||||
from sqlalchemy import delete, func, literal_column, select
|
||||
|
||||
from .acl import visible_to_user
|
||||
from .auth import login_required
|
||||
from .config import Config
|
||||
from .db import session_scope
|
||||
from .models.label import Label, NoteLabel
|
||||
from .models.note import NOTE_COLORS, Note
|
||||
from .models.note_attachment import NoteAttachment
|
||||
from .models.note_item import NoteItem
|
||||
|
||||
ALLOWED_IMAGE_MIMES = {"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}
|
||||
|
||||
bp = Blueprint("notes", __name__, url_prefix="/api/notes")
|
||||
|
||||
VALID_FILTERS = {"active", "archived", "trash"}
|
||||
@@ -70,12 +75,34 @@ async def _items_for_notes(db, note_ids: list) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
def _attachment_url(note_id, att_id) -> str:
|
||||
return f"/api/notes/{note_id}/attachments/{att_id}"
|
||||
|
||||
|
||||
async def _attachments_for_notes(db, note_ids: list) -> dict:
|
||||
result: dict = {}
|
||||
if not note_ids:
|
||||
return result
|
||||
rows = (
|
||||
await db.scalars(
|
||||
select(NoteAttachment).where(NoteAttachment.note_id.in_(note_ids)).order_by(NoteAttachment.created_at)
|
||||
)
|
||||
).all()
|
||||
for att in rows:
|
||||
result.setdefault(att.note_id, []).append(
|
||||
{"id": str(att.id), "url": _attachment_url(att.note_id, att.id), "mime": att.mime}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
async def _serialize_note(db, note: Note) -> dict:
|
||||
data = note.serialize()
|
||||
labels = await _labels_for_notes(db, [note.id])
|
||||
data["labels"] = labels.get(note.id, [])
|
||||
items = await _items_for_notes(db, [note.id])
|
||||
data["items"] = items.get(note.id, [])
|
||||
attachments = await _attachments_for_notes(db, [note.id])
|
||||
data["attachments"] = attachments.get(note.id, [])
|
||||
return data
|
||||
|
||||
|
||||
@@ -83,11 +110,13 @@ async def _serialize_notes(db, notes: list) -> list:
|
||||
ids = [n.id for n in notes]
|
||||
labels_map = await _labels_for_notes(db, ids)
|
||||
items_map = await _items_for_notes(db, ids)
|
||||
attach_map = await _attachments_for_notes(db, ids)
|
||||
out = []
|
||||
for n in notes:
|
||||
data = n.serialize()
|
||||
data["labels"] = labels_map.get(n.id, [])
|
||||
data["items"] = items_map.get(n.id, [])
|
||||
data["attachments"] = attach_map.get(n.id, [])
|
||||
out.append(data)
|
||||
return out
|
||||
|
||||
@@ -327,6 +356,84 @@ async def reorder_items(note_id: str):
|
||||
return jsonify(await _serialize_note(db, note))
|
||||
|
||||
|
||||
@bp.post("/<note_id>/attachments")
|
||||
@login_required
|
||||
async def upload_attachment(note_id: str):
|
||||
async with session_scope() as db:
|
||||
note = await _get_owned(db, note_id)
|
||||
if note is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
files = await request.files
|
||||
upload = files.get("file")
|
||||
if upload is None:
|
||||
return jsonify({"error": "no file provided"}), 400
|
||||
mime = (upload.content_type or "").split(";")[0].strip().lower()
|
||||
ext = ALLOWED_IMAGE_MIMES.get(mime)
|
||||
if ext is None:
|
||||
return jsonify({"error": "unsupported image type (png, jpeg, gif, webp only)"}), 415
|
||||
att_id = uuid.uuid4()
|
||||
rel = os.path.join(str(note.id), f"{att_id}{ext}")
|
||||
dest = Config.media_root() / rel
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
await upload.save(str(dest))
|
||||
db.add(NoteAttachment(id=att_id, note_id=note.id, path=rel, mime=mime, size=dest.stat().st_size))
|
||||
await db.commit()
|
||||
return jsonify(await _serialize_note(db, note)), 201
|
||||
|
||||
|
||||
@bp.get("/<note_id>/attachments/<att_id>")
|
||||
@login_required
|
||||
async def get_attachment(note_id: str, att_id: str):
|
||||
try:
|
||||
nid = uuid.UUID(note_id)
|
||||
aid = uuid.UUID(att_id)
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"error": "not found"}), 404
|
||||
async with session_scope() as db:
|
||||
# Owner OR shared may view (rule 47).
|
||||
note = await db.scalar(
|
||||
select(Note).where(Note.id == nid, visible_to_user("note", Note.owner_id, Note.id, g.user_id))
|
||||
)
|
||||
if note is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
att = await db.scalar(select(NoteAttachment).where(NoteAttachment.id == aid, NoteAttachment.note_id == nid))
|
||||
if att is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
mime = att.mime
|
||||
file_path = Config.media_root() / att.path
|
||||
if not file_path.is_file():
|
||||
return jsonify({"error": "not found"}), 404
|
||||
response = await send_file(str(file_path), mimetype=mime)
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
response.headers["Cache-Control"] = "private, max-age=86400"
|
||||
return response
|
||||
|
||||
|
||||
@bp.delete("/<note_id>/attachments/<att_id>")
|
||||
@login_required
|
||||
async def delete_attachment(note_id: str, att_id: str):
|
||||
try:
|
||||
aid = uuid.UUID(att_id)
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"error": "not found"}), 404
|
||||
async with session_scope() as db:
|
||||
note = await _get_owned(db, note_id)
|
||||
if note is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
att = await db.scalar(select(NoteAttachment).where(NoteAttachment.id == aid, NoteAttachment.note_id == note.id))
|
||||
if att is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
file_path = Config.media_root() / att.path
|
||||
await db.delete(att)
|
||||
await db.commit()
|
||||
result = await _serialize_note(db, note)
|
||||
try:
|
||||
file_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@bp.post("/<note_id>/trash")
|
||||
@login_required
|
||||
async def trash_note(note_id: str):
|
||||
|
||||
Reference in New Issue
Block a user