52 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			52 lines
		
	
	
		
			1.6 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
| from __future__ import unicode_literals
 | |
| import youtube_dl
 | |
| import os
 | |
| import logging
 | |
| 
 | |
| 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):
 | |
|         # print(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(),
 | |
|             'progress_hooks': [self.post_download_hook],
 | |
|             'updatetime': False
 | |
|         }
 | |
|         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 = ""
 | |
| 
 | |
|         return article_object
 | 
