Repository navigation
Expand file tree
/
Copy pathyoutube.py
More file actions
85 lines (66 loc) · 2.05 KB
/
Copy pathyoutube.py
File metadata and controls
85 lines (66 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import youtube_dl
from lib.exceptions import VideoTooLong, DownError
import logger
output = []
class Logger(object):
def debug(self, msg):
output.append(msg)
def warning(self, msg):
pass
def error(self, msg):
output.append(msg)
normal_options = {
'format': 'bestaudio/best',
'logger': Logger(),
'forcethumbnail': True,
'forcetitle': True,
'quite': True,
'gettitle': True,
'outtmpl': '%(id)s.v',
'prefer_ffmpeg': True,
'audioformat': 'wav',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'wav'
}]
}
validate_opts = {
'simulate': True,
'logger': Logger(),
'forceduration': True
}
class Downloader:
def __init__(self):
self.__youtube_id = None
def start(self, youtube_id):
logger.log('Start downloading %s' % youtube_id)
self.__youtube_id = youtube_id
if self.__validate():
self.__download(normal_options)
path_to_wave = youtube_id + '.wav'
title = output[4]
thumbnail = output[5].replace('maxresdefault', 'hqdefault')
return (path_to_wave, thumbnail, title)
def __validate(self):
self.__download(validate_opts)
duration = output[-1]
time_parts = str.split(str(duration), ':')
time_parts_len = len(time_parts)
# if 3 then it's over an hour
if time_parts_len == 1 or (time_parts_len == 2 and int(time_parts[0]) <= 25):
output[:] = []
return True
logger.log('Error video too long %s' % self.__youtube_id)
raise VideoTooLong
def __download(self, options):
with youtube_dl.YoutubeDL(options) as ydl:
try:
ydl.download(["http://www.youtube.com/watch?v=%s" %
self.__youtube_id])
except youtube_dl.utils.DownloadError as e:
raise DownError(e)
if __name__ == "__main__":
import sys
youtube_id = sys.argv[1]
dl = Downloader()
print dl.start(youtube_id)