* refactor(thumbnails): one resolver for where previews live on disk (#320) Add py/api/preview_store.py: the store of a source, a preview's path, URL parts to disk, containment (owns), a write generation and the lock around every preview's final rename. Every preview reader, writer and remover now asks it instead of joining <source>/thumbnails by hand: serve, on-demand, capture (its path resolved when the write starts), the after-scan queue, the thumbnail plans and job payloads, clear, the temp sweep, History covers, the auto-tag listing and the owned-preview lookups. Source mode only: every path is the one built before, so nothing changes on disk or on the wire. A structural test keeps new thumbnails joins out of the backend. * refactor(thumbnails): keep the after-scan queue's store rule and pin the write lock (#320) A planned target keeps the plan's own containment rule (inside the store, as the thumbnail job writes it); captures keep the serve rule. The structural test also covers PREVIEW_FOLDER joins and the repo-root modules; the write-lock test asserts the lock instead of waiting on a timer; new tests cover nested roots in the after-scan queue and a legacy upper-case preview served through the resolver. * feat(thumbnails): keep previews in one folder, set from config.json (#320) thumbnails.location in config.json can now name one folder for every source's previews: <folder>/<source key>/<rel>_thumb<ext>. A source key is a readable slug plus a short hash of the source's identity, stored in the folder's marker (.promptmanager-thumbnails.json) with the install that made it. Serving, on-demand and capture writes, listings, clear, delete, duplicates, the temp sweep and History covers all follow it; a leftover in <source>/thumbnails is never served and other text under thumbnails/ is refused. A missing, unplugged or foreign folder is unavailable (a probe checks it every 5 s within 2 s; a stalled or failing store call flips it at once): originals are served, nothing is written anywhere, the folder is never re-created, and generate, convert and clear answer 409 location-unavailable. A bad config value is unavailable too, never a fall-back to the sources. No UI yet: POST /settings refuses thumbnail_location (409 location-needs-move); GET /settings reports it with its path, the thumbnail status without one. Sources inside or around the folder and a library move into it are refused. * fix(thumbnails): never follow a marker or a link out of the thumbnail folder (#320) Marker keys are data, not paths: only a single <slug>-<hex> folder name is ever joined onto the thumbnail folder; anything else is dropped and logged. Every preview write and delete passes one ownership check (below a key folder, lexically and resolved, no link, junction or reparse point on the way); make_parent refuses anything else and writes nothing while the folder lacks this install's marker (an unmounted mount point). Clear never descends into a junction. The configured location is in force before any request (unchecked folder mode is unavailable), and a startup check that fails leaves it invalid, never the sources. Older listings that run on the event loop no longer touch the store in folder mode. A leftover under another case of thumbnails/ on a case-insensitive disk is refused too. * test(memory): let the musl test fake os.confstr on Windows (#523) The portability run on main fails since #523: Windows has no os.confstr, so patching it without create=True raises before the test runs. * feat(thumbnails): move thumbnails between the sources and one folder (#320) POST /images/thumbnails/plan reviews a move (what is copied, removed and left, free space, too-long Windows paths, sources no longer listed) and hands out a token; POST /jobs/thumbnails {mode: move} runs it as a thumbnails job: hold automatic previews, copy and check every preview on the job pool, switch with one config commit that records the old copies, then remove them. Per-file errors still switch; a folder-wide error, a cancel before the switch or a crash leaves nothing changed (a journal is undone at the next start); old copies that could not go are removed by a finishing job at the next start. Leaving a folder removes the previews of this install's sources that are no longer listed (Q320-8). Recreate folder and Use this folder answer an unavailable folder; the Thumbnail maintenance scope prune removes the thumbnails of removed sources. * feat(system): choose where thumbnails are kept and move them (#320) System › Sources & scans gains the Thumbnail location row (D196): Inside each source or One folder, the folder path, the status line and Review move…, whose review (D197) lists what is copied, removed and left before Move thumbnails starts; a refused folder is explained under the field, a folder of your own asks for a confirmation first. Activity shows a move and a prune with their own tiles and step line (D198). An unavailable folder shows a notice on Overview and Sources & scans with Recreate folder or Use this folder (D199). Thumbnail maintenance offers Remove thumbnails of removed sources in folder mode (D200), and Move library's review says where the thumbnails stay (D201). Closes #320 * fix(thumbnails): keep a move's own previews and never walk out of a store (#320) A cleanup that waited from an earlier move never names a key folder the new move just filled, so moving back keeps the previews. Removing empty folders walks top-down and never into a link or junction. Any error while copying undoes the copies; once the switch is committed, a journal that cannot be removed no longer undoes it. Hand-edited cleanup entries and marker keys never name a folder outside the stores; removal stops at interpreter exit. The path field carries aria-invalid with its reason, and a review that went stale reviews again. * test(thumbnails): cover the prune scope, the Overview notice and the space refusal (#320) The frontend coverage gate counted the new branches of thumbnail maintenance, the Activity views, the notices' Change location and the api-client's space refusal as uncovered; page and unit tests now drive them. * fix(thumbnails): report removals that fail and explain the quiet excepts (#320) An old thumbnail the finishing move cannot remove (held open on Windows) is now an error row of the job with its path, and logged; a failed copy's temp that cannot go is logged with its path. Every except that only passes says why, and the thread runners say their caller re-raises. * fix(thumbnails): never plan or delete through a linked key folder (#320) Review finding P1 on #591: in folder mode a source key folder that is a link or junction to a folder outside was still handed to the planner, so Convert outdated could remove an older-format file outside the thumbnail folder. ensure_store now refuses a linked store before any planning, and each removal of an old preview passes may_write at the moment it runs. * fix(thumbnails): the temp sweep never walks into a link (#320) Review finding P2 on #591: Clear thumbnails and the startup sweep removed crashed-write temps with a plain os.walk, which on Windows walks into a junction even without followlinks. The sweeper now skips a folder that is a link, junction or reparse point (the top one too), and each temp passes may_write before it is removed. * fix(thumbnails): lock the folder marker across processes (#320) Review finding P2 on #591: two installs sharing one thumbnail folder could each read the marker, add a key and replace it, so the last writer dropped the other's key. write_marker now re-reads, changes and replaces the marker under a lock file made with O_CREAT | O_EXCL beside it (atomic on shares, unlike flock); a lock older than 30 s, left by a writer that died, is taken over, and a wait past 1.5 s fails as a TimeoutError like an unreachable folder. Tested with three processes adding keys at once. * test(thumbnails): cover the space refusal, Overview's Use this folder and the prune review (#320) The frontend coverage floors of activity-kinds, system-overview and thumbnail-review: a disk without the space shows the review but cannot move (a fixture route fakes the free space), Use this folder on Overview reloads the host values, the prune review's text and rows are pure functions with unit tests, and Overview takes the System drafts it is always mounted with. * fix(thumbnails): never copy through a linked folder; refuse a target inside the folder in use (#320) Moving back to Inside each source followed an existing linked folder in the destination and could replace a file outside the source (Codex P1). A target nested inside the thumbnail folder in use was accepted, and the old-copy cleanup then removed the previews just copied there (Codex P2). Every copy now checks the whole destination chain for links, also when the folders exist, and the move refuses a folder inside the one in use with location-inside-current. The cancelled branches no longer mix explicit and implicit returns (code-quality note). * fix(system): one full stop in the move-back review (#320) * fix(thumbnails): a folder check answers for the folder as it is now (#320) Probe.check() joined a check already running, or a finished one nobody had collected. A folder deleted right after configure() woke the probe therefore stayed available until the next probe, which failed the Overview notice spec in the merge queue. It now waits for a running check and starts a new one, still never two at once, and a stuck check still times out. The spec also asserts the fixture's removal took effect.
514 lines
18 KiB
Python
514 lines
18 KiB
Python
"""Native reported locations and already-opened current media, without ownership."""
|
|
|
|
import asyncio
|
|
from dataclasses import dataclass
|
|
import errno
|
|
import hashlib
|
|
import hmac
|
|
import io
|
|
import json
|
|
import mimetypes
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
from typing import BinaryIO
|
|
|
|
from aiohttp import web
|
|
|
|
from . import preview_store, thumbnail_settings
|
|
from .images import _canonical, _public_path, SERVABLE_EXTENSIONS, VIDEO_EXTENSIONS
|
|
from .images import in_trash_below_roots
|
|
from .images import existing_media_thumbnail, media_preview_path
|
|
|
|
try:
|
|
from ...utils.execution_outputs import (
|
|
OutputReference,
|
|
OutputRoots,
|
|
snapshot_output_roots,
|
|
validate_output_reference,
|
|
)
|
|
except ImportError:
|
|
from utils.execution_outputs import (
|
|
OutputReference,
|
|
OutputRoots,
|
|
snapshot_output_roots,
|
|
validate_output_reference,
|
|
)
|
|
|
|
_SECRET = os.urandom(32)
|
|
_READ_SIZE = 64 * 1024
|
|
|
|
|
|
def _opaque(value: object) -> str:
|
|
raw = json.dumps(value, ensure_ascii=True, separators=(",", ":")).encode("ascii")
|
|
return hmac.new(_SECRET, raw, hashlib.sha256).hexdigest()
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class CurrentOutputScope:
|
|
path_style: str
|
|
lexical_output: str | None
|
|
lexical_temp: str | None
|
|
roots: OutputRoots
|
|
canonical_output: Path | None
|
|
canonical_temp: Path | None
|
|
authorized_roots: tuple[Path, ...]
|
|
current_scope: str
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ResolvedCurrentCandidate:
|
|
public: dict
|
|
canonical_target: Path | None = None
|
|
namespace: Path | None = None
|
|
gallery_root: Path | None = None
|
|
|
|
|
|
class CurrentLocationUnavailable(Exception):
|
|
"""A bounded current-file failure without the underlying private path."""
|
|
|
|
def __init__(self, reason: str, *, stale: bool = False) -> None:
|
|
self.reason = reason
|
|
self.stale = stale
|
|
super().__init__(reason)
|
|
|
|
|
|
def _host_directory(name: str) -> str | None:
|
|
try:
|
|
import folder_paths
|
|
|
|
value = getattr(folder_paths, name)()
|
|
except (ImportError, AttributeError, OSError):
|
|
return None
|
|
return value if type(value) is str else None
|
|
|
|
|
|
def snapshot_current_output_scope(api: object) -> CurrentOutputScope:
|
|
"""Bind host lexical namespaces independently of current gallery authority."""
|
|
from ..config import GalleryConfig
|
|
|
|
style = "windows" if os.name == "nt" else "posix"
|
|
output = _host_directory("get_output_directory")
|
|
temp = _host_directory("get_temp_directory")
|
|
roots = snapshot_output_roots(style, output, temp)
|
|
canonical_output = _canonical(output) if roots.output_key is not None else None
|
|
canonical_temp = _canonical(temp) if roots.temp_key is not None else None
|
|
authorized = tuple(
|
|
sorted({_canonical(path) for path in api._get_all_output_dirs()})
|
|
)
|
|
policy = []
|
|
for entry in GalleryConfig.MONITORING_DIRECTORIES:
|
|
valid, _ = GalleryConfig.validate_gallery_root(entry)
|
|
policy.append((entry if type(entry) is str else None, valid))
|
|
current_scope = _opaque(
|
|
[
|
|
"prompt-manager-current-output-v1",
|
|
style,
|
|
output,
|
|
temp,
|
|
roots.output_key,
|
|
roots.temp_key,
|
|
str(canonical_output) if canonical_output is not None else None,
|
|
str(canonical_temp) if canonical_temp is not None else None,
|
|
[str(path) for path in authorized],
|
|
sorted(
|
|
str(_canonical(path))
|
|
for path in GalleryConfig.allowed_gallery_parents()
|
|
),
|
|
sorted(policy, key=lambda item: (item[0] or "", item[1])),
|
|
sorted(str(_canonical(path)) for path in GalleryConfig.path_anchors()),
|
|
"gallery-validation-v1",
|
|
]
|
|
)
|
|
return CurrentOutputScope(
|
|
style,
|
|
output,
|
|
temp,
|
|
roots,
|
|
canonical_output,
|
|
canonical_temp,
|
|
authorized,
|
|
current_scope,
|
|
)
|
|
|
|
|
|
def _descriptor_reason(reference: dict, scope: CurrentOutputScope) -> str | None:
|
|
try:
|
|
validate_output_reference(OutputReference("current", 0, **reference))
|
|
except (TypeError, ValueError):
|
|
return "namespace_mismatch"
|
|
if reference["path_style"] != scope.path_style:
|
|
return "foreign_path_style"
|
|
folder = reference["folder_type"]
|
|
expected = scope.roots.output_key if folder == "output" else scope.roots.temp_key
|
|
if reference["root_key"] is None or expected is None:
|
|
return "root_unavailable"
|
|
if reference["root_key"] != expected:
|
|
return "namespace_mismatch"
|
|
return None
|
|
|
|
|
|
def candidate_locator(reference: dict, scope: CurrentOutputScope) -> str | None:
|
|
"""Validate the native namespace before constructing a lexical path; no IO."""
|
|
if _descriptor_reason(reference, scope) is not None:
|
|
return None
|
|
root = (
|
|
scope.lexical_output
|
|
if reference["folder_type"] == "output"
|
|
else scope.lexical_temp
|
|
)
|
|
return os.path.normcase(
|
|
os.path.normpath(
|
|
os.path.join(root, reference["subfolder"], reference["filename"])
|
|
)
|
|
)
|
|
|
|
|
|
def _authorized(target: Path, namespace: Path, scope: CurrentOutputScope) -> bool:
|
|
return target.is_relative_to(namespace) and any(
|
|
target.is_relative_to(root) for root in scope.authorized_roots
|
|
)
|
|
|
|
|
|
def _unavailable(reason: str, *, error: bool = False) -> ResolvedCurrentCandidate:
|
|
return ResolvedCurrentCandidate(
|
|
{
|
|
"status": "error" if error else "unavailable",
|
|
"reason": reason,
|
|
"evidence_class": "locator_candidate",
|
|
}
|
|
)
|
|
|
|
|
|
def resolve_current_candidate(
|
|
reference: dict, scope: CurrentOutputScope, gallery: dict
|
|
) -> ResolvedCurrentCandidate:
|
|
"""Observe only this exact current locator and its snapshot-owned association."""
|
|
reason = _descriptor_reason(reference, scope)
|
|
if reason is not None:
|
|
return _unavailable(reason)
|
|
lexical = candidate_locator(reference, scope)
|
|
namespace = (
|
|
scope.canonical_output
|
|
if reference["folder_type"] == "output"
|
|
else scope.canonical_temp
|
|
)
|
|
try:
|
|
if Path(reference["filename"]).suffix.lower() not in SERVABLE_EXTENSIONS:
|
|
return _unavailable("unsupported_media")
|
|
if namespace is None or not namespace.is_dir():
|
|
return _unavailable("root_unavailable")
|
|
target = _canonical(lexical)
|
|
if in_trash_below_roots(target, [namespace]):
|
|
# Every kind and the outputs listing come through here (#543).
|
|
return _unavailable("missing")
|
|
if not _authorized(target, namespace, scope):
|
|
return _unavailable("not_authorized")
|
|
if target.suffix.lower() not in SERVABLE_EXTENSIONS:
|
|
return _unavailable("unsupported_media")
|
|
observed = target.stat()
|
|
if not stat.S_ISREG(observed.st_mode):
|
|
return _unavailable("not_regular_file")
|
|
if not os.access(target, os.R_OK) or not observed.st_mode & 0o444:
|
|
return _unavailable("unreadable")
|
|
matching = gallery.get(lexical, {})
|
|
root = max(
|
|
(root for root in scope.authorized_roots if target.is_relative_to(root)),
|
|
key=lambda root: len(root.parts),
|
|
)
|
|
return ResolvedCurrentCandidate(
|
|
{
|
|
"status": "available",
|
|
"reason": None,
|
|
"evidence_class": "locator_candidate",
|
|
"gallery_match": matching.get("gallery_match", "none"),
|
|
"gallery_image_id": matching.get("gallery_image_id"),
|
|
"source_label": _public_path(namespace),
|
|
"relative_path": Path(
|
|
reference["subfolder"], reference["filename"]
|
|
).as_posix(),
|
|
"current_scope": scope.current_scope,
|
|
"location_key": _opaque(
|
|
["current-location-v1", scope.current_scope, str(target)]
|
|
),
|
|
},
|
|
target,
|
|
namespace,
|
|
root,
|
|
)
|
|
except FileNotFoundError:
|
|
return _unavailable("missing")
|
|
except PermissionError:
|
|
return _unavailable("unreadable")
|
|
except (OSError, ValueError):
|
|
return _unavailable("temporary_unavailable", error=True)
|
|
|
|
|
|
def _target_authorized(target, namespace, scope, store_root=None) -> bool:
|
|
"""A preview in the thumbnail folder (#320, folder mode) is authorized by
|
|
the store of its source (``preview_store.owns``: inside the key folder,
|
|
no link); everything else by the output namespace and the roots."""
|
|
if (
|
|
store_root is not None
|
|
and preview_store.current().mode == preview_store.FOLDER_MODE
|
|
):
|
|
return preview_store.owns(store_root, target)
|
|
return _authorized(target, namespace, scope)
|
|
|
|
|
|
def _open_current_target(
|
|
target: Path,
|
|
namespace: Path,
|
|
scope: CurrentOutputScope,
|
|
preview: bool = False,
|
|
store_root: Path | None = None,
|
|
) -> BinaryIO:
|
|
"""Open only the canonical target and verify authority against the actual handle.
|
|
|
|
A *preview* (a file under ``thumbnails/``) may also be JPEG XL (#317); in
|
|
folder mode it is authorized by the store of *store_root* (#320)."""
|
|
if _canonical(target) != target:
|
|
raise CurrentLocationUnavailable("not_authorized", stale=True)
|
|
if in_trash_below_roots(target, [namespace]):
|
|
# Also at the open: the cover chooses its preview after the candidate
|
|
# check, and a preview can be a link into a trash folder (#543).
|
|
raise CurrentLocationUnavailable("missing")
|
|
if not _target_authorized(target, namespace, scope, store_root):
|
|
raise CurrentLocationUnavailable("not_authorized")
|
|
suffix = target.suffix.lower()
|
|
if suffix not in SERVABLE_EXTENSIONS and not (
|
|
preview and suffix in thumbnail_settings.THUMBNAIL_EXTENSIONS
|
|
):
|
|
raise CurrentLocationUnavailable("unsupported_media")
|
|
flags = (
|
|
os.O_RDONLY
|
|
| getattr(os, "O_BINARY", 0)
|
|
| getattr(os, "O_NOFOLLOW", 0)
|
|
| getattr(os, "O_NONBLOCK", 0)
|
|
)
|
|
try:
|
|
fd = os.open(target, flags)
|
|
except FileNotFoundError:
|
|
raise CurrentLocationUnavailable("missing") from None
|
|
except PermissionError:
|
|
raise CurrentLocationUnavailable("unreadable") from None
|
|
except OSError as error:
|
|
if error.errno in (errno.ELOOP, errno.ENOTDIR):
|
|
raise CurrentLocationUnavailable("not_authorized", stale=True) from None
|
|
raise CurrentLocationUnavailable("temporary_unavailable") from None
|
|
try:
|
|
observed = os.fstat(fd)
|
|
if not stat.S_ISREG(observed.st_mode):
|
|
raise CurrentLocationUnavailable("not_regular_file")
|
|
if not observed.st_mode & 0o444 or not os.access(target, os.R_OK):
|
|
raise CurrentLocationUnavailable("unreadable")
|
|
current = os.stat(target, follow_symlinks=False)
|
|
if (
|
|
_canonical(target) != target
|
|
or (observed.st_dev, observed.st_ino) != (current.st_dev, current.st_ino)
|
|
or not _target_authorized(target, namespace, scope, store_root)
|
|
):
|
|
raise CurrentLocationUnavailable("not_authorized", stale=True)
|
|
return os.fdopen(fd, "rb")
|
|
except FileNotFoundError:
|
|
os.close(fd)
|
|
raise CurrentLocationUnavailable("missing") from None
|
|
except PermissionError:
|
|
os.close(fd)
|
|
raise CurrentLocationUnavailable("unreadable") from None
|
|
except BaseException:
|
|
os.close(fd)
|
|
raise
|
|
|
|
|
|
def _reauthorize_current_target(
|
|
resolved: ResolvedCurrentCandidate, scope: CurrentOutputScope
|
|
) -> None:
|
|
if _canonical(
|
|
resolved.canonical_target
|
|
) != resolved.canonical_target or not _authorized(
|
|
resolved.canonical_target, resolved.namespace, scope
|
|
):
|
|
raise CurrentLocationUnavailable("not_authorized", stale=True)
|
|
|
|
|
|
@dataclass
|
|
class _OpenedCurrentMedia:
|
|
handle: BinaryIO
|
|
size: int
|
|
content_type: str
|
|
|
|
def close(self) -> None:
|
|
self.handle.close()
|
|
|
|
|
|
def _preview_writable(root: Path, preview: Path) -> bool:
|
|
"""A preview may be written: the store of *root* and every link segment
|
|
of the preview's folder resolve inside it (the serve route's rule, #249;
|
|
``preview_store.owns``)."""
|
|
return preview_store.owns(root, preview)
|
|
|
|
|
|
def _is_jxl(path) -> bool:
|
|
return Path(path).suffix.lower() == ".jxl"
|
|
|
|
|
|
def _preview_without_jxl(root: Path, relative: Path) -> Path | None:
|
|
"""The first existing preview *relative* owns that is not JPEG XL."""
|
|
return next(
|
|
(
|
|
path
|
|
for path in thumbnail_settings.owned_thumbnails(root, relative)
|
|
if not _is_jxl(path)
|
|
),
|
|
None,
|
|
)
|
|
|
|
|
|
def accepts_jxl(request) -> bool:
|
|
"""Whether the request's ``Accept`` lists ``image/jxl``."""
|
|
accept = request.headers.get("Accept", "")
|
|
return any(
|
|
part.split(";", 1)[0].strip().lower() == "image/jxl"
|
|
for part in accept.split(",")
|
|
)
|
|
|
|
|
|
def _placeholder_media(placeholder: bytes) -> "_OpenedCurrentMedia":
|
|
return _OpenedCurrentMedia(io.BytesIO(placeholder), len(placeholder), "image/jpeg")
|
|
|
|
|
|
def _cover_target(resolved, ensure_preview, placeholder, accepts_jxl):
|
|
"""What the cover opens: a preview path, the placeholder media, or None
|
|
for the original (see ``_prepare_current_media``)."""
|
|
target = resolved.canonical_target
|
|
relative = target.relative_to(resolved.gallery_root)
|
|
is_video = target.suffix.lower() in VIDEO_EXTENSIONS
|
|
# #317: any preview the file owns (the current format first); a missing
|
|
# one is made under the current format's name.
|
|
preview = existing_media_thumbnail(resolved.gallery_root, relative)
|
|
if preview is not None and not accepts_jxl and _is_jxl(preview):
|
|
preview = _preview_without_jxl(resolved.gallery_root, relative)
|
|
if preview is None:
|
|
if is_video and placeholder is not None:
|
|
return _placeholder_media(placeholder)
|
|
return None
|
|
return _canonical(preview)
|
|
if preview is not None:
|
|
return _canonical(preview)
|
|
preview = media_preview_path(resolved.gallery_root, relative, create=True)
|
|
if (
|
|
ensure_preview is not None
|
|
and preview is not None
|
|
and _preview_writable(resolved.gallery_root, preview)
|
|
):
|
|
ensure_preview(target, preview, is_video)
|
|
if is_video and placeholder is not None:
|
|
return _placeholder_media(placeholder)
|
|
return None
|
|
|
|
|
|
def _prepare_current_media(
|
|
resolved: ResolvedCurrentCandidate,
|
|
scope: CurrentOutputScope,
|
|
*,
|
|
thumbnail: bool,
|
|
ensure_preview=None,
|
|
placeholder: bytes | None = None,
|
|
accepts_jxl: bool = True,
|
|
) -> _OpenedCurrentMedia:
|
|
"""Open the current file, or its preview for ``thumbnail``.
|
|
|
|
A missing preview that may be written is handed to
|
|
``ensure_preview(src, dst, is_video)`` (the route makes it and reads
|
|
again, #249). Without one an image's original is opened and a video is
|
|
the ``placeholder`` JPEG, never the video inside an ``<img>``.
|
|
|
|
The cover's URL names no format, so a JPEG XL preview goes only to a
|
|
browser whose ``Accept`` lists ``image/jxl`` (*accepts_jxl*, review M3).
|
|
Another one gets the file's preview in another format when there is one,
|
|
else the original image or a video's placeholder: never a broken image.
|
|
"""
|
|
target = resolved.canonical_target
|
|
is_preview = False
|
|
if thumbnail:
|
|
chosen = _cover_target(resolved, ensure_preview, placeholder, accepts_jxl)
|
|
if isinstance(chosen, _OpenedCurrentMedia):
|
|
return chosen
|
|
if chosen is not None:
|
|
target, is_preview = chosen, True
|
|
handle = _open_current_target(
|
|
target,
|
|
resolved.namespace,
|
|
scope,
|
|
is_preview,
|
|
resolved.gallery_root if is_preview else None,
|
|
)
|
|
try:
|
|
return _OpenedCurrentMedia(
|
|
handle,
|
|
os.fstat(handle.fileno()).st_size,
|
|
thumbnail_settings.content_type(target)
|
|
or mimetypes.guess_type(target.name)[0]
|
|
or "application/octet-stream",
|
|
)
|
|
except BaseException:
|
|
handle.close()
|
|
raise
|
|
|
|
|
|
async def _current_media_response(
|
|
request: web.Request, opened: _OpenedCurrentMedia
|
|
) -> web.StreamResponse:
|
|
"""Stream a bounded single range from a previously authorized handle."""
|
|
try:
|
|
try:
|
|
selected = request.http_range
|
|
start, stop = selected.start, selected.stop
|
|
partial = request.headers.get("Range") is not None
|
|
if (
|
|
partial
|
|
and request.headers["Range"].startswith("bytes=-")
|
|
and start == 0
|
|
):
|
|
raise ValueError("Empty suffix range")
|
|
if start is not None and start < 0:
|
|
start = max(0, opened.size + start)
|
|
start = start or 0
|
|
stop = min(opened.size, stop) if stop is not None else opened.size
|
|
if partial and (start >= stop or start >= opened.size):
|
|
raise ValueError("Unsatisfiable current media range")
|
|
except ValueError:
|
|
return web.Response(
|
|
status=416,
|
|
headers={
|
|
"Cache-Control": "no-store",
|
|
"Content-Range": f"bytes */{opened.size}",
|
|
},
|
|
)
|
|
headers = {
|
|
"Cache-Control": "no-store",
|
|
"Accept-Ranges": "bytes",
|
|
"Content-Type": opened.content_type,
|
|
"Content-Length": str(stop - start),
|
|
}
|
|
if partial:
|
|
headers["Content-Range"] = f"bytes {start}-{stop - 1}/{opened.size}"
|
|
response = web.StreamResponse(status=206 if partial else 200, headers=headers)
|
|
await response.prepare(request)
|
|
if request.method != "HEAD":
|
|
opened.handle.seek(start)
|
|
remaining = stop - start
|
|
while remaining:
|
|
chunk = await asyncio.get_running_loop().run_in_executor(
|
|
None, opened.handle.read, min(_READ_SIZE, remaining)
|
|
)
|
|
if not chunk:
|
|
break
|
|
remaining -= len(chunk)
|
|
await response.write(chunk)
|
|
await response.write_eof()
|
|
return response
|
|
finally:
|
|
opened.close()
|