M6 1900: any-file attachments + audio memos (broaden beyond images)
A note can now carry any file, not just images — PDFs, documents, audio memos, etc. "Dump anything" capture. Backend: - note_attachments.filename (migration 0019) records the original name for download + display. - Upload drops the image-only mime gate: accepts any type, derives the storage extension from the filename, and enforces a DB-backed per-file cap — new setting max_attachment_mb (default 25, rule 25). App body ceiling raised 12→64 MB (also lifts the import-zip / sync-push limits); the per-file cap is the effective attachment limit. - Serve sets Content-Disposition: images inline, everything else downloads with its original (header-sanitized) filename. - Import (native + Keep Takeout) now brings in ANY attachment, not just images — completing the Keep audio-memo gap; preserves filename + sha256. - Attachment metadata (delta feed + REST) carries filename. Frontend: - Editor renders attachments by kind: images inline (thumbnail), audio via an inline <audio> player, any other file as a download chip (paperclip + filename + size). File picker accepts any type; "Attach a file". - Card previews the first image; non-image files show as compact chips. Tests (DB-free): _safe_filename, _attachment_ext, _header_filename. 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:
@@ -35,7 +35,10 @@ 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
|
||||
# Hard request-body ceiling (any-file attachments, import zips, sync push). The
|
||||
# per-file attachment limit is the DB-backed `max_attachment_mb` setting, enforced
|
||||
# in the upload handler; this must stay >= the largest value that allows.
|
||||
app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024
|
||||
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(notes_bp)
|
||||
|
||||
@@ -11,8 +11,8 @@ 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."""
|
||||
"""A file uploaded onto a note (any type — images render inline, others download).
|
||||
Bytes live under Config.media_root(); this row records the relative path + metadata."""
|
||||
|
||||
__tablename__ = "note_attachments"
|
||||
|
||||
@@ -21,6 +21,8 @@ class NoteAttachment(Base):
|
||||
UUID(as_uuid=True), ForeignKey("notes.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
path: Mapped[str] = mapped_column(Text(), nullable=False) # relative to media_root
|
||||
# Original upload filename, for the download name + display (non-image files).
|
||||
filename: Mapped[str | None] = mapped_column(Text(), nullable=True)
|
||||
mime: Mapped[str] = mapped_column(Text(), nullable=False)
|
||||
size: Mapped[int] = mapped_column(BigInteger(), nullable=False)
|
||||
# Content hash (sha256 hex) for client-side dedupe + integrity over sync. Nullable
|
||||
|
||||
+52
-13
@@ -17,6 +17,7 @@ from .acl import visible_to_user
|
||||
from .auth import login_required
|
||||
from .config import Config
|
||||
from .db import session_scope
|
||||
from .settings import get_setting
|
||||
from .models.label import Label, NoteLabel
|
||||
from .models.note import NOTE_COLORS, Note
|
||||
from .models.note_attachment import NoteAttachment
|
||||
@@ -163,6 +164,7 @@ async def _attachments_for_notes(db, note_ids: list) -> dict:
|
||||
{
|
||||
"id": str(att.id),
|
||||
"url": _attachment_url(att.note_id, att.id),
|
||||
"filename": att.filename,
|
||||
"mime": att.mime,
|
||||
"size": att.size,
|
||||
"sha256": att.sha256,
|
||||
@@ -637,24 +639,34 @@ def _read_import_specs(zf: zipfile.ZipFile) -> tuple[list[dict], str]:
|
||||
|
||||
|
||||
def _import_attachment(db, note: Note, zf: zipfile.ZipFile, att: dict) -> bool:
|
||||
"""Copy one image attachment out of the zip into media storage and record it.
|
||||
Non-image types (e.g. Keep audio memos) are skipped until any-file attachments
|
||||
land. Returns True if written."""
|
||||
mime = (att.get("mime") or "").split(";")[0].strip().lower()
|
||||
ext = ALLOWED_IMAGE_MIMES.get(mime)
|
||||
"""Copy one attachment (any type — incl. Keep audio memos) out of the zip into
|
||||
media storage and record it, preserving its filename + hash. Returns True if written."""
|
||||
zpath = att.get("file")
|
||||
if ext is None or not zpath:
|
||||
if not zpath:
|
||||
return False
|
||||
try:
|
||||
raw = zf.read(zpath)
|
||||
except KeyError:
|
||||
return False
|
||||
filename = _safe_filename(posixpath.basename(zpath))
|
||||
mime = (att.get("mime") or "application/octet-stream").split(";")[0].strip().lower()
|
||||
ext = _attachment_ext(filename, mime)
|
||||
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)
|
||||
dest.write_bytes(raw)
|
||||
db.add(NoteAttachment(id=att_id, note_id=note.id, path=rel, mime=mime, size=len(raw)))
|
||||
db.add(
|
||||
NoteAttachment(
|
||||
id=att_id,
|
||||
note_id=note.id,
|
||||
path=rel,
|
||||
filename=filename,
|
||||
mime=mime,
|
||||
size=len(raw),
|
||||
sha256=hashlib.sha256(raw).hexdigest(),
|
||||
)
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@@ -1179,6 +1191,25 @@ async def reorder_items(note_id: str):
|
||||
return jsonify(await _serialize_note(db, note))
|
||||
|
||||
|
||||
def _safe_filename(name: str | None) -> str:
|
||||
"""The upload's original name reduced to a safe basename (display + download)."""
|
||||
base = os.path.basename((name or "").strip().replace("\\", "/"))
|
||||
return base[:255] or "file"
|
||||
|
||||
|
||||
def _attachment_ext(filename: str, mime: str) -> str:
|
||||
"""Storage extension: the original file's extension, else a known image ext."""
|
||||
ext = os.path.splitext(filename)[1].lower()
|
||||
if ext and len(ext) <= 12:
|
||||
return ext
|
||||
return ALLOWED_IMAGE_MIMES.get(mime, "")
|
||||
|
||||
|
||||
def _header_filename(name: str) -> str:
|
||||
"""Sanitize a filename for a Content-Disposition header (drop quotes/newlines)."""
|
||||
return re.sub(r'[\r\n"]', "", name or "")[:255] or "file"
|
||||
|
||||
|
||||
@bp.post("/<note_id>/attachments")
|
||||
@login_required
|
||||
async def upload_attachment(note_id: str):
|
||||
@@ -1190,10 +1221,10 @@ async def upload_attachment(note_id: str):
|
||||
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
|
||||
# Any file type is allowed — images render inline, everything else downloads.
|
||||
mime = (upload.content_type or "application/octet-stream").split(";")[0].strip().lower()
|
||||
filename = _safe_filename(upload.filename)
|
||||
ext = _attachment_ext(filename, mime)
|
||||
# A native client may supply the attachment's id so an offline-attached file
|
||||
# keeps its identity across sync. Re-uploading an id it already has is a no-op.
|
||||
form = await request.form
|
||||
@@ -1209,16 +1240,20 @@ async def upload_attachment(note_id: str):
|
||||
)
|
||||
if existing is not None:
|
||||
return jsonify(await _serialize_note(db, note)) # already have this blob
|
||||
raw = upload.stream.read()
|
||||
max_mb = int(await get_setting(db, "max_attachment_mb"))
|
||||
if len(raw) > max_mb * 1024 * 1024:
|
||||
return jsonify({"error": f"file is too large (max {max_mb} MB)"}), 413
|
||||
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))
|
||||
raw = dest.read_bytes()
|
||||
dest.write_bytes(raw)
|
||||
db.add(
|
||||
NoteAttachment(
|
||||
id=att_id,
|
||||
note_id=note.id,
|
||||
path=rel,
|
||||
filename=filename,
|
||||
mime=mime,
|
||||
size=len(raw),
|
||||
sha256=hashlib.sha256(raw).hexdigest(),
|
||||
@@ -1247,12 +1282,16 @@ async def get_attachment(note_id: str, att_id: str):
|
||||
if att is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
mime = att.mime
|
||||
filename = att.filename or os.path.basename(att.path)
|
||||
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"
|
||||
# Images display inline; every other type downloads with its original name.
|
||||
disposition = "inline" if mime.startswith("image/") else "attachment"
|
||||
response.headers["Content-Disposition"] = f'{disposition}; filename="{_header_filename(filename)}"'
|
||||
return response
|
||||
|
||||
|
||||
|
||||
@@ -43,6 +43,14 @@ REGISTRY: list[SettingDef] = [
|
||||
"How long a signed-in session stays valid before another login is required.",
|
||||
"Access",
|
||||
),
|
||||
SettingDef(
|
||||
"max_attachment_mb",
|
||||
"int",
|
||||
25,
|
||||
"Max attachment size (MB)",
|
||||
"Largest single file that can be attached to a note. Capped by the server body limit.",
|
||||
"Attachments",
|
||||
),
|
||||
]
|
||||
|
||||
_BY_KEY: dict[str, SettingDef] = {d.key: d for d in REGISTRY}
|
||||
|
||||
Reference in New Issue
Block a user