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