Skip to content
Snippets Groups Projects
ytdownloader.py 1.28 KiB
Newer Older
import logging
kjk's avatar
kjk committed
import shutil
from pathlib import Path

import yt_dlp.postprocessor
from yt_dlp import YoutubeDL

class YTDownloader:
kjk's avatar
kjk committed
    def __init__(self, audiodir: Path, videodir: Path, cache: bool):
kjk's avatar
kjk committed
        self.audiodir = audiodir
        self.videodir = videodir
kjk's avatar
kjk committed
        self.cache = cache
kjk's avatar
kjk committed

    def download(self, url: str, artist: str, song: str, spotify_uri: str):
kjk's avatar
kjk committed
        if (Path(self.videodir) / f"{artist} - {song}.mp4").is_file() and (Path(self.audiodir) / f"{artist} - {song}.mp3").is_file() and self.cache:
            return
kjk's avatar
kjk committed
        ydl_opts = {
            'logger': logging.getLogger("usdbdl"),
kjk's avatar
kjk committed
            'format': 'mp4/best',
kjk's avatar
kjk committed
            'outtmpl': f'{str((Path(self.audiodir) / f"{artist} - {song}").resolve())}.%(ext)s',
kjk's avatar
kjk committed
            # ℹ️ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
            'keepvideo': True,
            'postprocessors': [{  # Extract audio using ffmpeg
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
            }]
        }
        with YoutubeDL(ydl_opts) as ydl:
            ydl.download(url)

        Path(self.videodir).mkdir(parents=True, exist_ok=True)
kjk's avatar
kjk committed
        shutil.move(Path(self.audiodir) / f"{artist} - {song}.mp4", Path(self.videodir) / f"{artist} - {song}.mp4")