Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions app/services/media_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ def build_range_response(file_path: str, range_header: str) -> Response:
file_size = os.path.getsize(file_path)
stat = os.stat(file_path)

# Parse range header: "bytes=start-end"
# Parse range header: "bytes=start-end" or suffix-byte-range "bytes=-N"
range_spec = range_header.replace("bytes=", "").strip()
parts = range_spec.split("-")

start = int(parts[0]) if parts[0] else 0
end = int(parts[1]) if len(parts) > 1 and parts[1] else file_size - 1
if not parts[0] and len(parts) > 1 and parts[1]:
suffix_length = int(parts[1])
start = max(0, file_size - suffix_length)
end = file_size - 1
else:
start = int(parts[0]) if parts[0] else 0
end = int(parts[1]) if len(parts) > 1 and parts[1] else file_size - 1

# Clamp values
start = max(0, start)
Expand Down
29 changes: 29 additions & 0 deletions tests/test_media_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from pathlib import Path

from app.services.media_server import build_range_response


def test_build_range_response_supports_suffix_byte_range(tmp_path: Path):
file_path = tmp_path / "sample.bin"
content = b"0123456789"
file_path.write_bytes(content)

response = build_range_response(str(file_path), "bytes=-4")

assert response.status_code == 206
assert response.body == b"6789"
assert response.headers["content-range"] == "bytes 6-9/10"
assert response.headers["content-length"] == "4"


def test_build_range_response_keeps_standard_range_behavior(tmp_path: Path):
file_path = tmp_path / "sample.bin"
content = b"0123456789"
file_path.write_bytes(content)

response = build_range_response(str(file_path), "bytes=2-5")

assert response.status_code == 206
assert response.body == b"2345"
assert response.headers["content-range"] == "bytes 2-5/10"
assert response.headers["content-length"] == "4"