2020-06-02 00:05:02 +12:00
|
|
|
import os
|
2021-02-07 01:29:13 +13:00
|
|
|
import pathlib
|
2020-06-02 00:05:02 +12:00
|
|
|
import sys
|
|
|
|
|
2021-02-06 21:35:50 +13:00
|
|
|
import youtube_dl
|
2020-06-02 00:05:02 +12:00
|
|
|
|
2021-02-07 14:09:31 +13:00
|
|
|
from bulkredditdownloader.downloaders.downloader_utils import createHash
|
2021-02-07 14:05:18 +13:00
|
|
|
from bulkredditdownloader.errors import FileAlreadyExistsError
|
|
|
|
from bulkredditdownloader.utils import GLOBAL
|
|
|
|
from bulkredditdownloader.utils import printToFile as print
|
2021-02-06 21:35:50 +13:00
|
|
|
|
2020-06-02 00:05:02 +12:00
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2020-06-02 00:05:02 +12:00
|
|
|
class Youtube:
|
2021-02-07 01:29:13 +13:00
|
|
|
def __init__(self, directory: pathlib.Path, post: dict):
|
2021-02-25 22:32:06 +13:00
|
|
|
if not os.path.exists(directory):
|
|
|
|
os.makedirs(directory)
|
2020-06-02 00:05:02 +12:00
|
|
|
|
|
|
|
filename = GLOBAL.config['filename'].format(**post)
|
|
|
|
print(filename)
|
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
self.download(filename, directory, post['CONTENTURL'])
|
|
|
|
|
2021-02-07 01:29:13 +13:00
|
|
|
def download(self, filename: str, directory: pathlib.Path, url: str):
|
2020-06-02 00:05:02 +12:00
|
|
|
ydl_opts = {
|
|
|
|
"format": "best",
|
|
|
|
"outtmpl": str(directory / (filename + ".%(ext)s")),
|
|
|
|
"progress_hooks": [self._hook],
|
|
|
|
"playlistend": 1,
|
|
|
|
"nooverwrites": True,
|
|
|
|
"quiet": True
|
|
|
|
}
|
|
|
|
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
|
|
|
|
ydl.download([url])
|
|
|
|
|
2021-02-25 22:32:06 +13:00
|
|
|
location = directory / (filename + ".mp4")
|
2020-06-02 00:05:02 +12:00
|
|
|
|
|
|
|
if GLOBAL.arguments.no_dupes:
|
|
|
|
try:
|
2021-02-07 01:29:13 +13:00
|
|
|
file_hash = createHash(str(location))
|
2020-06-02 00:05:02 +12:00
|
|
|
except FileNotFoundError:
|
|
|
|
return None
|
2021-02-06 21:35:50 +13:00
|
|
|
if file_hash in GLOBAL.downloadedPosts():
|
2020-06-02 00:05:02 +12:00
|
|
|
os.remove(location)
|
|
|
|
raise FileAlreadyExistsError
|
2021-02-06 21:35:50 +13:00
|
|
|
GLOBAL.downloadedPosts.add(file_hash)
|
2021-02-25 22:32:06 +13:00
|
|
|
|
2020-06-02 00:05:02 +12:00
|
|
|
@staticmethod
|
|
|
|
def _hook(d):
|
2021-02-25 22:32:06 +13:00
|
|
|
if d['status'] == 'finished':
|
|
|
|
return print("Downloaded")
|
2021-02-06 21:35:50 +13:00
|
|
|
downloaded_mbs = int(d['downloaded_bytes'] * (10**(-6)))
|
|
|
|
file_size = int(d['total_bytes'] * (10**(-6)))
|
|
|
|
sys.stdout.write("{}Mb/{}Mb\r".format(downloaded_mbs, file_size))
|
2020-06-02 00:05:02 +12:00
|
|
|
sys.stdout.flush()
|