musicdlp/backend/ydl_pool.py

69 lines
1.7 KiB
Python

from yt_dlp import YoutubeDL
from yt_dlp.postprocessor import FFmpegExtractAudioPP
import config
import id3pp
class _CreateYDL:
@staticmethod
def youtube() -> YoutubeDL:
ydl = YoutubeDL({'format': 'ba'})
ydl.add_post_processor(id3pp.InfoYouTubePP(), when='before_dl')
ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec='mp3'), when='post_process')
return ydl
@staticmethod
def yt_proxied() -> YoutubeDL:
ydl = _CreateYDL.youtube()
ydl.params['proxy'] = config.get().yt_proxy
return ydl
@staticmethod
def yandex() -> YoutubeDL:
return YoutubeDL()
create_ydl_fn = {
'youtube': _CreateYDL.youtube,
'yt_proxied': _CreateYDL.yt_proxied,
'yandex': _CreateYDL.yandex,
}
ydl_fn_keys = create_ydl_fn.keys()
class Downloaders:
def __init__(self) -> None:
self.ydls: dict[str, YoutubeDL | None] = {
'youtube': None,
'yt_proxied': None,
'yandex': None,
}
def get_ydl(self, site: str) -> YoutubeDL:
cfg = config.get()
ydl = self.ydls[site]
if ydl is None:
ydl = create_ydl_fn[site]()
ydl.params['trim_file_name'] = cfg.path_length # Note: not only filename, but path in outtmpl
ydl.params['outtmpl']['default'] = cfg.tmpl
ydl.add_post_processor(id3pp.ID3TagsPP(), when='post_process')
cookies = cfg.cookies_dir / (site + '.txt')
if cookies.exists():
ydl.params['cookiefile'] = str(cookies)
return ydl
def cleanup(self) -> None:
for ydl in self.ydls.values():
if ydl is not None:
ydl.close()