2020-04-02 20:17:26 +00:00
|
|
|
import logging
|
2016-05-05 11:23:15 +00:00
|
|
|
import urllib.request
|
2020-04-02 20:17:26 +00:00
|
|
|
import os
|
|
|
|
from tempfile import NamedTemporaryFile
|
|
|
|
from szurubooru import config, errors
|
|
|
|
from szurubooru.func import mime, util
|
|
|
|
from youtube_dl import YoutubeDL
|
|
|
|
from youtube_dl.utils import YoutubeDLError
|
2016-05-05 11:23:15 +00:00
|
|
|
|
2016-08-14 12:22:53 +00:00
|
|
|
|
2020-04-02 20:17:26 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
def download(url: str, use_video_downloader: bool = False) -> bytes:
|
2016-08-14 08:45:00 +00:00
|
|
|
assert url
|
2016-05-05 11:23:15 +00:00
|
|
|
request = urllib.request.Request(url)
|
2017-03-03 16:24:58 +00:00
|
|
|
if config.config['user_agent']:
|
|
|
|
request.add_header('User-Agent', config.config['user_agent'])
|
2016-05-05 11:23:15 +00:00
|
|
|
request.add_header('Referer', url)
|
2016-09-25 12:52:47 +00:00
|
|
|
try:
|
|
|
|
with urllib.request.urlopen(request) as handle:
|
2020-04-02 20:17:26 +00:00
|
|
|
content = handle.read()
|
2016-09-26 20:51:00 +00:00
|
|
|
except Exception as ex:
|
|
|
|
raise errors.ProcessingError('Error downloading %s (%s)' % (url, ex))
|
2020-04-02 20:17:26 +00:00
|
|
|
if (use_video_downloader and
|
|
|
|
mime.get_mime_type(content) == 'application/octet-stream'):
|
|
|
|
return _youtube_dl_wrapper(url)
|
|
|
|
return content
|
|
|
|
|
|
|
|
|
|
|
|
def _youtube_dl_wrapper(url: str) -> bytes:
|
2020-04-07 19:14:53 +00:00
|
|
|
outpath = os.path.join(
|
|
|
|
config.config['data_dir'],
|
|
|
|
'temporary-uploads',
|
|
|
|
'youtubedl-' + util.get_sha1(url)[0:8] + '.dat')
|
2020-04-02 20:17:26 +00:00
|
|
|
options = {
|
2020-04-03 19:32:25 +00:00
|
|
|
'ignoreerrors': False,
|
2020-04-05 18:58:58 +00:00
|
|
|
'format': 'best[ext=webm]/best[ext=mp4]/best[ext=flv]',
|
2020-04-02 20:17:26 +00:00
|
|
|
'logger': logger,
|
2020-04-03 19:32:25 +00:00
|
|
|
'max_filesize': config.config['max_dl_filesize'],
|
|
|
|
'max_downloads': 1,
|
2020-04-07 19:14:53 +00:00
|
|
|
'outtmpl': outpath,
|
2020-04-02 20:17:26 +00:00
|
|
|
}
|
2020-04-03 19:32:25 +00:00
|
|
|
try:
|
2020-04-07 19:14:53 +00:00
|
|
|
with YoutubeDL(options) as ydl:
|
|
|
|
ydl.extract_info(url, download=True)
|
|
|
|
with open(outpath, 'rb') as f:
|
2020-04-03 19:32:25 +00:00
|
|
|
return f.read()
|
2020-04-07 19:14:53 +00:00
|
|
|
except YoutubeDLError as ex:
|
|
|
|
raise errors.ThirdPartyError(
|
|
|
|
'Error downloading video %s (%s)' % (url, ex))
|
2020-06-05 14:02:18 +00:00
|
|
|
except FileNotFoundError:
|
2020-04-03 19:32:25 +00:00
|
|
|
raise errors.ThirdPartyError(
|
2020-04-07 19:14:53 +00:00
|
|
|
'Error downloading video %s (file could not be saved)' % (url))
|