forked from trav/lintunes
v0.94.0: a playlist made from a Spotify or Apple Music link keeps the link's cover image (stored, not shown yet)
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""A playlist's own cover image (Round 130).
|
||||
|
||||
Spotify and Apple Music playlists (and albums) have a cover, and a playlist
|
||||
made from one of their links in Import from URL keeps it. Nothing *shows* it
|
||||
yet; this is only where it is kept.
|
||||
|
||||
One file per playlist, ``<data_dir>/playlist_art/<persistent_id>.jpg`` (or
|
||||
``.png``), so it rides the Syncthing share with the playlists but stays out
|
||||
of their JSON: a cover never makes a playlist look edited, and the conflict
|
||||
merge never has to know about it. Only the machine that made the playlist
|
||||
writes it. Writes are atomic (``.tmp`` → rename), like every JSON file.
|
||||
|
||||
A deleted playlist's cover is left where it is: undo brings the playlist
|
||||
back with the same id, and a cover is a few hundred KB.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
DIRNAME = "playlist_art"
|
||||
TIMEOUT = 20
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
USER_AGENT = ("Mozilla/5.0 (X11; Linux x86_64; rv:131.0) "
|
||||
"Gecko/20100101 Firefox/131.0")
|
||||
|
||||
_SUFFIXES = (".jpg", ".png")
|
||||
|
||||
|
||||
def image_suffix(data: bytes) -> str | None:
|
||||
"""".jpg" or ".png" by the bytes' own signature, else None."""
|
||||
if data[:3] == b"\xff\xd8\xff":
|
||||
return ".jpg"
|
||||
if data[:8] == b"\x89PNG\r\n\x1a\n":
|
||||
return ".png"
|
||||
return None
|
||||
|
||||
|
||||
def find(data_dir: Path, pid: str) -> Path | None:
|
||||
"""The playlist's cover file, or None when it has none."""
|
||||
folder = Path(data_dir) / DIRNAME
|
||||
for suffix in _SUFFIXES:
|
||||
path = folder / f"{pid}{suffix}"
|
||||
if path.is_file():
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def save(data_dir: Path, pid: str, data: bytes) -> Path:
|
||||
"""Keep ``data`` as the playlist's cover, replacing any other. Raises
|
||||
ValueError for bytes that aren't a JPEG or PNG."""
|
||||
suffix = image_suffix(data)
|
||||
if suffix is None:
|
||||
raise ValueError("not a JPEG or PNG image")
|
||||
if not pid or "/" in pid or pid.startswith("."):
|
||||
raise ValueError(f"bad playlist id {pid!r}")
|
||||
folder = Path(data_dir) / DIRNAME
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / f"{pid}{suffix}"
|
||||
tmp = path.with_name(path.name + ".tmp")
|
||||
tmp.write_bytes(data)
|
||||
os.replace(tmp, path)
|
||||
for other in _SUFFIXES:
|
||||
if other != suffix:
|
||||
(folder / f"{pid}{other}").unlink(missing_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def download(url: str) -> bytes:
|
||||
resp = requests.get(url, headers={"User-Agent": USER_AGENT},
|
||||
timeout=TIMEOUT, stream=True)
|
||||
resp.raise_for_status()
|
||||
data = b""
|
||||
for chunk in resp.iter_content(65536):
|
||||
data += chunk
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError("cover image is too large")
|
||||
return data
|
||||
|
||||
|
||||
def fetch_in_background(url: str, data_dir: Path, pid: str):
|
||||
"""Download ``url`` and keep it as the playlist's cover, on a daemon
|
||||
thread. A failure is logged and otherwise ignored: the playlist is
|
||||
complete without it."""
|
||||
def run():
|
||||
try:
|
||||
path = save(data_dir, pid, download(url))
|
||||
log.info("playlist art for %s saved to %s", pid, path)
|
||||
except Exception as e:
|
||||
log.warning("playlist art for %s from %s: %s", pid, url, e)
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
Reference in New Issue
Block a user