]> jfr.im git - yt-dlp.git/blame - youtube_dl/__init__.py
[gameone] Modernize
[yt-dlp.git] / youtube_dl / __init__.py
CommitLineData
235b3ba4
PH
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
a4bc4336
PH
4from __future__ import unicode_literals
5
235b3ba4 6__license__ = 'Public Domain'
235b3ba4 7
0d94f247 8import codecs
8f563f32 9import io
235b3ba4 10import os
0f818663 11import random
235b3ba4 12import sys
235b3ba4 13
c496ca96 14
2daabe49
PH
15from .options import (
16 parseOpts,
17)
8c25f81b 18from .compat import (
4644ac55 19 compat_expanduser,
e68301af 20 compat_getpass,
a4fd0415 21 compat_print,
e07e9313 22 workaround_optparse_bug9161,
8c25f81b
PH
23)
24from .utils import (
a4fd0415 25 DateRange,
acd69589 26 DEFAULT_OUTTMPL,
a4fd0415 27 decodeOption,
a4fd0415 28 DownloadError,
a4fd0415 29 MaxDownloadsReached,
a4fd0415 30 preferredencoding,
62e609ab 31 read_batch_urls,
a4fd0415 32 SameFileError,
e3946f98 33 setproctitle,
a4fd0415
PH
34 std_headers,
35 write_string,
a4fd0415 36)
d5ed35b6 37from .update import update_self
92a86f4c 38from .downloader import (
a4fd0415
PH
39 FileDownloader,
40)
05900629 41from .extractor import list_extractors
8222d8de 42from .YoutubeDL import YoutubeDL
a4fd0415 43
235b3ba4 44
b8ad4f02 45def _real_main(argv=None):
0d94f247
PH
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
e07e9313
PH
51 workaround_optparse_bug9161()
52
a4bc4336 53 setproctitle('youtube-dl')
e3946f98 54
b8ad4f02 55 parser, opts, args = parseOpts(argv)
59ae15a5 56
59ae15a5
PH
57 # Set user agent
58 if opts.user_agent is not None:
59 std_headers['User-Agent'] = opts.user_agent
1865ed31 60
28535652
BH
61 # Set referer
62 if opts.referer is not None:
63 std_headers['Referer'] = opts.referer
59ae15a5 64
410afb20
AA
65 # Custom HTTP headers
66 if opts.headers is not None:
67 for h in opts.headers:
68 if h.find(':', 1) < 0:
8bcc8756 69 parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
410afb20
AA
70 key, value = h.split(':', 2)
71 if opts.verbose:
8bcc8756 72 write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
410afb20
AA
73 std_headers[key] = value
74
59ae15a5
PH
75 # Dump user agent
76 if opts.dump_user_agent:
93eb15c5 77 compat_print(std_headers['User-Agent'])
59ae15a5
PH
78 sys.exit(0)
79
80 # Batch file verification
62e609ab 81 batch_urls = []
59ae15a5
PH
82 if opts.batchfile is not None:
83 try:
84 if opts.batchfile == '-':
85 batchfd = sys.stdin
86 else:
62e609ab
PH
87 batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
88 batch_urls = read_batch_urls(batchfd)
05afc96b 89 if opts.verbose:
a4bc4336 90 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
59ae15a5 91 except IOError:
a4bc4336 92 sys.exit('ERROR: batch file could not be read')
62e609ab 93 all_urls = batch_urls + args
59ae15a5 94 all_urls = [url.strip() for url in all_urls]
c774b3c6 95 _enc = preferredencoding()
41292a38 96 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
59ae15a5 97
59ae15a5 98 if opts.list_extractors:
05900629 99 for ie in list_extractors(opts.age_limit):
93eb15c5 100 compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
1a2c3c0f 101 matchedUrls = [url for url in all_urls if ie.suitable(url)]
59ae15a5 102 for mu in matchedUrls:
a4bc4336 103 compat_print(' ' + mu)
59ae15a5 104 sys.exit(0)
0f818663 105 if opts.list_extractor_descriptions:
05900629 106 for ie in list_extractors(opts.age_limit):
0f818663
PH
107 if not ie._WORKING:
108 continue
109 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
15870e90
PH
110 if desc is False:
111 continue
0f818663 112 if hasattr(ie, 'SEARCH_KEY'):
50a0f6df 113 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
a4bc4336
PH
114 _COUNTS = ('', '5', '10', 'all')
115 desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
0f818663
PH
116 compat_print(desc)
117 sys.exit(0)
118
59ae15a5
PH
119 # Conflicting, missing and erroneous options
120 if opts.usenetrc and (opts.username is not None or opts.password is not None):
a4bc4336 121 parser.error('using .netrc conflicts with giving username/password')
59ae15a5 122 if opts.password is not None and opts.username is None:
a4bc4336 123 parser.error('account username missing\n')
59ae15a5 124 if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
a4bc4336 125 parser.error('using output template conflicts with using title, video ID or auto number')
59ae15a5 126 if opts.usetitle and opts.useid:
a4bc4336 127 parser.error('using title conflicts with using video ID')
59ae15a5 128 if opts.username is not None and opts.password is None:
a4bc4336 129 opts.password = compat_getpass('Type account password and press [Return]: ')
59ae15a5
PH
130 if opts.ratelimit is not None:
131 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
132 if numeric_limit is None:
a4bc4336 133 parser.error('invalid rate limit specified')
59ae15a5 134 opts.ratelimit = numeric_limit
9e982f9e
JC
135 if opts.min_filesize is not None:
136 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
137 if numeric_limit is None:
a4bc4336 138 parser.error('invalid min_filesize specified')
9e982f9e
JC
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:
a4bc4336 143 parser.error('invalid max_filesize specified')
9e982f9e 144 opts.max_filesize = numeric_limit
59ae15a5
PH
145 if opts.retries is not None:
146 try:
147 opts.retries = int(opts.retries)
dca08720 148 except (TypeError, ValueError):
a4bc4336 149 parser.error('invalid retry count specified')
59ae15a5
PH
150 if opts.buffersize is not None:
151 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
152 if numeric_buffersize is None:
a4bc4336 153 parser.error('invalid buffer size specified')
59ae15a5 154 opts.buffersize = numeric_buffersize
a19fd00c 155 if opts.playliststart <= 0:
a4bc4336 156 raise ValueError('Playlist start must be positive')
a19fd00c 157 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
a4bc4336 158 raise ValueError('Playlist end must be greater than playlist start')
59ae15a5 159 if opts.extractaudio:
510e6f6d 160 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
a4bc4336 161 parser.error('invalid audio format specified')
59ae15a5
PH
162 if opts.audioquality:
163 opts.audioquality = opts.audioquality.strip('k').strip('K')
164 if not opts.audioquality.isdigit():
a4bc4336 165 parser.error('invalid audio quality specified')
7851b379 166 if opts.recodevideo is not None:
b7d73595 167 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
a4bc4336 168 parser.error('invalid video recode format specified')
bd558525
JMF
169 if opts.date is not None:
170 date = DateRange.day(opts.date)
171 else:
172 date = DateRange(opts.dateafter, opts.datebefore)
59ae15a5 173
de3ef3ed
PH
174 # Do not download videos when there are audio-only formats
175 if opts.extractaudio and not opts.keepvideo and opts.format is None:
176 opts.format = 'bestaudio/best'
177
0b7f3118
JMF
178 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
179 # this was the old behaviour if only --all-sub was given.
b74e86f4 180 if opts.allsubtitles and not opts.writeautomaticsub:
0b7f3118
JMF
181 opts.writesubtitles = True
182
5cb9c312
PH
183 if sys.version_info < (3,):
184 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
0be41ec2
PH
185 if opts.outtmpl is not None:
186 opts.outtmpl = opts.outtmpl.decode(preferredencoding())
5f6a1245 187 outtmpl = ((opts.outtmpl is not None and opts.outtmpl)
8bcc8756
JW
188 or (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s')
189 or (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s')
190 or (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
191 or (opts.usetitle and '%(title)s-%(id)s.%(ext)s')
192 or (opts.useid and '%(id)s.%(ext)s')
193 or (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s')
194 or DEFAULT_OUTTMPL)
dca02c80 195 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
a4bc4336
PH
196 parser.error('Cannot download a video and extract audio into the same'
197 ' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
198 ' template'.format(outtmpl))
29c7a63d 199
63e0be34 200 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
4644ac55 201 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
525ef922 202
4f026faf
PH
203 # PostProcessors
204 postprocessors = []
205 # Add the metadata pp first, the other pps will copy it
206 if opts.addmetadata:
207 postprocessors.append({'key': 'FFmpegMetadata'})
208 if opts.extractaudio:
209 postprocessors.append({
210 'key': 'FFmpegExtractAudio',
211 'preferredcodec': opts.audioformat,
212 'preferredquality': opts.audioquality,
213 'nopostoverwrites': opts.nopostoverwrites,
214 })
215 if opts.recodevideo:
216 postprocessors.append({
217 'key': 'FFmpegVideoConvertor',
218 'preferedformat': opts.recodevideo,
219 })
220 if opts.embedsubtitles:
221 postprocessors.append({
222 'key': 'FFmpegEmbedSubtitle',
223 'subtitlesformat': opts.subtitlesformat,
224 })
225 if opts.xattrs:
226 postprocessors.append({'key': 'XAttrMetadata'})
227 if opts.embedthumbnail:
228 if not opts.addmetadata:
229 postprocessors.append({'key': 'FFmpegAudioFix'})
230 postprocessors.append({'key': 'AtomicParsley'})
231 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
232 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
233 if opts.exec_cmd:
234 postprocessors.append({
235 'key': 'ExecAfterDownload',
236 'verboseOutput': opts.verbose,
237 'exec_cmd': opts.exec_cmd,
238 })
239
bdde425c 240 ydl_opts = {
59ae15a5
PH
241 'usenetrc': opts.usenetrc,
242 'username': opts.username,
243 'password': opts.password,
83317f69 244 'twofactor': opts.twofactor,
c6c19746 245 'videopassword': opts.videopassword,
525ef922 246 'quiet': (opts.quiet or any_printing),
ad8915b7 247 'no_warnings': opts.no_warnings,
59ae15a5
PH
248 'forceurl': opts.geturl,
249 'forcetitle': opts.gettitle,
1a2adf3f 250 'forceid': opts.getid,
59ae15a5
PH
251 'forcethumbnail': opts.getthumbnail,
252 'forcedescription': opts.getdescription,
525ef922 253 'forceduration': opts.getduration,
59ae15a5
PH
254 'forcefilename': opts.getfilename,
255 'forceformat': opts.getformat,
9d153818 256 'forcejson': opts.dumpjson,
63e0be34 257 'dump_single_json': opts.dump_single_json,
1bdeb7be
JMF
258 'simulate': opts.simulate or any_printing,
259 'skip_download': opts.skip_download,
59ae15a5
PH
260 'format': opts.format,
261 'format_limit': opts.format_limit,
262 'listformats': opts.listformats,
5cb9c312 263 'outtmpl': outtmpl,
213c31ae 264 'autonumber_size': opts.autonumber_size,
59ae15a5
PH
265 'restrictfilenames': opts.restrictfilenames,
266 'ignoreerrors': opts.ignoreerrors,
267 'ratelimit': opts.ratelimit,
268 'nooverwrites': opts.nooverwrites,
269 'retries': opts.retries,
270 'buffersize': opts.buffersize,
271 'noresizebuffer': opts.noresizebuffer,
272 'continuedl': opts.continue_dl,
273 'noprogress': opts.noprogress,
5717d91a 274 'progress_with_newline': opts.progress_with_newline,
59ae15a5
PH
275 'playliststart': opts.playliststart,
276 'playlistend': opts.playlistend,
ff815fe6 277 'playlistreverse': opts.playlist_reverse,
47192f92 278 'noplaylist': opts.noplaylist,
59ae15a5
PH
279 'logtostderr': opts.outtmpl == '-',
280 'consoletitle': opts.consoletitle,
281 'nopart': opts.nopart,
282 'updatetime': opts.updatetime,
283 'writedescription': opts.writedescription,
1fb07d10 284 'writeannotations': opts.writeannotations,
59ae15a5 285 'writeinfojson': opts.writeinfojson,
11d9224e 286 'writethumbnail': opts.writethumbnail,
59ae15a5 287 'writesubtitles': opts.writesubtitles,
b004821f 288 'writeautomaticsub': opts.writeautomaticsub,
ae608b80 289 'allsubtitles': opts.allsubtitles,
2a4093ea 290 'listsubtitles': opts.listsubtitles,
9e62bc44 291 'subtitlesformat': opts.subtitlesformat,
d6e203b3 292 'subtitleslangs': opts.subtitleslangs,
8271226a
PH
293 'matchtitle': decodeOption(opts.matchtitle),
294 'rejecttitle': decodeOption(opts.rejecttitle),
59ae15a5
PH
295 'max_downloads': opts.max_downloads,
296 'prefer_free_formats': opts.prefer_free_formats,
297 'verbose': opts.verbose,
855703e5 298 'dump_intermediate_pages': opts.dump_intermediate_pages,
d41e6efc 299 'write_pages': opts.write_pages,
8d5d3a5d 300 'test': opts.test,
7851b379 301 'keepvideo': opts.keepvideo,
9e982f9e 302 'min_filesize': opts.min_filesize,
bd558525 303 'max_filesize': opts.max_filesize,
5fe18bdb
PH
304 'min_views': opts.min_views,
305 'max_views': opts.max_views,
11d9224e 306 'daterange': date,
7f747732 307 'cachedir': opts.cachedir,
f8061589 308 'youtube_print_sig_code': opts.youtube_print_sig_code,
8dbe9899 309 'age_limit': opts.age_limit,
17093b83 310 'download_archive': download_archive_fn,
dca08720
PH
311 'cookiefile': opts.cookiefile,
312 'nocheckcertificate': opts.no_check_certificate,
7e8c0af0 313 'prefer_insecure': opts.prefer_insecure,
c2e52508 314 'proxy': opts.proxy,
6ad14cab 315 'socket_timeout': opts.socket_timeout,
0783b09b 316 'bidi_workaround': opts.bidi_workaround,
a0ddb8a2 317 'debug_printtraffic': opts.debug_printtraffic,
76b1bd67 318 'prefer_ffmpeg': opts.prefer_ffmpeg,
7b0817e8 319 'include_ads': opts.include_ads,
04b4d394 320 'default_search': opts.default_search,
4919603f 321 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
62fec3b2 322 'encoding': opts.encoding,
8d31fa3c 323 'exec_cmd': opts.exec_cmd,
057a5206 324 'extract_flat': opts.extract_flat,
4f026faf 325 'postprocessors': postprocessors,
bdde425c 326 }
59ae15a5 327
bdde425c 328 with YoutubeDL(ydl_opts) as ydl:
bdde425c
PH
329 # Update version
330 if opts.update_self:
331 update_self(ydl.to_screen, opts.verbose)
332
052421ff
PH
333 # Remove cache dir
334 if opts.rm_cachedir:
a0e07d31 335 ydl.cache.remove()
052421ff 336
bdde425c 337 # Maybe do nothing
1dcc4c0c 338 if (len(all_urls) < 1) and (opts.load_info_filename is None):
7d4111ed 339 if opts.update_self or opts.rm_cachedir:
bdde425c 340 sys.exit()
59ae15a5 341
7d4111ed
PH
342 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
343 parser.error('you must provide at least one URL')
344
bdde425c 345 try:
1dcc4c0c
JMF
346 if opts.load_info_filename is not None:
347 retcode = ydl.download_with_info_file(opts.load_info_filename)
348 else:
349 retcode = ydl.download(all_urls)
bdde425c 350 except MaxDownloadsReached:
a4bc4336 351 ydl.to_screen('--max-download limit reached, aborting.')
bdde425c 352 retcode = 101
59ae15a5 353
59ae15a5 354 sys.exit(retcode)
235b3ba4 355
a27b9e8b 356
b8ad4f02 357def main(argv=None):
59ae15a5 358 try:
b8ad4f02 359 _real_main(argv)
59ae15a5
PH
360 except DownloadError:
361 sys.exit(1)
362 except SameFileError:
a4bc4336 363 sys.exit('ERROR: fixed output name but more than one file to download')
59ae15a5 364 except KeyboardInterrupt:
a4bc4336 365 sys.exit('\nERROR: Interrupted by user')