]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/__init__.py
a9730292cd6801c1bbd7f68b586e288bad7fe21d
[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_shlex_split,
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 ':' not in h:
70 parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
71 key, value = h.split(':', 1)
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 write_string(std_headers['User-Agent'] + '\n', out=sys.stdout)
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(
89 compat_expanduser(opts.batchfile),
90 'r', encoding='utf-8', errors='ignore')
91 batch_urls = read_batch_urls(batchfd)
92 if opts.verbose:
93 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
94 except IOError:
95 sys.exit('ERROR: batch file could not be read')
96 all_urls = batch_urls + args
97 all_urls = [url.strip() for url in all_urls]
98 _enc = preferredencoding()
99 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
100
101 if opts.list_extractors:
102 for ie in list_extractors(opts.age_limit):
103 write_string(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else '') + '\n', out=sys.stdout)
104 matchedUrls = [url for url in all_urls if ie.suitable(url)]
105 for mu in matchedUrls:
106 write_string(' ' + mu + '\n', out=sys.stdout)
107 sys.exit(0)
108 if opts.list_extractor_descriptions:
109 for ie in list_extractors(opts.age_limit):
110 if not ie._WORKING:
111 continue
112 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
113 if desc is False:
114 continue
115 if hasattr(ie, 'SEARCH_KEY'):
116 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
117 _COUNTS = ('', '5', '10', 'all')
118 desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
119 write_string(desc + '\n', out=sys.stdout)
120 sys.exit(0)
121
122 # Conflicting, missing and erroneous options
123 if opts.usenetrc and (opts.username is not None or opts.password is not None):
124 parser.error('using .netrc conflicts with giving username/password')
125 if opts.password is not None and opts.username is None:
126 parser.error('account username missing\n')
127 if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
128 parser.error('using output template conflicts with using title, video ID or auto number')
129 if opts.usetitle and opts.useid:
130 parser.error('using title conflicts with using video ID')
131 if opts.username is not None and opts.password is None:
132 opts.password = compat_getpass('Type account password and press [Return]: ')
133 if opts.ratelimit is not None:
134 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
135 if numeric_limit is None:
136 parser.error('invalid rate limit specified')
137 opts.ratelimit = numeric_limit
138 if opts.min_filesize is not None:
139 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
140 if numeric_limit is None:
141 parser.error('invalid min_filesize specified')
142 opts.min_filesize = numeric_limit
143 if opts.max_filesize is not None:
144 numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
145 if numeric_limit is None:
146 parser.error('invalid max_filesize specified')
147 opts.max_filesize = numeric_limit
148 if opts.sleep_interval is not None:
149 if opts.sleep_interval < 0:
150 parser.error('sleep interval must be positive or 0')
151 if opts.max_sleep_interval is not None:
152 if opts.max_sleep_interval < 0:
153 parser.error('max sleep interval must be positive or 0')
154 if opts.max_sleep_interval < opts.sleep_interval:
155 parser.error('max sleep interval must be greater than or equal to min sleep interval')
156 else:
157 opts.max_sleep_interval = opts.sleep_interval
158
159 def parse_retries(retries):
160 if retries in ('inf', 'infinite'):
161 parsed_retries = float('inf')
162 else:
163 try:
164 parsed_retries = int(retries)
165 except (TypeError, ValueError):
166 parser.error('invalid retry count specified')
167 return parsed_retries
168 if opts.retries is not None:
169 opts.retries = parse_retries(opts.retries)
170 if opts.fragment_retries is not None:
171 opts.fragment_retries = parse_retries(opts.fragment_retries)
172 if opts.buffersize is not None:
173 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
174 if numeric_buffersize is None:
175 parser.error('invalid buffer size specified')
176 opts.buffersize = numeric_buffersize
177 if opts.playliststart <= 0:
178 raise ValueError('Playlist start must be positive')
179 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
180 raise ValueError('Playlist end must be greater than playlist start')
181 if opts.extractaudio:
182 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
183 parser.error('invalid audio format specified')
184 if opts.audioquality:
185 opts.audioquality = opts.audioquality.strip('k').strip('K')
186 if not opts.audioquality.isdigit():
187 parser.error('invalid audio quality specified')
188 if opts.recodevideo is not None:
189 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
190 parser.error('invalid video recode format specified')
191 if opts.convertsubtitles is not None:
192 if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
193 parser.error('invalid subtitle format specified')
194
195 if opts.date is not None:
196 date = DateRange.day(opts.date)
197 else:
198 date = DateRange(opts.dateafter, opts.datebefore)
199
200 # Do not download videos when there are audio-only formats
201 if opts.extractaudio and not opts.keepvideo and opts.format is None:
202 opts.format = 'bestaudio/best'
203
204 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
205 # this was the old behaviour if only --all-sub was given.
206 if opts.allsubtitles and not opts.writeautomaticsub:
207 opts.writesubtitles = True
208
209 outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
210 (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
211 (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
212 (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
213 (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
214 (opts.useid and '%(id)s.%(ext)s') or
215 (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
216 DEFAULT_OUTTMPL)
217 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
218 parser.error('Cannot download a video and extract audio into the same'
219 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
220 ' template'.format(outtmpl))
221
222 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
223 any_printing = opts.print_json
224 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
225
226 # PostProcessors
227 postprocessors = []
228 # Add the metadata pp first, the other pps will copy it
229 if opts.metafromtitle:
230 postprocessors.append({
231 'key': 'MetadataFromTitle',
232 'titleformat': opts.metafromtitle
233 })
234 if opts.addmetadata:
235 postprocessors.append({'key': 'FFmpegMetadata'})
236 if opts.extractaudio:
237 postprocessors.append({
238 'key': 'FFmpegExtractAudio',
239 'preferredcodec': opts.audioformat,
240 'preferredquality': opts.audioquality,
241 'nopostoverwrites': opts.nopostoverwrites,
242 })
243 if opts.recodevideo:
244 postprocessors.append({
245 'key': 'FFmpegVideoConvertor',
246 'preferedformat': opts.recodevideo,
247 })
248 if opts.convertsubtitles:
249 postprocessors.append({
250 'key': 'FFmpegSubtitlesConvertor',
251 'format': opts.convertsubtitles,
252 })
253 if opts.embedsubtitles:
254 postprocessors.append({
255 'key': 'FFmpegEmbedSubtitle',
256 })
257 if opts.xattrs:
258 postprocessors.append({'key': 'XAttrMetadata'})
259 if opts.embedthumbnail:
260 already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
261 postprocessors.append({
262 'key': 'EmbedThumbnail',
263 'already_have_thumbnail': already_have_thumbnail
264 })
265 if not already_have_thumbnail:
266 opts.writethumbnail = True
267 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
268 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
269 if opts.exec_cmd:
270 postprocessors.append({
271 'key': 'ExecAfterDownload',
272 'exec_cmd': opts.exec_cmd,
273 })
274 if opts.xattr_set_filesize:
275 try:
276 import xattr
277 xattr # Confuse flake8
278 except ImportError:
279 parser.error('setting filesize xattr requested but python-xattr is not available')
280 external_downloader_args = None
281 if opts.external_downloader_args:
282 external_downloader_args = compat_shlex_split(opts.external_downloader_args)
283 postprocessor_args = None
284 if opts.postprocessor_args:
285 postprocessor_args = compat_shlex_split(opts.postprocessor_args)
286 match_filter = (
287 None if opts.match_filter is None
288 else match_filter_func(opts.match_filter))
289
290 ydl_opts = {
291 'usenetrc': opts.usenetrc,
292 'username': opts.username,
293 'password': opts.password,
294 'twofactor': opts.twofactor,
295 'videopassword': opts.videopassword,
296 'quiet': (opts.quiet or any_getting or any_printing),
297 'no_warnings': opts.no_warnings,
298 'forceurl': opts.geturl,
299 'forcetitle': opts.gettitle,
300 'forceid': opts.getid,
301 'forcethumbnail': opts.getthumbnail,
302 'forcedescription': opts.getdescription,
303 'forceduration': opts.getduration,
304 'forcefilename': opts.getfilename,
305 'forceformat': opts.getformat,
306 'forcejson': opts.dumpjson or opts.print_json,
307 'dump_single_json': opts.dump_single_json,
308 'simulate': opts.simulate or any_getting,
309 'skip_download': opts.skip_download,
310 'format': opts.format,
311 'listformats': opts.listformats,
312 'outtmpl': outtmpl,
313 'autonumber_size': opts.autonumber_size,
314 'restrictfilenames': opts.restrictfilenames,
315 'ignoreerrors': opts.ignoreerrors,
316 'force_generic_extractor': opts.force_generic_extractor,
317 'ratelimit': opts.ratelimit,
318 'nooverwrites': opts.nooverwrites,
319 'retries': opts.retries,
320 'fragment_retries': opts.fragment_retries,
321 'buffersize': opts.buffersize,
322 'noresizebuffer': opts.noresizebuffer,
323 'continuedl': opts.continue_dl,
324 'noprogress': opts.noprogress,
325 'progress_with_newline': opts.progress_with_newline,
326 'playliststart': opts.playliststart,
327 'playlistend': opts.playlistend,
328 'playlistreverse': opts.playlist_reverse,
329 'noplaylist': opts.noplaylist,
330 'logtostderr': opts.outtmpl == '-',
331 'consoletitle': opts.consoletitle,
332 'nopart': opts.nopart,
333 'updatetime': opts.updatetime,
334 'writedescription': opts.writedescription,
335 'writeannotations': opts.writeannotations,
336 'writeinfojson': opts.writeinfojson,
337 'writethumbnail': opts.writethumbnail,
338 'write_all_thumbnails': opts.write_all_thumbnails,
339 'writesubtitles': opts.writesubtitles,
340 'writeautomaticsub': opts.writeautomaticsub,
341 'allsubtitles': opts.allsubtitles,
342 'listsubtitles': opts.listsubtitles,
343 'subtitlesformat': opts.subtitlesformat,
344 'subtitleslangs': opts.subtitleslangs,
345 'matchtitle': decodeOption(opts.matchtitle),
346 'rejecttitle': decodeOption(opts.rejecttitle),
347 'max_downloads': opts.max_downloads,
348 'prefer_free_formats': opts.prefer_free_formats,
349 'verbose': opts.verbose,
350 'dump_intermediate_pages': opts.dump_intermediate_pages,
351 'write_pages': opts.write_pages,
352 'test': opts.test,
353 'keepvideo': opts.keepvideo,
354 'min_filesize': opts.min_filesize,
355 'max_filesize': opts.max_filesize,
356 'min_views': opts.min_views,
357 'max_views': opts.max_views,
358 'daterange': date,
359 'cachedir': opts.cachedir,
360 'youtube_print_sig_code': opts.youtube_print_sig_code,
361 'age_limit': opts.age_limit,
362 'download_archive': download_archive_fn,
363 'cookiefile': opts.cookiefile,
364 'nocheckcertificate': opts.no_check_certificate,
365 'prefer_insecure': opts.prefer_insecure,
366 'proxy': opts.proxy,
367 'socket_timeout': opts.socket_timeout,
368 'bidi_workaround': opts.bidi_workaround,
369 'debug_printtraffic': opts.debug_printtraffic,
370 'prefer_ffmpeg': opts.prefer_ffmpeg,
371 'include_ads': opts.include_ads,
372 'default_search': opts.default_search,
373 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
374 'encoding': opts.encoding,
375 'extract_flat': opts.extract_flat,
376 'mark_watched': opts.mark_watched,
377 'merge_output_format': opts.merge_output_format,
378 'postprocessors': postprocessors,
379 'fixup': opts.fixup,
380 'source_address': opts.source_address,
381 'call_home': opts.call_home,
382 'sleep_interval': opts.sleep_interval,
383 'max_sleep_interval': opts.max_sleep_interval,
384 'external_downloader': opts.external_downloader,
385 'list_thumbnails': opts.list_thumbnails,
386 'playlist_items': opts.playlist_items,
387 'xattr_set_filesize': opts.xattr_set_filesize,
388 'match_filter': match_filter,
389 'no_color': opts.no_color,
390 'ffmpeg_location': opts.ffmpeg_location,
391 'hls_prefer_native': opts.hls_prefer_native,
392 'hls_use_mpegts': opts.hls_use_mpegts,
393 'external_downloader_args': external_downloader_args,
394 'postprocessor_args': postprocessor_args,
395 'cn_verification_proxy': opts.cn_verification_proxy,
396 'geo_verification_proxy': opts.geo_verification_proxy,
397
398 }
399
400 with YoutubeDL(ydl_opts) as ydl:
401 # Update version
402 if opts.update_self:
403 update_self(ydl.to_screen, opts.verbose, ydl._opener)
404
405 # Remove cache dir
406 if opts.rm_cachedir:
407 ydl.cache.remove()
408
409 # Maybe do nothing
410 if (len(all_urls) < 1) and (opts.load_info_filename is None):
411 if opts.update_self or opts.rm_cachedir:
412 sys.exit()
413
414 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
415 parser.error(
416 'You must provide at least one URL.\n'
417 'Type youtube-dl --help to see a list of all options.')
418
419 try:
420 if opts.load_info_filename is not None:
421 retcode = ydl.download_with_info_file(compat_expanduser(opts.load_info_filename))
422 else:
423 retcode = ydl.download(all_urls)
424 except MaxDownloadsReached:
425 ydl.to_screen('--max-download limit reached, aborting.')
426 retcode = 101
427
428 sys.exit(retcode)
429
430
431 def main(argv=None):
432 try:
433 _real_main(argv)
434 except DownloadError:
435 sys.exit(1)
436 except SameFileError:
437 sys.exit('ERROR: fixed output name but more than one file to download')
438 except KeyboardInterrupt:
439 sys.exit('\nERROR: Interrupted by user')
440
441 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']