]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/__init__.py
debian/control: Add B-D on pandoc and zip. Closes: #828905.
[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
149 def parse_retries(retries):
150 if retries in ('inf', 'infinite'):
151 parsed_retries = float('inf')
152 else:
153 try:
154 parsed_retries = int(retries)
155 except (TypeError, ValueError):
156 parser.error('invalid retry count specified')
157 return parsed_retries
158 if opts.retries is not None:
159 opts.retries = parse_retries(opts.retries)
160 if opts.fragment_retries is not None:
161 opts.fragment_retries = parse_retries(opts.fragment_retries)
162 if opts.buffersize is not None:
163 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
164 if numeric_buffersize is None:
165 parser.error('invalid buffer size specified')
166 opts.buffersize = numeric_buffersize
167 if opts.playliststart <= 0:
168 raise ValueError('Playlist start must be positive')
169 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
170 raise ValueError('Playlist end must be greater than playlist start')
171 if opts.extractaudio:
172 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
173 parser.error('invalid audio format specified')
174 if opts.audioquality:
175 opts.audioquality = opts.audioquality.strip('k').strip('K')
176 if not opts.audioquality.isdigit():
177 parser.error('invalid audio quality specified')
178 if opts.recodevideo is not None:
179 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv', 'avi']:
180 parser.error('invalid video recode format specified')
181 if opts.convertsubtitles is not None:
182 if opts.convertsubtitles not in ['srt', 'vtt', 'ass']:
183 parser.error('invalid subtitle format specified')
184
185 if opts.date is not None:
186 date = DateRange.day(opts.date)
187 else:
188 date = DateRange(opts.dateafter, opts.datebefore)
189
190 # Do not download videos when there are audio-only formats
191 if opts.extractaudio and not opts.keepvideo and opts.format is None:
192 opts.format = 'bestaudio/best'
193
194 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
195 # this was the old behaviour if only --all-sub was given.
196 if opts.allsubtitles and not opts.writeautomaticsub:
197 opts.writesubtitles = True
198
199 outtmpl = ((opts.outtmpl is not None and opts.outtmpl) or
200 (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s') or
201 (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s') or
202 (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s') or
203 (opts.usetitle and '%(title)s-%(id)s.%(ext)s') or
204 (opts.useid and '%(id)s.%(ext)s') or
205 (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s') or
206 DEFAULT_OUTTMPL)
207 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
208 parser.error('Cannot download a video and extract audio into the same'
209 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
210 ' template'.format(outtmpl))
211
212 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
213 any_printing = opts.print_json
214 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
215
216 # PostProcessors
217 postprocessors = []
218 # Add the metadata pp first, the other pps will copy it
219 if opts.metafromtitle:
220 postprocessors.append({
221 'key': 'MetadataFromTitle',
222 'titleformat': opts.metafromtitle
223 })
224 if opts.addmetadata:
225 postprocessors.append({'key': 'FFmpegMetadata'})
226 if opts.extractaudio:
227 postprocessors.append({
228 'key': 'FFmpegExtractAudio',
229 'preferredcodec': opts.audioformat,
230 'preferredquality': opts.audioquality,
231 'nopostoverwrites': opts.nopostoverwrites,
232 })
233 if opts.recodevideo:
234 postprocessors.append({
235 'key': 'FFmpegVideoConvertor',
236 'preferedformat': opts.recodevideo,
237 })
238 if opts.convertsubtitles:
239 postprocessors.append({
240 'key': 'FFmpegSubtitlesConvertor',
241 'format': opts.convertsubtitles,
242 })
243 if opts.embedsubtitles:
244 postprocessors.append({
245 'key': 'FFmpegEmbedSubtitle',
246 })
247 if opts.xattrs:
248 postprocessors.append({'key': 'XAttrMetadata'})
249 if opts.embedthumbnail:
250 already_have_thumbnail = opts.writethumbnail or opts.write_all_thumbnails
251 postprocessors.append({
252 'key': 'EmbedThumbnail',
253 'already_have_thumbnail': already_have_thumbnail
254 })
255 if not already_have_thumbnail:
256 opts.writethumbnail = True
257 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
258 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
259 if opts.exec_cmd:
260 postprocessors.append({
261 'key': 'ExecAfterDownload',
262 'exec_cmd': opts.exec_cmd,
263 })
264 if opts.xattr_set_filesize:
265 try:
266 import xattr
267 xattr # Confuse flake8
268 except ImportError:
269 parser.error('setting filesize xattr requested but python-xattr is not available')
270 external_downloader_args = None
271 if opts.external_downloader_args:
272 external_downloader_args = compat_shlex_split(opts.external_downloader_args)
273 postprocessor_args = None
274 if opts.postprocessor_args:
275 postprocessor_args = compat_shlex_split(opts.postprocessor_args)
276 match_filter = (
277 None if opts.match_filter is None
278 else match_filter_func(opts.match_filter))
279
280 ydl_opts = {
281 'usenetrc': opts.usenetrc,
282 'username': opts.username,
283 'password': opts.password,
284 'twofactor': opts.twofactor,
285 'videopassword': opts.videopassword,
286 'quiet': (opts.quiet or any_getting or any_printing),
287 'no_warnings': opts.no_warnings,
288 'forceurl': opts.geturl,
289 'forcetitle': opts.gettitle,
290 'forceid': opts.getid,
291 'forcethumbnail': opts.getthumbnail,
292 'forcedescription': opts.getdescription,
293 'forceduration': opts.getduration,
294 'forcefilename': opts.getfilename,
295 'forceformat': opts.getformat,
296 'forcejson': opts.dumpjson or opts.print_json,
297 'dump_single_json': opts.dump_single_json,
298 'simulate': opts.simulate or any_getting,
299 'skip_download': opts.skip_download,
300 'format': opts.format,
301 'listformats': opts.listformats,
302 'outtmpl': outtmpl,
303 'autonumber_size': opts.autonumber_size,
304 'restrictfilenames': opts.restrictfilenames,
305 'ignoreerrors': opts.ignoreerrors,
306 'force_generic_extractor': opts.force_generic_extractor,
307 'ratelimit': opts.ratelimit,
308 'nooverwrites': opts.nooverwrites,
309 'retries': opts.retries,
310 'fragment_retries': opts.fragment_retries,
311 'buffersize': opts.buffersize,
312 'noresizebuffer': opts.noresizebuffer,
313 'continuedl': opts.continue_dl,
314 'noprogress': opts.noprogress,
315 'progress_with_newline': opts.progress_with_newline,
316 'playliststart': opts.playliststart,
317 'playlistend': opts.playlistend,
318 'playlistreverse': opts.playlist_reverse,
319 'noplaylist': opts.noplaylist,
320 'logtostderr': opts.outtmpl == '-',
321 'consoletitle': opts.consoletitle,
322 'nopart': opts.nopart,
323 'updatetime': opts.updatetime,
324 'writedescription': opts.writedescription,
325 'writeannotations': opts.writeannotations,
326 'writeinfojson': opts.writeinfojson,
327 'writethumbnail': opts.writethumbnail,
328 'write_all_thumbnails': opts.write_all_thumbnails,
329 'writesubtitles': opts.writesubtitles,
330 'writeautomaticsub': opts.writeautomaticsub,
331 'allsubtitles': opts.allsubtitles,
332 'listsubtitles': opts.listsubtitles,
333 'subtitlesformat': opts.subtitlesformat,
334 'subtitleslangs': opts.subtitleslangs,
335 'matchtitle': decodeOption(opts.matchtitle),
336 'rejecttitle': decodeOption(opts.rejecttitle),
337 'max_downloads': opts.max_downloads,
338 'prefer_free_formats': opts.prefer_free_formats,
339 'verbose': opts.verbose,
340 'dump_intermediate_pages': opts.dump_intermediate_pages,
341 'write_pages': opts.write_pages,
342 'test': opts.test,
343 'keepvideo': opts.keepvideo,
344 'min_filesize': opts.min_filesize,
345 'max_filesize': opts.max_filesize,
346 'min_views': opts.min_views,
347 'max_views': opts.max_views,
348 'daterange': date,
349 'cachedir': opts.cachedir,
350 'youtube_print_sig_code': opts.youtube_print_sig_code,
351 'age_limit': opts.age_limit,
352 'download_archive': download_archive_fn,
353 'cookiefile': opts.cookiefile,
354 'nocheckcertificate': opts.no_check_certificate,
355 'prefer_insecure': opts.prefer_insecure,
356 'proxy': opts.proxy,
357 'socket_timeout': opts.socket_timeout,
358 'bidi_workaround': opts.bidi_workaround,
359 'debug_printtraffic': opts.debug_printtraffic,
360 'prefer_ffmpeg': opts.prefer_ffmpeg,
361 'include_ads': opts.include_ads,
362 'default_search': opts.default_search,
363 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
364 'encoding': opts.encoding,
365 'extract_flat': opts.extract_flat,
366 'mark_watched': opts.mark_watched,
367 'merge_output_format': opts.merge_output_format,
368 'postprocessors': postprocessors,
369 'fixup': opts.fixup,
370 'source_address': opts.source_address,
371 'call_home': opts.call_home,
372 'sleep_interval': opts.sleep_interval,
373 'external_downloader': opts.external_downloader,
374 'list_thumbnails': opts.list_thumbnails,
375 'playlist_items': opts.playlist_items,
376 'xattr_set_filesize': opts.xattr_set_filesize,
377 'match_filter': match_filter,
378 'no_color': opts.no_color,
379 'ffmpeg_location': opts.ffmpeg_location,
380 'hls_prefer_native': opts.hls_prefer_native,
381 'hls_use_mpegts': opts.hls_use_mpegts,
382 'external_downloader_args': external_downloader_args,
383 'postprocessor_args': postprocessor_args,
384 'cn_verification_proxy': opts.cn_verification_proxy,
385 }
386
387 with YoutubeDL(ydl_opts) as ydl:
388 # Update version
389 if opts.update_self:
390 update_self(ydl.to_screen, opts.verbose, ydl._opener)
391
392 # Remove cache dir
393 if opts.rm_cachedir:
394 ydl.cache.remove()
395
396 # Maybe do nothing
397 if (len(all_urls) < 1) and (opts.load_info_filename is None):
398 if opts.update_self or opts.rm_cachedir:
399 sys.exit()
400
401 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
402 parser.error(
403 'You must provide at least one URL.\n'
404 'Type youtube-dl --help to see a list of all options.')
405
406 try:
407 if opts.load_info_filename is not None:
408 retcode = ydl.download_with_info_file(compat_expanduser(opts.load_info_filename))
409 else:
410 retcode = ydl.download(all_urls)
411 except MaxDownloadsReached:
412 ydl.to_screen('--max-download limit reached, aborting.')
413 retcode = 101
414
415 sys.exit(retcode)
416
417
418 def main(argv=None):
419 try:
420 _real_main(argv)
421 except DownloadError:
422 sys.exit(1)
423 except SameFileError:
424 sys.exit('ERROR: fixed output name but more than one file to download')
425 except KeyboardInterrupt:
426 sys.exit('\nERROR: Interrupted by user')
427
428 __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']