From 510a6a49ce51ece4a98140a480f097631cbfd83b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 22:25:54 +0000 Subject: [PATCH] Import a picture by its address POST /api/assets/import-image downloads one picture and catalogues it through the upload's own ingest, for Video Creator's image search. Inline rather than queued: the caller is waiting to place it, and it is one bounded download. The SSRF check runs on every hop; the server's type names the file, a page answering for a picture is refused, SVG is never taken from the web. A repeat is caught by address, then by checksum, and returns the existing asset. The page is recorded as the source, with retrieved_at and the search's description, stamped embedded; licence and creator stay empty because no search knows them. download_image sits beside download_audio in ingest/web.py, which now share one streaming download. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01V1geD3rf5gNTeFwCtstRx7 --- README.md | 4 +- backend/app/enrichment/page_import.py | 6 +- backend/app/ingest/web.py | 98 +++++++++++++--- backend/app/routers/imports.py | 62 +++++++++- backend/app/services/image_import.py | 148 ++++++++++++++++++++++++ backend/tests/test_image_import.py | 157 ++++++++++++++++++++++++++ docs/image-import.md | 37 ++++++ 7 files changed, 489 insertions(+), 23 deletions(-) create mode 100644 backend/app/services/image_import.py create mode 100644 backend/tests/test_image_import.py create mode 100644 docs/image-import.md diff --git a/README.md b/README.md index ac27e63..93e41f9 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,9 @@ user row. The changes that makes possible are specified in - **Import from a link** — paste a YouTube (or Rumble, Odysee, Vimeo…) URL and it arrives titled, attributed, tagged and split into its chapters, with the site's captions as a transcript when there is no Deepgram key. Playlists too. See - [`docs/url-import.md`](docs/url-import.md). + [`docs/url-import.md`](docs/url-import.md). A single picture can be imported by its + address too, which is how Video Creator files the pictures its image search finds + ([`docs/image-import.md`](docs/image-import.md)). - **Find the moment** — full-text search over names, descriptions, summaries, tags and transcripts, fused with semantic search so half-remembered wording still lands. Hits in audio and video come back with a timestamp you can jump straight to. diff --git a/backend/app/enrichment/page_import.py b/backend/app/enrichment/page_import.py index f89305f..6244776 100644 --- a/backend/app/enrichment/page_import.py +++ b/backend/app/enrichment/page_import.py @@ -161,7 +161,7 @@ def similar_in_library(session: Session, user_id: str, tracks: list[PageTrack]) return found -def _same_file(session: Session, user_id: str, path: Path) -> Optional[Asset]: +def same_file(session: Session, user_id: str, path: Path) -> Optional[Asset]: """An asset in this library with exactly these bytes, if there is one. The checksum every stored file already carries is what catches a duplicate the URL @@ -334,7 +334,7 @@ def report(received: int, total: Optional[int]) -> None: raise PageImportError(str(exc)) from exc progress("Checking for a copy already here", 86, "") - duplicate = _same_file(session, job.user_id, path) + duplicate = same_file(session, job.user_id, path) if duplicate is not None: # The download is thrown away with the temp directory. What the page said # still fills the copy's blanks, so a track uploaded bare gains its credits @@ -490,7 +490,7 @@ def import_saved( continue track = matches.get(name) - duplicate = _same_file(session, user_id, path) + duplicate = same_file(session, user_id, path) if duplicate is not None: if track is not None: apply_track_metadata(session, duplicate, track, fill_blanks_only=True) diff --git a/backend/app/ingest/web.py b/backend/app/ingest/web.py index c05b4e7..752ffe7 100644 --- a/backend/app/ingest/web.py +++ b/backend/app/ingest/web.py @@ -1,6 +1,7 @@ -"""Fetching a web page, or one audio file named on it, on the user's behalf. +"""Fetching a web page, or one audio file or picture named on it, on the user's behalf. -For importing tracks from a page (`ingest/page_tracks.py`). The same rules as +For importing tracks from a page (`ingest/page_tracks.py`) and pictures found by an +image search (`services/image_import.py`). The same rules as `generation/download.py`, which is fal-specific (its errors, its retry policy, image and video only), restated here for a page and a track rather than shared through a flag: @@ -41,6 +42,8 @@ # A long, high-bitrate track. Anything bigger is not a soundtrack. MAX_TRACK_BYTES = 200 * 1024 * 1024 MAX_TRACK_SECONDS = 15 * 60 +# A large photograph. A picture for a video frame needs no more than a few megapixels. +MAX_IMAGE_BYTES = 40 * 1024 * 1024 # Says what is asking, so a site that wants to can tell this apart from a browser and # from a crawler. It is one person's library fetching the tracks they picked. @@ -67,6 +70,24 @@ } +_IMAGE_TYPES = { + "image/jpeg": ".jpg", + "image/jpg": ".jpg", + "image/pjpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/webp": ".webp", + "image/avif": ".avif", + "image/bmp": ".bmp", + "image/tiff": ".tiff", +} +# What a picture from the web may be stored as. Narrower than an upload's list: no SVG, +# which is a document that can carry script and is served back from this origin, and +# none of the camera formats (HEIC) or icons a person might upload but a site sends a +# browser as something else anyway. +WEB_IMAGE_EXTENSIONS = frozenset(_IMAGE_TYPES.values()) | {".jpeg", ".tif"} + + class WebFetchError(Exception): """A page or a track could not be fetched. The message is worded for the user.""" @@ -161,30 +182,57 @@ def download_audio( with an HTML page (a login wall, a "download starting" interstitial) must not land in the library as a broken track. """ + return _download(url, workdir, stem, what="track", extension=_audio_extension, + refused="That link is not an audio file", max_bytes=max_bytes, + on_progress=on_progress) + + +def download_image(url: str, workdir: Path, stem: str, *, max_bytes: int = MAX_IMAGE_BYTES) -> Path: + """Fetch one picture into `workdir/` and return the path. + + The same refusal as a track's: a URL that answers with a page is not a picture. An + image search's "image URL" is often a page that shows one, or a hotlink guard's + placeholder, and that must not become an asset. + """ + return _download(url, workdir, stem, what="picture", extension=_image_extension, + refused="That link is not a picture GAM can store", max_bytes=max_bytes) + + +def _download( + url: str, + workdir: Path, + stem: str, + *, + what: str, + extension: Callable[[str, Optional[str]], Optional[str]], + refused: str, + max_bytes: int, + on_progress: Optional[Progress] = None, +) -> Path: report = on_progress or (lambda _received, _total: None) try: with _client("identity") as client, _get(client, url) as (final, response): if response.status_code >= 400: - raise _status_error("track", response) + raise _status_error(what, response) encoding = response.headers.get("content-encoding", "").strip().lower() if encoding not in ("", "identity"): - raise WebFetchError("The site sent the track compressed, which is refused") + raise WebFetchError(f"The site sent the {what} compressed, which is refused") - extension = _audio_extension(final, response.headers.get("content-type")) - if extension is None: - raise WebFetchError("That link is not an audio file") + suffix = extension(final, response.headers.get("content-type")) + if suffix is None: + raise WebFetchError(refused) total = _content_length(response) if total is not None and total > max_bytes: - raise _too_large(max_bytes) + raise _too_large(what, max_bytes) - destination = workdir / f"{stem}{extension}" - _stream_to(response, destination, max_bytes=max_bytes, total=total, report=report) + destination = workdir / f"{stem}{suffix}" + _stream_to(response, destination, what=what, max_bytes=max_bytes, total=total, report=report) return destination except httpx.TimeoutException as exc: - raise WebFetchError("The track did not download in time") from exc + raise WebFetchError(f"The {what} did not download in time") from exc except httpx.RequestError as exc: - raise WebFetchError(f"Could not download the track ({type(exc).__name__})") from exc + raise WebFetchError(f"Could not download the {what} ({type(exc).__name__})") from exc def _audio_extension(url: str, content_type: Optional[str]) -> Optional[str]: @@ -195,8 +243,24 @@ def _audio_extension(url: str, content_type: Optional[str]) -> Optional[str]: return _AUDIO_TYPES.get(media_type) +def _image_extension(url: str, content_type: Optional[str]) -> Optional[str]: + # The server's type first, unlike a track: picture URLs are full of `.php?id=` and of + # CDNs that send WebP from a `.jpg` path to browsers that accept it, and the file must + # be stored under what it is. The path is the fallback for servers that send + # `application/octet-stream`. + media_type = (content_type or "").split(";", 1)[0].strip().lower() + if media_type in _IMAGE_TYPES: + return _IMAGE_TYPES[media_type] + if media_type.startswith("image/") or media_type in ("", "application/octet-stream", "binary/octet-stream"): + from_path = extension_of(urlsplit(url).path) + if from_path in WEB_IMAGE_EXTENSIONS: + return from_path + return None + + def _stream_to( - response: httpx.Response, destination: Path, *, max_bytes: int, total: Optional[int], report: Progress + response: httpx.Response, destination: Path, *, what: str, max_bytes: int, total: Optional[int], + report: Progress, ) -> None: received = 0 started = monotonic() @@ -205,9 +269,9 @@ def _stream_to( for chunk in response.iter_bytes(): received += len(chunk) if received > max_bytes: - raise _too_large(max_bytes) + raise _too_large(what, max_bytes) if monotonic() - started > MAX_TRACK_SECONDS: - raise WebFetchError("The track did not download in time") + raise WebFetchError(f"The {what} did not download in time") handle.write(chunk) report(received, total) except BaseException: @@ -216,5 +280,5 @@ def _stream_to( raise -def _too_large(max_bytes: int) -> WebFetchError: - return WebFetchError(f"The track is larger than the {max_bytes // (1024 * 1024)} MB limit") +def _too_large(what: str, max_bytes: int) -> WebFetchError: + return WebFetchError(f"The {what} is larger than the {max_bytes // (1024 * 1024)} MB limit") diff --git a/backend/app/routers/imports.py b/backend/app/routers/imports.py index 8a9e4fb..532fe6d 100644 --- a/backend/app/routers/imports.py +++ b/backend/app/routers/imports.py @@ -10,7 +10,7 @@ from typing import List, Optional -from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status +from fastapi import APIRouter, Depends, File, HTTPException, Response, UploadFile, status from pydantic import BaseModel, Field from sqlmodel import Session @@ -26,8 +26,12 @@ from app.models.job import KIND_IMPORT_TRACK, KIND_IMPORT_URL from app.schemas import DataResponse from app.safe_url import require_safe_external_url +from app.schemas_assets import AssetRead from app.schemas_jobs import ActivityJobRead -from app.storage import capacity +from app.services import assets as asset_service +from app.services import image_import +from app.services import tags as tag_service +from app.storage import build_storage, capacity router = APIRouter() @@ -78,6 +82,60 @@ def start_url_import( return DataResponse(data=KINDS["enrichment"].to_activity(job)) +# ─── one picture, by its address ───────────────────────────────────────────── + + +class ImageImportCreate(BaseModel): + """A picture an image search found, as the person chose it.""" + + image_url: str = Field(min_length=1, max_length=MAX_URL) + page_url: Optional[str] = Field(default=None, max_length=MAX_URL) + title: Optional[str] = Field(default=None, max_length=500) + description: Optional[str] = Field(default=None, max_length=20_000) + tags: List[str] = Field(default_factory=list, max_length=20) + + +@router.post("/import-image", response_model=DataResponse[AssetRead], status_code=status.HTTP_201_CREATED) +def import_image( + payload: ImageImportCreate, + response: Response, + user: CurrentUser, + session: Session = Depends(get_session), +) -> DataResponse[AssetRead]: + """Download one picture and catalogue it. 201 with the new asset, or 200 with the + one already here (the same address, or the same bytes). + + Inline rather than queued: see `services/image_import.py`. The address is checked + against private address space on every redirect hop, by `ingest/web.py`. + """ + capacity.require_room() + request = image_import.ImageImport( + image_url=payload.image_url.strip(), + page_url=(payload.page_url or "").strip() or None, + title=payload.title, + description=payload.description, + tags=[t for t in payload.tags if t.strip()], + ) + try: + result = image_import.import_image(session, user.id, request) + except image_import.ImageImportError as exc: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={"code": "image_unavailable", "message": str(exc)}, + ) + except web.WebFetchError as exc: # the address check, before anything is fetched + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail={"code": "unsafe_url", "message": str(exc)}, + ) + if result.existing: + response.status_code = status.HTTP_200_OK + asset = result.asset + return DataResponse( + data=asset_service.to_read_model(asset, build_storage(), tag_service.tags_for(session, asset.id)) + ) + + # ─── tracks from a music library's page ────────────────────────────────────── diff --git a/backend/app/services/image_import.py b/backend/app/services/image_import.py new file mode 100644 index 0000000..d7b373f --- /dev/null +++ b/backend/app/services/image_import.py @@ -0,0 +1,148 @@ +"""Importing one picture from the web, by its URL: what Video Creator files a picture +found by its image search through. + +Synchronous, unlike every other import, because the caller is waiting to place the +picture on a scene and a picture is one bounded request: at most `web.MAX_IMAGE_BYTES`, +no transcoding, a thumbnail. A video or a track is minutes of download and goes on the +queue; this would spend longer queued than fetching. + +What the search said about the picture is all there is to say. No backend knows who +made it or under what licence, so neither is written: an empty licence is the honest +"unknown" the attribution filters (`unattributed=true`) already find, and filling it +with a guess is the confidently wrong citation M10 exists to prevent. +""" + +from __future__ import annotations + +import logging +import re +import tempfile +from dataclasses import dataclass, field +from pathlib import Path +from typing import Optional + +from sqlmodel import Session, select + +from app.clock import utcnow +from app.enrichment.page_import import same_file +from app.ingest import web +from app.ingest.filetypes import SOURCE_URL +from app.models.asset import Asset +from app.services import assets as asset_service +from app.services import tags as tag_service +from app.storage import build_storage, capacity + +logger = logging.getLogger(__name__) + +MAX_NAME = 255 +MAX_DESCRIPTION = 20_000 + + +class ImageImportError(Exception): + """The picture could not be imported. Worded for the person.""" + + +@dataclass +class ImageImport: + image_url: str + # The page the picture is on, when the search said. It is what the credit names. + page_url: Optional[str] = None + title: Optional[str] = None + description: Optional[str] = None + tags: list[str] = field(default_factory=list) + + +@dataclass +class ImportedImage: + asset: Asset + # True when the library already held it (same address, or the same bytes). + existing: bool + + +def _by_address(session: Session, user_id: str, request: ImageImport) -> Optional[Asset]: + # Only the picture's own address identifies it: a page holds many pictures, so a + # page URL match would hand back a different one. `source_url` holds the picture's + # address only when no page was known, so this catches those; a picture recorded + # under its page is caught after the download instead, by its checksum. + return session.exec( + select(Asset).where( + Asset.user_id == user_id, + Asset.source_url == request.image_url, + Asset.asset_type == "image", + ) + ).first() + + +def _name(request: ImageImport, path: Path) -> str: + for candidate in (request.title, request.description): + text = " ".join((candidate or "").split()) + if text: + return text[:MAX_NAME] + return path.name + + +def import_image(session: Session, user_id: str, request: ImageImport) -> ImportedImage: + web.require_safe(request.image_url) + if request.page_url: + # Never fetched, but stored and shown as a link, so it has to be a web address. + if not request.page_url.startswith(("http://", "https://")): + raise ImageImportError("The page address is not a web address") + + found = _by_address(session, user_id, request) + if found is not None: + return ImportedImage(found, existing=True) + if not capacity.has_room(): + raise ImageImportError(capacity.DISK_FULL_MESSAGE) + + with tempfile.TemporaryDirectory(prefix="gam-image-") as workdir: + try: + path = web.download_image(request.image_url, Path(workdir), "picture") + except web.WebFetchError as exc: + raise ImageImportError(str(exc)) from exc + + duplicate = same_file(session, user_id, path) + if duplicate is not None: + # The same bytes from another address (a CDN size variant, a mirror), or a + # picture uploaded by hand. Its details are a person's, so they stay. + return ImportedImage(duplicate, existing=True) + + name = _name(request, path) + stem = re.sub(r"[\\/]+", "-", name).strip()[:200] or "picture" + try: + asset = asset_service.ingest_file( + session, + build_storage(), + user_id=user_id, + source_path=path, + filename=f"{stem}{path.suffix.lower()}", + name=name, + source=SOURCE_URL, + ) + except asset_service.UnsupportedFile as exc: + raise ImageImportError("The site sent a file the library does not accept") from exc + + _record_source(session, asset, request) + return ImportedImage(asset, existing=False) + + +def _record_source(session: Session, asset: Asset, request: ImageImport) -> None: + """Where it came from, stamped `embedded`: what the source said, unchecked.""" + changes: dict = {"source_url": request.page_url or request.image_url, "retrieved_at": utcnow()} + description = " ".join((request.description or "").split()) + if description: + changes["description"] = description[:MAX_DESCRIPTION] + try: + asset_service.apply_embedded_metadata(session, asset, changes) + except Exception: # noqa: BLE001 - the picture is in; losing its source must not undo that + logger.warning("Could not record where %s came from", asset.id, exc_info=True) + + try: + attached = 0 + for name in request.tags: + tag = tag_service.get_or_create(session, asset.user_id, name) + if tag is not None and tag_service.attach(session, asset.id, tag.id): + attached += 1 + if attached: + asset_service.reindex_ids(session, [asset.id]) + except Exception: # noqa: BLE001 - same + logger.warning("Could not tag %s", asset.id, exc_info=True) diff --git a/backend/tests/test_image_import.py b/backend/tests/test_image_import.py new file mode 100644 index 0000000..bbc6724 --- /dev/null +++ b/backend/tests/test_image_import.py @@ -0,0 +1,157 @@ +"""`POST /api/assets/import-image`: one picture an image search found, filed in the library. + +The network is replaced at `ingest/web.py`'s client, so the real download code runs +(type sniffing, the cap, the redirect check) and the bytes go through the upload's own +ingest. DNS is faked to a public address, so the SSRF check runs without touching it. +""" + +import socket +from pathlib import Path + +import httpx +import pytest +from sqlmodel import select + +from app.ingest import web +from app.models.asset import PROVENANCE_EMBEDDED, Asset + +FIXTURES = Path(__file__).parent / "fixtures" +JPEG = (FIXTURES / "sample_image.jpg").read_bytes() +PNG = (FIXTURES / "sample_image.png").read_bytes() + + +def _resolving_to(address): + def fake_getaddrinfo(host, port, *args, **kwargs): + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, 0))] + + return fake_getaddrinfo + + +@pytest.fixture(autouse=True) +def public_dns(monkeypatch): + monkeypatch.setattr(socket, "getaddrinfo", _resolving_to("93.184.216.34")) + + +@pytest.fixture +def serve(monkeypatch): + """Answer `web`'s requests from `serve.routes` (url -> Response). `serve` is also the + list of URLs asked for.""" + + class Asked(list): + routes: dict[str, httpx.Response] + + asked = Asked() + asked.routes = {} + routes = asked.routes + + def handler(request): + asked.append(str(request.url)) + return routes.get(str(request.url), httpx.Response(404)) + + def client(accept_encoding): + return httpx.Client(transport=httpx.MockTransport(handler), follow_redirects=False, + headers={"Accept-Encoding": accept_encoding}) + + monkeypatch.setattr(web, "_client", client) + return asked + + +def _jpeg(): + return httpx.Response(200, headers={"content-type": "image/jpeg"}, content=JPEG) + + +def test_a_picture_is_downloaded_catalogued_and_credited_to_its_page(library, session, serve): + serve.routes["https://cdn.example.org/owl.jpg"] = _jpeg() + response = library.post("/api/assets/import-image", json={ + "image_url": "https://cdn.example.org/owl.jpg", + "page_url": "https://birds.example.org/owls", + "title": "Barn owl at dusk", + "description": "A barn owl in flight over a field", + "tags": ["owls", "web"], + }) + assert response.status_code == 201, response.text + data = response.json()["data"] + assert (data["name"], data["asset_type"]) == ("Barn owl at dusk", "image") + assert data["thumb_url"] and data["file_url"] + + asset = session.get(Asset, data["id"]) + assert asset.source_url == "https://birds.example.org/owls" + assert asset.retrieved_at is not None + assert asset.description == "A barn owl in flight over a field" + # What the search said, unchecked; and nothing is claimed about the rights. + assert PROVENANCE_EMBEDDED in (asset.field_provenance or "") + assert asset.license is None and asset.creator is None + assert sorted(t["name"] for t in data["tags"]) == ["owls", "web"] + + +def test_the_same_picture_twice_is_one_asset(library, session, serve): + serve.routes["https://cdn.example.org/owl.jpg"] = _jpeg() + serve.routes["https://cdn.example.org/owl-large.jpg"] = _jpeg() + first = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/owl.jpg"}) + assert first.status_code == 201 + again = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/owl.jpg"}) + # Known by its address, so not even downloaded again. + assert again.status_code == 200 and again.json()["data"]["id"] == first.json()["data"]["id"] + assert serve.count("https://cdn.example.org/owl.jpg") == 1 + # Another address with the same bytes is known by its checksum. + mirror = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/owl-large.jpg", + "page_url": "https://elsewhere.example/p"}) + assert mirror.status_code == 200 and mirror.json()["data"]["id"] == first.json()["data"]["id"] + assert len(session.exec(select(Asset)).all()) == 1 + + +def test_the_servers_type_names_the_file_not_the_path(library, session, serve): + # A CDN sending PNG (or WebP) from a `.jpg` path: stored as what it is. + serve.routes["https://cdn.example.org/x.jpg"] = httpx.Response( + 200, headers={"content-type": "image/png"}, content=PNG) + data = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/x.jpg"}).json()["data"] + assert session.get(Asset, data["id"]).storage_key.endswith(".png") + + +def test_a_page_instead_of_a_picture_is_refused(library, session, serve): + serve.routes["https://site.example.org/photo?id=4"] = httpx.Response( + 200, headers={"content-type": "text/html"}, content=b"hotlink denied") + response = library.post("/api/assets/import-image", json={"image_url": "https://site.example.org/photo?id=4"}) + assert response.status_code == 400 + assert response.json()["detail"] == {"code": "image_unavailable", + "message": "That link is not a picture GAM can store"} + assert session.exec(select(Asset)).all() == [] + + +def test_svg_is_not_taken_from_the_web(library, serve): + serve.routes["https://cdn.example.org/logo.svg"] = httpx.Response( + 200, headers={"content-type": "image/svg+xml"}, content=b"") + assert library.post("/api/assets/import-image", + json={"image_url": "https://cdn.example.org/logo.svg"}).status_code == 400 + + +def test_an_inward_address_is_refused_before_any_fetch(library, serve, monkeypatch): + monkeypatch.setattr(socket, "getaddrinfo", _resolving_to("10.0.0.5")) + response = library.post("/api/assets/import-image", json={"image_url": "https://intranet.example/x.jpg"}) + assert response.status_code == 400 and response.json()["detail"]["code"] == "unsafe_url" + assert serve == [] + + +def test_a_redirect_inward_is_refused(library, serve): + serve.routes["https://cdn.example.org/r.jpg"] = httpx.Response(302, headers={"location": "https://127.0.0.1/x.jpg"}) + response = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/r.jpg"}) + assert response.status_code == 400 + assert "not one this app will fetch" in response.json()["detail"]["message"] + + +def test_a_picture_over_the_cap_is_refused(serve, tmp_path): + serve.routes["https://cdn.example.org/huge.jpg"] = _jpeg() + with pytest.raises(web.WebFetchError, match="picture is larger than"): + web.download_image("https://cdn.example.org/huge.jpg", tmp_path, "p", max_bytes=10) + assert list(tmp_path.iterdir()) == [] + + +def test_a_page_address_must_be_a_web_address(library, serve): + serve.routes["https://cdn.example.org/owl.jpg"] = _jpeg() + response = library.post("/api/assets/import-image", json={"image_url": "https://cdn.example.org/owl.jpg", + "page_url": "javascript:alert(1)"}) + assert response.status_code == 400 + + +def test_signed_out_is_refused(client): + assert client.post("/api/assets/import-image", json={"image_url": "https://x.example/a.jpg"}).status_code == 401 diff --git a/docs/image-import.md b/docs/image-import.md new file mode 100644 index 0000000..10c6c4f --- /dev/null +++ b/docs/image-import.md @@ -0,0 +1,37 @@ +# Import a picture by its address + +**Status:** built. For Gecko Video Creator's image search: GVC finds pictures through +Gecko Suite (`POST /api/v1/search/images`, the suite's configured web search backend), +the person picks one for a background or an overlay, and GVC files it here so the video +refers to a GAM asset like any other. + +`POST /api/assets/import-image` + +```json +{"image_url": "https://…/owl.jpg", "page_url": "https://…/owls", "title": "…", + "description": "…", "tags": ["…"]} +``` + +Answers `201` with the new asset, or `200` with the one already here. Errors are +`400 image_unavailable` (the sentence says why: not a picture, too large, refused by the +site, timed out) or `400 unsafe_url`. + +## Decisions + +| Question | Decision | Why | +|---|---|---| +| Queued or inline | **Inline** | The caller is waiting to place the picture. One bounded download (40 MB at most) and a thumbnail would spend longer queued than fetching. Every other import is a video or a track: minutes, so a job. | +| What is stored | JPEG, PNG, GIF, WebP, AVIF, BMP, TIFF | Narrower than an upload. **No SVG** (a document that can carry script, served back from this origin), no HEIC or icons. | +| File type | **The server's `Content-Type` first**, the path's extension as the fallback | Picture URLs are full of `.php?id=`, and CDNs send WebP from a `.jpg` path. A page answering for a picture (a hotlink guard, a login wall) is refused rather than stored. | +| Duplicates | Address, then checksum | The image address catches a repeat before downloading when no page was recorded; the checksum catches the rest (CDN size variants, mirrors, a picture uploaded by hand). A duplicate returns the existing asset untouched, so a person's edits stay. | +| Credit | `source_url` = the page when known, else the picture's address. `retrieved_at` = now. The search's description as `description`. All stamped `embedded` | The page is what a citation names. **Licence and creator are left empty**: no search backend knows them, and an empty licence is the "unknown" `unattributed=true` already finds. | +| Safety | The SSRF check on every redirect hop, uncompressed bodies only, capped while it arrives | `ingest/web.py`'s rules, shared with the track import (`download_image` beside `download_audio`). | + +## Files + +| File | Role | +|---|---| +| `backend/app/routers/imports.py` | The route. | +| `backend/app/services/image_import.py` | Duplicate checks, download, `ingest_file`, the source fields. | +| `backend/app/ingest/web.py` | `download_image`, and the type rules. | +| `backend/tests/test_image_import.py` | Through the route, with the network faked at `web`'s client. |