]> jfr.im git - yt-dlp.git/blob - youtube_dl/__init__.py
Merge branch 'subtitles-rework'
[yt-dlp.git] / 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
174 if opts.date is not None:
175 date = DateRange.day(opts.date)
176 else:
177 date = DateRange(opts.dateafter, opts.datebefore)
178
179 # Do not download videos when there are audio-only formats
180 if opts.extractaudio and not opts.keepvideo and opts.format is None:
181 opts.format = 'bestaudio/best'
182
183 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
184 # this was the old behaviour if only --all-sub was given.
185 if opts.allsubtitles and not opts.writeautomaticsub:
186 opts.writesubtitles = True
187
188 if sys.version_info < (3,):
189 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
190 if opts.outtmpl is not None:
191 opts.outtmpl = opts.outtmpl.decode(preferredencoding())
192 outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
193 (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
194 (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
195 (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
196 (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
197 (opts.useid and '%(id)s.%(ext)s') or
198 (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
199 DEFAULT_OUTTMPL)
200 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
201 parser.error('Cannot download a video and extract audio into the same'
202 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
203 ' template'.format(outtmpl))
204
205 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
206 any_printing = opts.print_json
207 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
208
209 # PostProcessors
210 postprocessors = []
211 # Add the metadata pp first, the other pps will copy it
212 if opts.addmetadata:
213 postprocessors.append({'key': 'FFmpegMetadata'})
214 if opts.extractaudio:
215 postprocessors.append({
216 'key': 'FFmpegExtractAudio',
217 'preferredcodec': opts.audioformat,
218 'preferredquality': opts.audioquality,
219 'nopostoverwrites': opts.nopostoverwrites,
220 })
221 if opts.recodevideo:
222 postprocessors.append({
223 'key': 'FFmpegVideoConvertor',
224 'preferedformat': opts.recodevideo,
225 })
226 if opts.embedsubtitles:
227 postprocessors.append({
228 'key': 'FFmpegEmbedSubtitle',
229 })
230 if opts.xattrs:
231 postprocessors.append({'key': 'XAttrMetadata'})
232 if opts.embedthumbnail:
233 if not opts.addmetadata:
234 postprocessors.append({'key': 'FFmpegAudioFix'})
235 postprocessors.append({'key': 'AtomicParsley'})
236 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
237 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
238 if opts.exec_cmd:
239 postprocessors.append({
240 'key': 'ExecAfterDownload',
241 'verboseOutput': opts.verbose,
242 'exec_cmd': opts.exec_cmd,
243 })
244 if opts.xattr_set_filesize:
245 try:
246 import xattr
247 xattr # Confuse flake8
248 except ImportError:
249 parser.error('setting filesize xattr requested but python-xattr is not available')
250 match_filter = (
251 None if opts.match_filter is None
252 else match_filter_func(opts.match_filter))
253
254 ydl_opts = {
255 'usenetrc': opts.usenetrc,
256 'username': opts.username,
257 'password': opts.password,
258 'twofactor': opts.twofactor,
259 'videopassword': opts.videopassword,
260 'quiet': (opts.quiet or any_getting or any_printing),
261 'no_warnings': opts.no_warnings,
262 'forceurl': opts.geturl,
263 'forcetitle': opts.gettitle,
264 'forceid': opts.getid,
265 'forcethumbnail': opts.getthumbnail,
266 'forcedescription': opts.getdescription,
267 'forceduration': opts.getduration,
268 'forcefilename': opts.getfilename,
269 'forceformat': opts.getformat,
270 'forcejson': opts.dumpjson or opts.print_json,
271 'dump_single_json': opts.dump_single_json,
272 'simulate': opts.simulate or any_getting,
273 'skip_download': opts.skip_download,
274 'format': opts.format,
275 'format_limit': opts.format_limit,
276 'listformats': opts.listformats,
277 'outtmpl': outtmpl,
278 'autonumber_size': opts.autonumber_size,
279 'restrictfilenames': opts.restrictfilenames,
280 'ignoreerrors': opts.ignoreerrors,
281 'ratelimit': opts.ratelimit,
282 'nooverwrites': opts.nooverwrites,
283 'retries': opts_retries,
284 'buffersize': opts.buffersize,
285 'noresizebuffer': opts.noresizebuffer,
286 'continuedl': opts.continue_dl,
287 'noprogress': opts.noprogress,
288 'progress_with_newline': opts.progress_with_newline,
289 'playliststart': opts.playliststart,
290 'playlistend': opts.playlistend,
291 'playlistreverse': opts.playlist_reverse,
292 'noplaylist': opts.noplaylist,
293 'logtostderr': opts.outtmpl == '-',
294 'consoletitle': opts.consoletitle,
295 'nopart': opts.nopart,
296 'updatetime': opts.updatetime,
297 'writedescription': opts.writedescription,
298 'writeannotations': opts.writeannotations,
299 'writeinfojson': opts.writeinfojson,
300 'writethumbnail': opts.writethumbnail,
301 'write_all_thumbnails': opts.write_all_thumbnails,
302 'writesubtitles': opts.writesubtitles,
303 'writeautomaticsub': opts.writeautomaticsub,
304 'allsubtitles': opts.allsubtitles,
305 'listsubtitles': opts.listsubtitles,
306 'subtitlesformat': opts.subtitlesformat,
307 'subtitleslangs': opts.subtitleslangs,
308 'matchtitle': decodeOption(opts.matchtitle),
309 'rejecttitle': decodeOption(opts.rejecttitle),
310 'max_downloads': opts.max_downloads,
311 'prefer_free_formats': opts.prefer_free_formats,
312 'verbose': opts.verbose,
313 'dump_intermediate_pages': opts.dump_intermediate_pages,
314 'write_pages': opts.write_pages,
315 'test': opts.test,
316 'keepvideo': opts.keepvideo,
317 'min_filesize': opts.min_filesize,
318 'max_filesize': opts.max_filesize,
319 'min_views': opts.min_views,
320 'max_views': opts.max_views,
321 'daterange': date,
322 'cachedir': opts.cachedir,
323 'youtube_print_sig_code': opts.youtube_print_sig_code,
324 'age_limit': opts.age_limit,
325 'download_archive': download_archive_fn,
326 'cookiefile': opts.cookiefile,
327 'nocheckcertificate': opts.no_check_certificate,
328 'prefer_insecure': opts.prefer_insecure,
329 'proxy': opts.proxy,
330 'socket_timeout': opts.socket_timeout,
331 'bidi_workaround': opts.bidi_workaround,
332 'debug_printtraffic': opts.debug_printtraffic,
333 'prefer_ffmpeg': opts.prefer_ffmpeg,
334 'include_ads': opts.include_ads,
335 'default_search': opts.default_search,
336 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
337 'encoding': opts.encoding,
338 'exec_cmd': opts.exec_cmd,
339 'extract_flat': opts.extract_flat,
340 'merge_output_format': opts.merge_output_format,
341 'postprocessors': postprocessors,
342 'fixup': opts.fixup,
343 'source_address': opts.source_address,
344 'call_home': opts.call_home,
345 'sleep_interval': opts.sleep_interval,
346 'external_downloader': opts.external_downloader,
347 'list_thumbnails': opts.list_thumbnails,
348 'playlist_items': opts.playlist_items,
349 'xattr_set_filesize': opts.xattr_set_filesize,
350 'match_filter': match_filter,
351 'no_color': opts.no_color,
352 'ffmpeg_location': opts.ffmpeg_location,
353 'hls_prefer_native': opts.hls_prefer_native,
354 }
355
356 with YoutubeDL(ydl_opts) as ydl:
357 # Update version
358 if opts.update_self:
359 update_self(ydl.to_screen, opts.verbose)
360
361 # Remove cache dir
362 if opts.rm_cachedir:
363 ydl.cache.remove()
364
365 # Maybe do nothing
366 if (len(all_urls) < 1) and (opts.load_info_filename is None):
367 if opts.update_self or opts.rm_cachedir:
368 sys.exit()
369
370 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
371 parser.error(
372 'You must provide at least one URL.\n'
373 'Type youtube-dl --help to see a list of all options.')
374
375 try:
376 if opts.load_info_filename is not None:
377 retcode = ydl.download_with_info_file(opts.load_info_filename)
378 else:
379 retcode = ydl.download(all_urls)
380 except MaxDownloadsReached:
381 ydl.to_screen('--max-download limit reached, aborting.')
382 retcode = 101
383
384 sys.exit(retcode)
385
386
387 def main(argv=None):
388 try:
389 _real_main(argv)
390 except DownloadError:
391 sys.exit(1)
392 except SameFileError:
393 sys.exit('ERROR: fixed output name but more than one file to download')
394 except KeyboardInterrupt:
395 sys.exit('\nERROR: Interrupted by user')
396
397 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']