mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 03:45:09 +00:00
fix(session): make RnetResponse a context manager for cover downloads
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
"""An rnet response works in a ``with`` block, as a requests.Response does.
|
||||
|
||||
The music tagger reads a cover with ``with session.get(...)`` on the session that the service gives it.
|
||||
Each test here sends a real rnet request to a local server.
|
||||
The body has no image magic bytes, so a content type in a result comes only from the response header.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.music.tagger import download_cover
|
||||
from unshackle.core.session import RnetSession
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
COVER = b"cover body"
|
||||
|
||||
|
||||
class CoverServer(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "image/png")
|
||||
self.send_header("Content-Length", str(len(COVER)))
|
||||
self.end_headers()
|
||||
self.wfile.write(COVER)
|
||||
|
||||
def log_message(self, *args: object) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cover_url() -> Iterator[str]:
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), CoverServer)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield f"http://127.0.0.1:{httpd.server_port}/cover.png"
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
def test_a_with_block_gives_the_response_itself_and_its_content(cover_url: str) -> None:
|
||||
response = RnetSession().get(cover_url)
|
||||
|
||||
with response as entered:
|
||||
assert entered is response
|
||||
assert entered.content == COVER
|
||||
|
||||
|
||||
def test_the_end_of_the_with_block_closes_the_response(cover_url: str) -> None:
|
||||
with RnetSession().get(cover_url) as response:
|
||||
pass
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
_ = response.content
|
||||
|
||||
|
||||
def test_an_exception_in_the_with_block_propagates_and_the_response_still_closes(cover_url: str) -> None:
|
||||
with pytest.raises(ValueError, match="raised inside the with block"), RnetSession().get(cover_url) as response:
|
||||
raise ValueError("raised inside the with block")
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
_ = response.content
|
||||
|
||||
|
||||
def test_download_cover_returns_the_image_and_its_content_type(cover_url: str) -> None:
|
||||
assert download_cover(RnetSession(), cover_url) == (COVER, "image/png")
|
||||
@@ -12,6 +12,7 @@ from typing import Any
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.titles.music import song_metadata
|
||||
from unshackle.core.utils.collections import as_list
|
||||
from unshackle.core.utils.subprocess import log_tool_run
|
||||
@@ -76,7 +77,9 @@ class MusicMetadataResult:
|
||||
}
|
||||
|
||||
|
||||
def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_md5: str = "") -> MusicMetadataResult:
|
||||
def write_music_metadata(
|
||||
path: Path, song: Any, *, session: AnySession | None = None, source_md5: str = ""
|
||||
) -> MusicMetadataResult:
|
||||
"""Write normalized music metadata for FLAC, Ogg, Opus, MP3, WAV, and M4A/MP4 audio files.
|
||||
|
||||
Opus files get no ``REPLAYGAIN_*`` tags, because RFC 7845 section 5.2.1 says an Opus file should not carry them.
|
||||
@@ -324,7 +327,7 @@ def write_mp4_tags(path: Path, tags: TagValues, cover_data: bytes | None, mime_t
|
||||
audio.save()
|
||||
|
||||
|
||||
def download_cover(session: Any, artwork_url: str) -> tuple[bytes | None, str]:
|
||||
def download_cover(session: AnySession | None, artwork_url: str) -> tuple[bytes | None, str]:
|
||||
if not session or not artwork_url:
|
||||
return None, ""
|
||||
try:
|
||||
|
||||
@@ -118,7 +118,11 @@ class RnetResponseHeaders(MutableMapping):
|
||||
|
||||
|
||||
class RnetResponse:
|
||||
"""Wraps rnet.BlockingResponse with a requests-compatible API."""
|
||||
"""Wraps rnet.BlockingResponse with a requests-compatible API.
|
||||
|
||||
A ``with`` block gives this response and closes it at the end. Read the body inside the block:
|
||||
a body left unread cannot be read after it.
|
||||
"""
|
||||
|
||||
def __init__(self, resp: Any) -> None:
|
||||
self._resp = resp
|
||||
@@ -233,6 +237,12 @@ class RnetResponse:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> RnetResponse:
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc: Any) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
def utf8_text(res: Response | RnetResponse) -> str:
|
||||
"""Return the response text, decoded as UTF-8 unless the server sent a charset.
|
||||
|
||||
@@ -5,7 +5,6 @@ import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
from unshackle.core import binaries
|
||||
@@ -17,6 +16,7 @@ from unshackle.core.providers import (
|
||||
get_available_providers,
|
||||
resolve_by_ids,
|
||||
)
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.titles.movie import Movie
|
||||
from unshackle.core.titles.music import Song
|
||||
@@ -92,7 +92,7 @@ def tag_file(
|
||||
tvdb_id: int | None = None,
|
||||
anilist_id: int | str | None = None,
|
||||
anime: bool = False,
|
||||
session: Any = None,
|
||||
session: AnySession | None = None,
|
||||
) -> None:
|
||||
log.debug("Tagging file %s with title %r", path, title)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user