import youtube_dl import os import logging import configuration download_config = configuration.config["downloads"] logger = logging.getLogger(__name__) class MyLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(self, msg): logger.error(msg) class YouTubeDownloader: def __init__(self) -> None: pass def post_download_hook(self, ret_code): if ret_code['status'] == 'finished': file_loc = ret_code["filename"] fname = os.path.basename(file_loc) self.article_object.file_name = fname def save_video(self, article_object): """Saves video accoring to url and save path""" self.article_object = article_object url = article_object.article_url logger.info("Saving new video") file_path = os.path.join(article_object.save_path, article_object.fname_template) ydl_opts = { 'format': 'best[height<=720]', 'outtmpl': f"{file_path}.%(ext)s", # basically the filename from the object, but with a custom extension depending on the download 'logger': MyLogger(), # supress verbosity 'progress_hooks': [self.post_download_hook], 'updatetime': False, # File is also used by firefox so make sure to not write to it! # youtube dl apparenlty does not support cookies.sqlite and the documentation is not clear on how to use cookies.txt } try: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) # article file name is updated in self.post_download_hook except Exception as e: logger.error(f"Youtube download crashed: {e}") article_object.file_name = "" logfile = os.path.join(download_config["local_storage_path"], "failed_downloads.csv") logger.info(f"Logging youtube errors seperately to {logfile}") with open(logfile, "a+") as f: f.write(f"{url}\n") return article_object