Introduce --skip-unavailable-fragments
[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_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         'skip_unavailable_fragments': opts.skip_unavailable_fragments,
322         'buffersize': opts.buffersize,
323         'noresizebuffer': opts.noresizebuffer,
324         'continuedl': opts.continue_dl,
325         'noprogress': opts.noprogress,
326         'progress_with_newline': opts.progress_with_newline,
327         'playliststart': opts.playliststart,
328         'playlistend': opts.playlistend,
329         'playlistreverse': opts.playlist_reverse,
330         'noplaylist': opts.noplaylist,
331         'logtostderr': opts.outtmpl == '-',
332         'consoletitle': opts.consoletitle,
333         'nopart': opts.nopart,
334         'updatetime': opts.updatetime,
335         'writedescription': opts.writedescription,
336         'writeannotations': opts.writeannotations,
337         'writeinfojson': opts.writeinfojson,
338         'writethumbnail': opts.writethumbnail,
339         'write_all_thumbnails': opts.write_all_thumbnails,
340         'writesubtitles': opts.writesubtitles,
341         'writeautomaticsub': opts.writeautomaticsub,
342         'allsubtitles': opts.allsubtitles,
343         'listsubtitles': opts.listsubtitles,
344         'subtitlesformat': opts.subtitlesformat,
345         'subtitleslangs': opts.subtitleslangs,
346         'matchtitle': decodeOption(opts.matchtitle),
347         'rejecttitle': decodeOption(opts.rejecttitle),
348         'max_downloads': opts.max_downloads,
349         'prefer_free_formats': opts.prefer_free_formats,
350         'verbose': opts.verbose,
351         'dump_intermediate_pages': opts.dump_intermediate_pages,
352         'write_pages': opts.write_pages,
353         'test': opts.test,
354         'keepvideo': opts.keepvideo,
355         'min_filesize': opts.min_filesize,
356         'max_filesize': opts.max_filesize,
357         'min_views': opts.min_views,
358         'max_views': opts.max_views,
359         'daterange': date,
360         'cachedir': opts.cachedir,
361         'youtube_print_sig_code': opts.youtube_print_sig_code,
362         'age_limit': opts.age_limit,
363         'download_archive': download_archive_fn,
364         'cookiefile': opts.cookiefile,
365         'nocheckcertificate': opts.no_check_certificate,
366         'prefer_insecure': opts.prefer_insecure,
367         'proxy': opts.proxy,
368         'socket_timeout': opts.socket_timeout,
369         'bidi_workaround': opts.bidi_workaround,
370         'debug_printtraffic': opts.debug_printtraffic,
371         'prefer_ffmpeg': opts.prefer_ffmpeg,
372         'include_ads': opts.include_ads,
373         'default_search': opts.default_search,
374         'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
375         'encoding': opts.encoding,
376         'extract_flat': opts.extract_flat,
377         'mark_watched': opts.mark_watched,
378         'merge_output_format': opts.merge_output_format,
379         'postprocessors': postprocessors,
380         'fixup': opts.fixup,
381         'source_address': opts.source_address,
382         'call_home': opts.call_home,
383         'sleep_interval': opts.sleep_interval,
384         'max_sleep_interval': opts.max_sleep_interval,
385         'external_downloader': opts.external_downloader,
386         'list_thumbnails': opts.list_thumbnails,
387         'playlist_items': opts.playlist_items,
388         'xattr_set_filesize': opts.xattr_set_filesize,
389         'match_filter': match_filter,
390         'no_color': opts.no_color,
391         'ffmpeg_location': opts.ffmpeg_location,
392         'hls_prefer_native': opts.hls_prefer_native,
393         'hls_use_mpegts': opts.hls_use_mpegts,
394         'external_downloader_args': external_downloader_args,
395         'postprocessor_args': postprocessor_args,
396         'cn_verification_proxy': opts.cn_verification_proxy,
397         'geo_verification_proxy': opts.geo_verification_proxy,
398
399     }
400
401     with YoutubeDL(ydl_opts) as ydl:
402         # Update version
403         if opts.update_self:
404             update_self(ydl.to_screen, opts.verbose, ydl._opener)
405
406         # Remove cache dir
407         if opts.rm_cachedir:
408             ydl.cache.remove()
409
410         # Maybe do nothing
411         if (len(all_urls) < 1) and (opts.load_info_filename is None):
412             if opts.update_self or opts.rm_cachedir:
413                 sys.exit()
414
415             ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
416             parser.error(
417                 'You must provide at least one URL.\n'
418                 'Type youtube-dl --help to see a list of all options.')
419
420         try:
421             if opts.load_info_filename is not None:
422                 retcode = ydl.download_with_info_file(compat_expanduser(opts.load_info_filename))
423             else:
424                 retcode = ydl.download(all_urls)
425         except MaxDownloadsReached:
426             ydl.to_screen('--max-download limit reached, aborting.')
427             retcode = 101
428
429     sys.exit(retcode)
430
431
432 def main(argv=None):
433     try:
434         _real_main(argv)
435     except DownloadError:
436         sys.exit(1)
437     except SameFileError:
438         sys.exit('ERROR: fixed output name but more than one file to download')
439     except KeyboardInterrupt:
440         sys.exit('\nERROR: Interrupted by user')
441
442 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']