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