web_server_remote_media.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Inline audio/video from a profile's SSH workspace for ``/api/files/stream``.
  2. A host file streams through Starlette's ``FileResponse``, which answers ``Range`` itself. A file on
  3. the SSH machine has no local handle, so this answers the one byte range a media element asks for
  4. by reading exactly that slice through the workspace adapter (``SshWorkspaceFs.stream_file``).
  5. The caller has already chosen the backend and checked the file (sensitive path, media type, size).
  6. """
  7. from __future__ import annotations
  8. import re
  9. import urllib.parse
  10. from pathlib import PurePosixPath
  11. from typing import Any
  12. from fastapi import HTTPException, Request
  13. from fastapi.responses import Response, StreamingResponse
  14. _SINGLE_RANGE = re.compile(r"^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$", re.IGNORECASE)
  15. # More digits than any file this route serves can need. A longer number is read as one value past
  16. # every file instead of being converted: int() refuses a few thousand digits (a 500).
  17. _MAX_POSITION_DIGITS = 19
  18. _PAST_ANY_FILE = 10**_MAX_POSITION_DIGITS
  19. def _position(digits: str) -> int:
  20. """A ``Range`` byte position, or ``_PAST_ANY_FILE`` for one too long to be in any file."""
  21. digits = digits.lstrip("0") or "0"
  22. return int(digits) if len(digits) <= _MAX_POSITION_DIGITS else _PAST_ANY_FILE
  23. def _unsatisfiable(size: int) -> HTTPException:
  24. return HTTPException(
  25. status_code=416, detail="Requested range not satisfiable", headers={"Content-Range": f"bytes */{size}"},
  26. )
  27. def byte_range(header: str | None, size: int) -> tuple[int, int] | None:
  28. """The inclusive ``(first, last)`` byte span one ``bytes=`` range asks of a *size*-byte file,
  29. or None to serve the whole file. A header this does not read (several ranges, another unit, a
  30. last byte before the first) is ignored, as RFC 9110 allows; a range the file cannot satisfy
  31. raises 416. A last byte past the end is the end, and a suffix longer than the file is all of it,
  32. however many digits either has."""
  33. match = _SINGLE_RANGE.match(header or "")
  34. if match is None or match.groups() == ("", ""):
  35. return None
  36. first_digits, last_digits = match.groups()
  37. if not first_digits: # a suffix: the last N bytes
  38. suffix = _position(last_digits)
  39. if suffix == 0 or size == 0:
  40. raise _unsatisfiable(size)
  41. return max(size - suffix, 0), size - 1
  42. first = _position(first_digits)
  43. last = _position(last_digits) if last_digits else None
  44. if last is not None and last < first:
  45. return None
  46. if first >= size:
  47. raise _unsatisfiable(size)
  48. return first, min(last, size - 1) if last is not None else size - 1
  49. def remote_media_response(request: Request, workspace: Any, target: str, size: int, media_type: str) -> Response:
  50. """*target* on the SSH *workspace* as inline media: 200 for the whole file, 206 for the range
  51. the request asks, 416 for one it cannot have. A HEAD reads none of it."""
  52. span = byte_range(request.headers.get("range"), size)
  53. first, last = span if span is not None else (0, size - 1)
  54. length = max(last - first + 1, 0)
  55. name = urllib.parse.quote(PurePosixPath(target).name)
  56. headers = {
  57. "Accept-Ranges": "bytes",
  58. "Content-Disposition": f"inline; filename*=UTF-8''{name}",
  59. "Content-Length": str(length),
  60. "X-Content-Type-Options": "nosniff",
  61. }
  62. status = 200
  63. if span is not None:
  64. status = 206
  65. headers["Content-Range"] = f"bytes {first}-{last}/{size}"
  66. if request.method == "HEAD" or length == 0:
  67. return Response(status_code=status, media_type=media_type, headers=headers)
  68. body = workspace.stream_file(target, offset=first, length=length) if span else workspace.stream_file(target)
  69. return StreamingResponse(body, status_code=status, media_type=media_type, headers=headers)