]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/__init__.py
Prepare for release.
[youtubedl] / youtube_dl / __init__.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import unicode_literals
5
6 __license__ = 'Public Domain'
7
8 import codecs
9 import io
10 import os
11 import random
12 import sys
13
14
15 from .options import (
16 parseOpts,
17 )
18 from .compat import (
19 compat_expanduser,
20 compat_getpass,
21 compat_print,
22 workaround_optparse_bug9161,
23 )
24 from .utils import (
25 DateRange,
26 decodeOption,
27 DEFAULT_OUTTMPL,
28 DownloadError,
29 match_filter_func,
30 MaxDownloadsReached,
31 preferredencoding,
32 read_batch_urls,
33 SameFileError,
34 setproctitle,
35 std_headers,
36 write_string,
37 )
38 from .update import update_self
39 from .downloader import (
40 FileDownloader,
41 )
42 from .extractor import gen_extractors, list_extractors
43 from .YoutubeDL import YoutubeDL
44
45
46 def _real_main(argv=None):
47 # Compatibility fixes for Windows
48 if sys.platform == 'win32':
49 # https://github.com/rg3/youtube-dl/issues/820
50 codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
51
52 workaround_optparse_bug9161()
53
54 setproctitle('youtube-dl')
55
56 parser, opts, args = parseOpts(argv)
57
58 # Set user agent
59 if opts.user_agent is not None:
60 std_headers['User-Agent'] = opts.user_agent
61
62 # Set referer
63 if opts.referer is not None:
64 std_headers['Referer'] = opts.referer
65
66 # Custom HTTP headers
67 if opts.headers is not None:
68 for h in opts.headers:
69 if h.find(':', 1) < 0:
70 parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
71 key, value = h.split(':', 2)
72 if opts.verbose:
73 write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
74 std_headers[key] = value
75
76 # Dump user agent
77 if opts.dump_user_agent:
78 compat_print(std_headers['User-Agent'])
79 sys.exit(0)
80
81 # Batch file verification
82 batch_urls = []
83 if opts.batchfile is not None:
84 try:
85 if opts.batchfile == '-':
86 batchfd = sys.stdin
87 else:
88 batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
89 batch_urls = read_batch_urls(batchfd)
90 if opts.verbose:
91 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
92 except IOError:
93 sys.exit('ERROR: batch file could not be read')
94 all_urls = batch_urls + args
95 all_urls = [url.strip() for url in all_urls]
96 _enc = preferredencoding()
97 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
98
99 if opts.list_extractors:
100 for ie in list_extractors(opts.age_limit):
101 compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
102 matchedUrls = [url for url in all_urls if ie.suitable(url)]
103 for mu in matchedUrls:
104 compat_print(' ' + mu)
105 sys.exit(0)
106 if opts.list_extractor_descriptions:
107 for ie in list_extractors(opts.age_limit):
108 if not ie._WORKING:
109 continue
110 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
111 if desc is False:
112 continue
113 if hasattr(ie, 'SEARCH_KEY'):
114 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
115 _COUNTS = ('', '5', '10', 'all')
116 desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
117 compat_print(desc)
118 sys.exit(0)
119
120 # Conflicting, missing and erroneous options
121 if opts.usenetrc and (opts.username is not None or opts.password is not None):
122 parser.error('using .netrc conflicts with giving username/password')
123 if opts.password is not None and opts.username is None:
124 parser.error('account username missing\n')
125 if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
126 parser.error('using output template conflicts with using title, video ID or auto number')
127 if opts.usetitle and opts.useid:
128 parser.error('using title conflicts with using video ID')
129 if opts.username is not None and opts.password is None:
130 opts.password = compat_getpass('Type account password and press [Return]: ')
131 if opts.ratelimit is not None:
132 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
133 if numeric_limit is None:
134 parser.error('invalid rate limit specified')
135 opts.ratelimit = numeric_limit
136 if opts.min_filesize is not None:
137 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
138 if numeric_limit is None:
139 parser.error('invalid min_filesize specified')
140 opts.min_filesize = numeric_limit
141 if opts.max_filesize is not None:
142 numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
143 if numeric_limit is None:
144 parser.error('invalid max_filesize specified')
145 opts.max_filesize = numeric_limit
146 if opts.retries is not None:
147 if opts.retries in ('inf', 'infinite'):
148 opts_retries = float('inf')
149 else:
150 try:
151 opts_retries = int(opts.retries)
152 except (TypeError, ValueError):
153 parser.error('invalid retry count specified')
154 if opts.buffersize is not None:
155 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
156 if numeric_buffersize is None:
157 parser.error('invalid buffer size specified')
158 opts.buffersize = numeric_buffersize
159 if opts.playliststart <= 0:
160 raise ValueError('Playlist start must be positive')
161 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
162 raise ValueError('Playlist end must be greater than playlist start')
163 if opts.extractaudio:
164 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
165 parser.error('invalid audio format specified')
166 if opts.audioquality:
167 opts.audioquality = opts.audioquality.strip('k').strip('K')
168 if not opts.audioquality.isdigit():
169 parser.error('invalid audio quality specified')
170 if opts.recodevideo is not None:
171 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
172 parser.error('invalid video recode format specified')
173 if opts.convertsubtitles is not None:
174 if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
175 parser.error('invalid subtitle format specified')
176
177 if opts.date is not None:
178 date = DateRange.day(opts.date)
179 else:
180 date = DateRange(opts.dateafter, opts.datebefore)
181
182 # Do not download videos when there are audio-only formats
183 if opts.extractaudio and not opts.keepvideo and opts.format is None:
184 opts.format = 'bestaudio/best'
185
186 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
187 # this was the old behaviour if only --all-sub was given.
188 if opts.allsubtitles and not opts.writeautomaticsub:
189 opts.writesubtitles = True
190
191 if sys.version_info < (3,):
192 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
193 if opts.outtmpl is not None:
194 opts.outtmpl = opts.outtmpl.decode(preferredencoding())
195 outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
196 (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
197 (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
198 (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
199 (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
200 (opts.useid and '%(id)s.%(ext)s') or
201 (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
202 DEFAULT_OUTTMPL)
203 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
204 parser.error('Cannot download a video and extract audio into the same'
205 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
206 ' template'.format(outtmpl))
207
208 any_getting = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson or opts.dump_single_json
209 any_printing = opts.print_json
210 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
211
212 # PostProcessors
213 postprocessors = []
214 # Add the metadata pp first, the other pps will copy it
215 if opts.addmetadata:
216 postprocessors.append({'key': 'FFmpegMetadata'})
217 if opts.extractaudio:
218 postprocessors.append({
219 'key': 'FFmpegExtractAudio',
220 'preferredcodec': opts.audioformat,
221 'preferredquality': opts.audioquality,
222 'nopostoverwrites': opts.nopostoverwrites,
223 })
224 if opts.recodevideo:
225 postprocessors.append({
226 'key': 'FFmpegVideoConvertor',
227 'preferedformat': opts.recodevideo,
228 })
229 if opts.convertsubtitles:
230 postprocessors.append({
231 'key': 'FFmpegSubtitlesConvertor',
232 'format': opts.convertsubtitles,
233 })
234 if opts.embedsubtitles:
235 postprocessors.append({
236 'key': 'FFmpegEmbedSubtitle',
237 })
238 if opts.xattrs:
239 postprocessors.append({'key': 'XAttrMetadata'})
240 if opts.embedthumbnail:
241 if not opts.addmetadata:
242 postprocessors.append({'key': 'FFmpegAudioFix'})
243 postprocessors.append({'key': 'AtomicParsley'})
244 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
245 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
246 if opts.exec_cmd:
247 postprocessors.append({
248 'key': 'ExecAfterDownload',
249 'verboseOutput': opts.verbose,
250 'exec_cmd': opts.exec_cmd,
251 })
252 if opts.xattr_set_filesize:
253 try:
254 import xattr
255 xattr # Confuse flake8
256 except ImportError:
257 parser.error('setting filesize xattr requested but python-xattr is not available')
258 match_filter = (
259 None if opts.match_filter is None
260 else match_filter_func(opts.match_filter))
261
262 ydl_opts = {
263 'usenetrc': opts.usenetrc,
264 'username': opts.username,
265 'password': opts.password,
266 'twofactor': opts.twofactor,
267 'videopassword': opts.videopassword,
268 'quiet': (opts.quiet or any_getting or any_printing),
269 'no_warnings': opts.no_warnings,
270 'forceurl': opts.geturl,
271 'forcetitle': opts.gettitle,
272 'forceid': opts.getid,
273 'forcethumbnail': opts.getthumbnail,
274 'forcedescription': opts.getdescription,
275 'forceduration': opts.getduration,
276 'forcefilename': opts.getfilename,
277 'forceformat': opts.getformat,
278 'forcejson': opts.dumpjson or opts.print_json,
279 'dump_single_json': opts.dump_single_json,
280 'simulate': opts.simulate or any_getting,
281 'skip_download': opts.skip_download,
282 'format': opts.format,
283 'format_limit': opts.format_limit,
284 'listformats': opts.listformats,
285 'outtmpl': outtmpl,
286 'autonumber_size': opts.autonumber_size,
287 'restrictfilenames': opts.restrictfilenames,
288 'ignoreerrors': opts.ignoreerrors,
289 'ratelimit': opts.ratelimit,
290 'nooverwrites': opts.nooverwrites,
291 'retries': opts_retries,
292 'buffersize': opts.buffersize,
293 'noresizebuffer': opts.noresizebuffer,
294 'continuedl': opts.continue_dl,
295 'noprogress': opts.noprogress,
296 'progress_with_newline': opts.progress_with_newline,
297 'playliststart': opts.playliststart,
298 'playlistend': opts.playlistend,
299 'playlistreverse': opts.playlist_reverse,
300 'noplaylist': opts.noplaylist,
301 'logtostderr': opts.outtmpl == '-',
302 'consoletitle': opts.consoletitle,
303 'nopart': opts.nopart,
304 'updatetime': opts.updatetime,
305 'writedescription': opts.writedescription,
306 'writeannotations': opts.writeannotations,
307 'writeinfojson': opts.writeinfojson,
308 'writethumbnail': opts.writethumbnail,
309 'write_all_thumbnails': opts.write_all_thumbnails,
310 'writesubtitles': opts.writesubtitles,
311 'writeautomaticsub': opts.writeautomaticsub,
312 'allsubtitles': opts.allsubtitles,
313 'listsubtitles': opts.listsubtitles,
314 'subtitlesformat': opts.subtitlesformat,
315 'subtitleslangs': opts.subtitleslangs,
316 'matchtitle': decodeOption(opts.matchtitle),
317 'rejecttitle': decodeOption(opts.rejecttitle),
318 'max_downloads': opts.max_downloads,
319 'prefer_free_formats': opts.prefer_free_formats,
320 'verbose': opts.verbose,
321 'dump_intermediate_pages': opts.dump_intermediate_pages,
322 'write_pages': opts.write_pages,
323 'test': opts.test,
324 'keepvideo': opts.keepvideo,
325 'min_filesize': opts.min_filesize,
326 'max_filesize': opts.max_filesize,
327 'min_views': opts.min_views,
328 'max_views': opts.max_views,
329 'daterange': date,
330 'cachedir': opts.cachedir,
331 'youtube_print_sig_code': opts.youtube_print_sig_code,
332 'age_limit': opts.age_limit,
333 'download_archive': download_archive_fn,
334 'cookiefile': opts.cookiefile,
335 'nocheckcertificate': opts.no_check_certificate,
336 'prefer_insecure': opts.prefer_insecure,
337 'proxy': opts.proxy,
338 'socket_timeout': opts.socket_timeout,
339 'bidi_workaround': opts.bidi_workaround,
340 'debug_printtraffic': opts.debug_printtraffic,
341 'prefer_ffmpeg': opts.prefer_ffmpeg,
342 'include_ads': opts.include_ads,
343 'default_search': opts.default_search,
344 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
345 'encoding': opts.encoding,
346 'exec_cmd': opts.exec_cmd,
347 'extract_flat': opts.extract_flat,
348 'merge_output_format': opts.merge_output_format,
349 'postprocessors': postprocessors,
350 'fixup': opts.fixup,
351 'source_address': opts.source_address,
352 'call_home': opts.call_home,
353 'sleep_interval': opts.sleep_interval,
354 'external_downloader': opts.external_downloader,
355 'list_thumbnails': opts.list_thumbnails,
356 'playlist_items': opts.playlist_items,
357 'xattr_set_filesize': opts.xattr_set_filesize,
358 'match_filter': match_filter,
359 'no_color': opts.no_color,
360 'ffmpeg_location': opts.ffmpeg_location,
361 'hls_prefer_native': opts.hls_prefer_native,
362 }
363
364 with YoutubeDL(ydl_opts) as ydl:
365 # Update version
366 if opts.update_self:
367 update_self(ydl.to_screen, opts.verbose)
368
369 # Remove cache dir
370 if opts.rm_cachedir:
371 ydl.cache.remove()
372
373 # Maybe do nothing
374 if (len(all_urls) < 1) and (opts.load_info_filename is None):
375 if opts.update_self or opts.rm_cachedir:
376 sys.exit()
377
378 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
379 parser.error(
380 'You must provide at least one URL.\n'
381 'Type youtube-dl --help to see a list of all options.')
382
383 try:
384 if opts.load_info_filename is not None:
385 retcode = ydl.download_with_info_file(opts.load_info_filename)
386 else:
387 retcode = ydl.download(all_urls)
388 except MaxDownloadsReached:
389 ydl.to_screen('--max-download limit reached, aborting.')
390 retcode = 101
391
392 sys.exit(retcode)
393
394
395 def main(argv=None):
396 try:
397 _real_main(argv)
398 except DownloadError:
399 sys.exit(1)
400 except SameFileError:
401 sys.exit('ERROR: fixed output name but more than one file to download')
402 except KeyboardInterrupt:
403 sys.exit('\nERROR: Interrupted by user')
404
405 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']