musicdlp/backend/cover.py
DarkCat09 03458db829
Fix: cover.download()
- resp.read returns nothing, contents are already in resp.data
- add mime type safety check
2024-05-09 18:33:13 +04:00

46 lines
1.1 KiB
Python

import mimetypes
import subprocess
from pathlib import Path
import http_pool
def download_from_yt(url: str, album_path: Path) -> None:
'''YouTube-specific cover art downloader.
See https://git.dc09.ru/DarkCat09/musicdlp/issues/1#issuecomment-202'''
path = album_path / 'cover.webp'
if path.exists():
return
ret = subprocess.call(
[
'ffmpeg',
'-nostdin',
'-i', url,
'-vf', 'crop=ih:ih',
str(album_path / 'cover.webp'),
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if ret != 0:
raise RuntimeError(f'FFmpeg returned {ret} exit code')
def download(url: str, album_path: Path) -> None:
'''General cover art downloader'''
resp = http_pool.get().request('GET', url)
ct = resp.headers['content-type']
if not ct.startswith('image'):
raise ValueError('thumbnail is not an image')
ext = mimetypes.guess_extension(ct) or '.jpg'
path = album_path / ('cover' + ext)
if path.exists():
return
with path.open('wb') as f:
f.write(resp.data)