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