1
0
Fork 0
mirror of synced 2024-06-29 11:30:30 +12:00
bulk-downloader-for-reddit/bulkredditdownloader/site_downloaders/youtube.py

46 lines
1.5 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import logging
2021-02-11 12:10:40 +13:00
import tempfile
2021-02-28 17:52:20 +13:00
from pathlib import Path
2021-02-25 23:40:08 +13:00
from typing import Optional
import youtube_dl
2021-02-11 12:10:40 +13:00
from praw.models import Submission
2021-02-11 12:10:40 +13:00
from bulkredditdownloader.resource import Resource
2021-02-28 17:52:20 +13:00
from bulkredditdownloader.site_authenticator import SiteAuthenticator
2021-02-07 20:08:24 +13:00
from bulkredditdownloader.site_downloaders.base_downloader import BaseDownloader
logger = logging.getLogger(__name__)
2021-02-07 14:33:19 +13:00
class Youtube(BaseDownloader):
2021-02-15 18:12:27 +13:00
def __init__(self, post: Submission):
super().__init__(post)
2021-02-26 21:57:05 +13:00
def find_resources(self, authenticator: Optional[SiteAuthenticator] = None) -> list[Resource]:
2021-02-25 23:40:08 +13:00
return [self._download_video()]
2021-02-11 12:10:40 +13:00
def _download_video(self) -> Resource:
with tempfile.TemporaryDirectory() as temp_dir:
2021-02-28 17:52:20 +13:00
download_path = Path(temp_dir).resolve()
2021-02-11 12:10:40 +13:00
ydl_opts = {
"format": "best",
2021-02-28 17:52:20 +13:00
"outtmpl": str(download_path) + '/' + 'test.%(ext)s',
2021-02-11 12:10:40 +13:00
"playlistend": 1,
"nooverwrites": True,
"quiet": True
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([self.post.url])
2021-02-28 17:52:20 +13:00
downloaded_file = list(download_path.iterdir())[0]
extension = downloaded_file.suffix
with open(downloaded_file, 'rb') as file:
2021-02-11 12:10:40 +13:00
content = file.read()
2021-02-28 17:52:20 +13:00
out = Resource(self.post, self.post.url, extension)
2021-02-25 23:40:08 +13:00
out.content = content
2021-02-28 17:52:20 +13:00
out.create_hash()
2021-02-25 23:40:08 +13:00
return out