Files
romm/backend/utils/nginx.py
Georges-Antoine Assi 72cb59ecac fix(roms): list the plain filename first in Content-Disposition
EmulatorJS's nightly build (loaded when netplay is on) names a downloaded
ROM with /filename="?([^";]+)"?/ against Content-Disposition. With
filename* first, that matched "*=UTF-8''xmcota.zip", so FBNeo and the MAME
cores, which identify a romset by its file name, reported an unknown
romset. The nightly now keeps arcade zips whole, so the name is all that
still broke them.

RFC 6266 appendix D asks for filename before filename* for this reason;
browsers still prefer filename*. The header is built by one helper now,
and ZipResponse takes the raw name so it is encoded once.

Fixes #3279

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 08:40:29 -04:00

108 lines
3.7 KiB
Python

import dataclasses
from collections.abc import Collection
from pathlib import PurePath
from typing import Any
from urllib.parse import quote
from anyio import Path
from fastapi.responses import Response
from utils.filesystem import CONTROL_CHARS
def content_disposition(filename: str, disposition: str = "attachment") -> str:
"""Build a Content-Disposition value for `filename`, percent-encoded once."""
encoded = quote(filename)
# Plain `filename` first (RFC 6266 appendix D): EmulatorJS reads the first match.
return f"{disposition}; filename=\"{encoded}\"; filename*=UTF-8''{encoded}"
@dataclasses.dataclass(frozen=True)
class ZipContentLine:
"""Dataclass for lines returned in the response body, for usage with the `mod_zip` module.
Reference:
https://github.com/evanmiller/mod_zip?tab=readme-ov-file#usage
"""
crc32: str | None
size_bytes: int
encoded_location: str
filename: str
def __post_init__(self) -> None:
"""Keep the rendered line parseable as exactly one mod_zip record.
The manifest is line-oriented, so a line feed in a name taken off disk
would otherwise let that name forge an extra archive entry.
"""
location = self.encoded_location
if " " in location or CONTROL_CHARS.search(location):
raise ValueError(f"mod_zip location must be URL-encoded, got {location!r}")
object.__setattr__(self, "filename", CONTROL_CHARS.sub("_", self.filename))
def __str__(self) -> str:
crc32 = self.crc32 or "-"
return f"{crc32} {self.size_bytes} {self.encoded_location} {self.filename}"
class ZipResponse(Response):
"""Response class for returning a ZIP archive with multiple files, using the `mod_zip` module."""
def __init__(
self,
*,
content_lines: Collection[ZipContentLine],
filename: str,
**kwargs: Any,
):
if kwargs.get("content"):
raise ValueError(
"Argument 'content' must not be provided, as it is generated from 'content_lines'"
)
kwargs["content"] = "\n".join(str(line) for line in content_lines)
kwargs.setdefault("headers", {}).update(
{
"Content-Disposition": content_disposition(filename),
"X-Archive-Files": "zip",
"X-Archive-Charset": "UTF-8",
}
)
super().__init__(**kwargs)
class FileRedirectResponse(Response):
"""Response class for serving a file download by using the X-Accel-Redirect header."""
def __init__(
self,
*,
download_path: Path | PurePath,
filename: str | None = None,
disposition: str = "attachment",
**kwargs: Any,
):
"""
Arguments:
- download_path: Path to the file to be served. Only its name and string
form are read, so either flavour of Path works.
- filename: Name of the file to be served. If not provided, the file name from the
download_path is used.
- disposition: "attachment" (default) forces a download; "inline" lets the
browser render/stream the file (required for <audio> to issue Range
requests and seek). Nginx itself still handles the Range parsing.
"""
media_type = kwargs.pop("media_type", "application/octet-stream")
filename = filename or download_path.name
kwargs.setdefault("headers", {}).update(
{
"Content-Disposition": content_disposition(filename, disposition),
"X-Accel-Redirect": quote(str(download_path)),
}
)
super().__init__(media_type=media_type, **kwargs)