Prześlij pliki do "audio"
This commit is contained in:
1 parent
30a27e3093
commit
01d8dc0562
1 file changed
+49
@@ -0,0 +1,49 @@
|
|||||||
|
# audio/cover_manager.py
|
||||||
|
import os
|
||||||
|
import json
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import pathlib
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class CoverManager:
|
||||||
|
"""
|
||||||
|
Pobiera i buforuje okładki stacji radiowych.
|
||||||
|
|
||||||
|
- `cache_dir` – katalog, w którym trzymane są pobrane pliki.
|
||||||
|
- `get_cover_path(station_id)` – zwraca pełną ścieżkę do pliku, albo None.
|
||||||
|
- `fetch_and_save(url, station_id)` – pobiera z sieci i zapisuje.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, cache_dir: str = "cover"):
|
||||||
|
self.cache_dir = pathlib.Path(cache_dir)
|
||||||
|
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
def _hash(self, text: str) -> str:
|
||||||
|
return hashlib.sha1(text.encode("utf-8")).hexdigest()[:10]
|
||||||
|
|
||||||
|
def get_cover_path(self, station_id: str) -> str | None:
|
||||||
|
"""Sprawdza, czy istnieje już pobrana okładka o danym ID."""
|
||||||
|
pattern = self.cache_dir / f"{self._hash(station_id)}.*"
|
||||||
|
matches = list(pattern.parent.glob(pattern.name))
|
||||||
|
if matches:
|
||||||
|
return str(matches[0])
|
||||||
|
return None
|
||||||
|
|
||||||
|
def fetch_and_save(self, url: str, station_id: str) -> str | None:
|
||||||
|
"""Pobiera okładkę i zapisuje pod hash‑owaną nazwą."""
|
||||||
|
try:
|
||||||
|
resp = urllib.request.urlopen(url, timeout=10)
|
||||||
|
data = resp.read()
|
||||||
|
ext = pathlib.Path(resp.url).suffix or ".jpg"
|
||||||
|
filename = self.cache_dir / f"{self._hash(station_id)}{ext}"
|
||||||
|
with open(filename, "wb") as f:
|
||||||
|
f.write(data)
|
||||||
|
log.info("Pobrano okładkę → %s", filename)
|
||||||
|
return str(filename)
|
||||||
|
except Exception as exc:
|
||||||
|
log.error("Nie udało się pobrać okładki (%s): %s", url, exc)
|
||||||
|
return None
|
||||||
Reference in new issue
Block a user