]> jfr.im git - yt-dlp.git/blame - youtube_dl/__init__.py
[pornhd] Fix extraction (fixes #4915)
[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
PH
25 DateRange,
26 decodeOption,
347de493 27 DEFAULT_OUTTMPL,
a4fd0415 28 DownloadError,
347de493 29 match_filter_func,
a4fd0415 30 MaxDownloadsReached,
a4fd0415 31 preferredencoding,
62e609ab 32 read_batch_urls,
a4fd0415 33 SameFileError,
e3946f98 34 setproctitle,
a4fd0415
PH
35 std_headers,
36 write_string,
a4fd0415 37)
d5ed35b6 38from .update import update_self
92a86f4c 39from .downloader import (
a4fd0415
PH
40 FileDownloader,
41)
2bad0e5d 42from .extractor import gen_extractors, list_extractors
8222d8de 43from .YoutubeDL import YoutubeDL
a4fd0415 44
235b3ba4 45
b8ad4f02 46def _real_main(argv=None):
0d94f247
PH
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
e07e9313
PH
52 workaround_optparse_bug9161()
53
a4bc4336 54 setproctitle('youtube-dl')
e3946f98 55
b8ad4f02 56 parser, opts, args = parseOpts(argv)
59ae15a5 57
59ae15a5
PH
58 # Set user agent
59 if opts.user_agent is not None:
60 std_headers['User-Agent'] = opts.user_agent
1865ed31 61
28535652
BH
62 # Set referer
63 if opts.referer is not None:
64 std_headers['Referer'] = opts.referer
59ae15a5 65
410afb20
AA
66 # Custom HTTP headers
67 if opts.headers is not None:
68 for h in opts.headers:
69 if h.find(':', 1) < 0:
8bcc8756 70 parser.error('wrong header formatting, it should be key:value, not "%s"' % h)
410afb20
AA
71 key, value = h.split(':', 2)
72 if opts.verbose:
8bcc8756 73 write_string('[debug] Adding header from command line option %s:%s\n' % (key, value))
410afb20
AA
74 std_headers[key] = value
75
59ae15a5
PH
76 # Dump user agent
77 if opts.dump_user_agent:
93eb15c5 78 compat_print(std_headers['User-Agent'])
59ae15a5
PH
79 sys.exit(0)
80
81 # Batch file verification
62e609ab 82 batch_urls = []
59ae15a5
PH
83 if opts.batchfile is not None:
84 try:
85 if opts.batchfile == '-':
86 batchfd = sys.stdin
87 else:
62e609ab
PH
88 batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
89 batch_urls = read_batch_urls(batchfd)
05afc96b 90 if opts.verbose:
a4bc4336 91 write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
59ae15a5 92 except IOError:
a4bc4336 93 sys.exit('ERROR: batch file could not be read')
62e609ab 94 all_urls = batch_urls + args
59ae15a5 95 all_urls = [url.strip() for url in all_urls]
c774b3c6 96 _enc = preferredencoding()
41292a38 97 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
59ae15a5 98
59ae15a5 99 if opts.list_extractors:
05900629 100 for ie in list_extractors(opts.age_limit):
93eb15c5 101 compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
1a2c3c0f 102 matchedUrls = [url for url in all_urls if ie.suitable(url)]
59ae15a5 103 for mu in matchedUrls:
a4bc4336 104 compat_print(' ' + mu)
59ae15a5 105 sys.exit(0)
0f818663 106 if opts.list_extractor_descriptions:
05900629 107 for ie in list_extractors(opts.age_limit):
0f818663
PH
108 if not ie._WORKING:
109 continue
110 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
15870e90
PH
111 if desc is False:
112 continue
0f818663 113 if hasattr(ie, 'SEARCH_KEY'):
50a0f6df 114 _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
a4bc4336
PH
115 _COUNTS = ('', '5', '10', 'all')
116 desc += ' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
0f818663
PH
117 compat_print(desc)
118 sys.exit(0)
119
59ae15a5
PH
120 # Conflicting, missing and erroneous options
121 if opts.usenetrc and (opts.username is not None or opts.password is not None):
a4bc4336 122 parser.error('using .netrc conflicts with giving username/password')
59ae15a5 123 if opts.password is not None and opts.username is None:
a4bc4336 124 parser.error('account username missing\n')
59ae15a5 125 if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
a4bc4336 126 parser.error('using output template conflicts with using title, video ID or auto number')
59ae15a5 127 if opts.usetitle and opts.useid:
a4bc4336 128 parser.error('using title conflicts with using video ID')
59ae15a5 129 if opts.username is not None and opts.password is None:
a4bc4336 130 opts.password = compat_getpass('Type account password and press [Return]: ')
59ae15a5
PH
131 if opts.ratelimit is not None:
132 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
133 if numeric_limit is None:
a4bc4336 134 parser.error('invalid rate limit specified')
59ae15a5 135 opts.ratelimit = numeric_limit
9e982f9e
JC
136 if opts.min_filesize is not None:
137 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
138 if numeric_limit is None:
a4bc4336 139 parser.error('invalid min_filesize specified')
9e982f9e
JC
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:
a4bc4336 144 parser.error('invalid max_filesize specified')
9e982f9e 145 opts.max_filesize = numeric_limit
59ae15a5 146 if opts.retries is not None:
baeaeffc
PH
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')
59ae15a5
PH
154 if opts.buffersize is not None:
155 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
156 if numeric_buffersize is None:
a4bc4336 157 parser.error('invalid buffer size specified')
59ae15a5 158 opts.buffersize = numeric_buffersize
a19fd00c 159 if opts.playliststart <= 0:
a4bc4336 160 raise ValueError('Playlist start must be positive')
a19fd00c 161 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
a4bc4336 162 raise ValueError('Playlist end must be greater than playlist start')
59ae15a5 163 if opts.extractaudio:
510e6f6d 164 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
a4bc4336 165 parser.error('invalid audio format specified')
59ae15a5
PH
166 if opts.audioquality:
167 opts.audioquality = opts.audioquality.strip('k').strip('K')
168 if not opts.audioquality.isdigit():
a4bc4336 169 parser.error('invalid audio quality specified')
7851b379 170 if opts.recodevideo is not None:
b7d73595 171 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
a4bc4336 172 parser.error('invalid video recode format specified')
bd1a281e 173
bd558525
JMF
174 if opts.date is not None:
175 date = DateRange.day(opts.date)
176 else:
177 date = DateRange(opts.dateafter, opts.datebefore)
59ae15a5 178
de3ef3ed
PH
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
0b7f3118
JMF
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.
b74e86f4 185 if opts.allsubtitles and not opts.writeautomaticsub:
0b7f3118
JMF
186 opts.writesubtitles = True
187
5cb9c312
PH
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)
0be41ec2
PH
190 if opts.outtmpl is not None:
191 opts.outtmpl = opts.outtmpl.decode(preferredencoding())
5f6a1245 192 outtmpl = ((opts.outtmpl is not None and opts.outtmpl)
8bcc8756
JW
193 or (opts.format == '-1' and opts.usetitle and '%(title)s-%(id)s-%(format)s.%(ext)s')
194 or (opts.format == '-1' and '%(id)s-%(format)s.%(ext)s')
195 or (opts.usetitle and opts.autonumber and '%(autonumber)s-%(title)s-%(id)s.%(ext)s')
196 or (opts.usetitle and '%(title)s-%(id)s.%(ext)s')
197 or (opts.useid and '%(id)s.%(ext)s')
198 or (opts.autonumber and '%(autonumber)s-%(id)s.%(ext)s')
199 or DEFAULT_OUTTMPL)
dca02c80 200 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
a4bc4336
PH
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))
29c7a63d 204
c0bdf32a
PH
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
4644ac55 207 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
525ef922 208
4f026faf
PH
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 'subtitlesformat': opts.subtitlesformat,
230 })
231 if opts.xattrs:
232 postprocessors.append({'key': 'XAttrMetadata'})
233 if opts.embedthumbnail:
234 if not opts.addmetadata:
235 postprocessors.append({'key': 'FFmpegAudioFix'})
236 postprocessors.append({'key': 'AtomicParsley'})
237 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
238 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
239 if opts.exec_cmd:
240 postprocessors.append({
241 'key': 'ExecAfterDownload',
242 'verboseOutput': opts.verbose,
243 'exec_cmd': opts.exec_cmd,
244 })
881e6a1f
PH
245 if opts.xattr_set_filesize:
246 try:
247 import xattr
cc1237f4 248 xattr # Confuse flake8
881e6a1f
PH
249 except ImportError:
250 parser.error('setting filesize xattr requested but python-xattr is not available')
347de493
PH
251 match_filter = (
252 None if opts.match_filter is None
253 else match_filter_func(opts.match_filter))
4f026faf 254
bdde425c 255 ydl_opts = {
59ae15a5
PH
256 'usenetrc': opts.usenetrc,
257 'username': opts.username,
258 'password': opts.password,
83317f69 259 'twofactor': opts.twofactor,
c6c19746 260 'videopassword': opts.videopassword,
c0bdf32a 261 'quiet': (opts.quiet or any_getting or any_printing),
ad8915b7 262 'no_warnings': opts.no_warnings,
59ae15a5
PH
263 'forceurl': opts.geturl,
264 'forcetitle': opts.gettitle,
1a2adf3f 265 'forceid': opts.getid,
59ae15a5
PH
266 'forcethumbnail': opts.getthumbnail,
267 'forcedescription': opts.getdescription,
525ef922 268 'forceduration': opts.getduration,
59ae15a5
PH
269 'forcefilename': opts.getfilename,
270 'forceformat': opts.getformat,
c0bdf32a 271 'forcejson': opts.dumpjson or opts.print_json,
63e0be34 272 'dump_single_json': opts.dump_single_json,
c0bdf32a 273 'simulate': opts.simulate or any_getting,
1bdeb7be 274 'skip_download': opts.skip_download,
59ae15a5
PH
275 'format': opts.format,
276 'format_limit': opts.format_limit,
277 'listformats': opts.listformats,
5cb9c312 278 'outtmpl': outtmpl,
213c31ae 279 'autonumber_size': opts.autonumber_size,
59ae15a5
PH
280 'restrictfilenames': opts.restrictfilenames,
281 'ignoreerrors': opts.ignoreerrors,
282 'ratelimit': opts.ratelimit,
283 'nooverwrites': opts.nooverwrites,
baeaeffc 284 'retries': opts_retries,
59ae15a5
PH
285 'buffersize': opts.buffersize,
286 'noresizebuffer': opts.noresizebuffer,
287 'continuedl': opts.continue_dl,
288 'noprogress': opts.noprogress,
5717d91a 289 'progress_with_newline': opts.progress_with_newline,
59ae15a5
PH
290 'playliststart': opts.playliststart,
291 'playlistend': opts.playlistend,
ff815fe6 292 'playlistreverse': opts.playlist_reverse,
47192f92 293 'noplaylist': opts.noplaylist,
59ae15a5
PH
294 'logtostderr': opts.outtmpl == '-',
295 'consoletitle': opts.consoletitle,
296 'nopart': opts.nopart,
297 'updatetime': opts.updatetime,
298 'writedescription': opts.writedescription,
1fb07d10 299 'writeannotations': opts.writeannotations,
59ae15a5 300 'writeinfojson': opts.writeinfojson,
11d9224e 301 'writethumbnail': opts.writethumbnail,
ec82d85a 302 'write_all_thumbnails': opts.write_all_thumbnails,
59ae15a5 303 'writesubtitles': opts.writesubtitles,
b004821f 304 'writeautomaticsub': opts.writeautomaticsub,
ae608b80 305 'allsubtitles': opts.allsubtitles,
2a4093ea 306 'listsubtitles': opts.listsubtitles,
9e62bc44 307 'subtitlesformat': opts.subtitlesformat,
d6e203b3 308 'subtitleslangs': opts.subtitleslangs,
8271226a
PH
309 'matchtitle': decodeOption(opts.matchtitle),
310 'rejecttitle': decodeOption(opts.rejecttitle),
59ae15a5
PH
311 'max_downloads': opts.max_downloads,
312 'prefer_free_formats': opts.prefer_free_formats,
313 'verbose': opts.verbose,
855703e5 314 'dump_intermediate_pages': opts.dump_intermediate_pages,
d41e6efc 315 'write_pages': opts.write_pages,
8d5d3a5d 316 'test': opts.test,
7851b379 317 'keepvideo': opts.keepvideo,
9e982f9e 318 'min_filesize': opts.min_filesize,
bd558525 319 'max_filesize': opts.max_filesize,
5fe18bdb
PH
320 'min_views': opts.min_views,
321 'max_views': opts.max_views,
11d9224e 322 'daterange': date,
7f747732 323 'cachedir': opts.cachedir,
f8061589 324 'youtube_print_sig_code': opts.youtube_print_sig_code,
8dbe9899 325 'age_limit': opts.age_limit,
17093b83 326 'download_archive': download_archive_fn,
dca08720
PH
327 'cookiefile': opts.cookiefile,
328 'nocheckcertificate': opts.no_check_certificate,
7e8c0af0 329 'prefer_insecure': opts.prefer_insecure,
c2e52508 330 'proxy': opts.proxy,
6ad14cab 331 'socket_timeout': opts.socket_timeout,
0783b09b 332 'bidi_workaround': opts.bidi_workaround,
a0ddb8a2 333 'debug_printtraffic': opts.debug_printtraffic,
76b1bd67 334 'prefer_ffmpeg': opts.prefer_ffmpeg,
7b0817e8 335 'include_ads': opts.include_ads,
04b4d394 336 'default_search': opts.default_search,
4919603f 337 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
62fec3b2 338 'encoding': opts.encoding,
8d31fa3c 339 'exec_cmd': opts.exec_cmd,
057a5206 340 'extract_flat': opts.extract_flat,
34c781a2 341 'merge_output_format': opts.merge_output_format,
4f026faf 342 'postprocessors': postprocessors,
6271f1ca 343 'fixup': opts.fixup,
be4a824d 344 'source_address': opts.source_address,
58b1f00d 345 'call_home': opts.call_home,
5f0d813d 346 'sleep_interval': opts.sleep_interval,
222516d9 347 'external_downloader': opts.external_downloader,
cfb56d1a 348 'list_thumbnails': opts.list_thumbnails,
c14e88f0 349 'playlist_items': opts.playlist_items,
881e6a1f 350 'xattr_set_filesize': opts.xattr_set_filesize,
347de493 351 'match_filter': match_filter,
bdde425c 352 }
59ae15a5 353
bdde425c 354 with YoutubeDL(ydl_opts) as ydl:
bdde425c
PH
355 # Update version
356 if opts.update_self:
357 update_self(ydl.to_screen, opts.verbose)
358
052421ff
PH
359 # Remove cache dir
360 if opts.rm_cachedir:
a0e07d31 361 ydl.cache.remove()
052421ff 362
bdde425c 363 # Maybe do nothing
1dcc4c0c 364 if (len(all_urls) < 1) and (opts.load_info_filename is None):
7d4111ed 365 if opts.update_self or opts.rm_cachedir:
bdde425c 366 sys.exit()
59ae15a5 367
7d4111ed 368 ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
adc0ae3c
PH
369 parser.error(
370 'You must provide at least one URL.\n'
371 'Type youtube-dl --help to see a list of all options.')
7d4111ed 372
bdde425c 373 try:
1dcc4c0c
JMF
374 if opts.load_info_filename is not None:
375 retcode = ydl.download_with_info_file(opts.load_info_filename)
376 else:
377 retcode = ydl.download(all_urls)
bdde425c 378 except MaxDownloadsReached:
a4bc4336 379 ydl.to_screen('--max-download limit reached, aborting.')
bdde425c 380 retcode = 101
59ae15a5 381
59ae15a5 382 sys.exit(retcode)
235b3ba4 383
a27b9e8b 384
b8ad4f02 385def main(argv=None):
59ae15a5 386 try:
b8ad4f02 387 _real_main(argv)
59ae15a5
PH
388 except DownloadError:
389 sys.exit(1)
390 except SameFileError:
a4bc4336 391 sys.exit('ERROR: fixed output name but more than one file to download')
59ae15a5 392 except KeyboardInterrupt:
a4bc4336 393 sys.exit('\nERROR: Interrupted by user')
2bad0e5d
PH
394
395__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']