]> jfr.im git - yt-dlp.git/blame - youtube_dlc/YoutubeDL.py
Remove recursion in at_insert()
[yt-dlp.git] / youtube_dlc / YoutubeDL.py
CommitLineData
8222d8de 1#!/usr/bin/env python
dcdb292f 2# coding: utf-8
8222d8de 3
6febd1c1 4from __future__ import absolute_import, unicode_literals
8222d8de 5
26e63931 6import collections
31bd3925 7import contextlib
317f7ab6 8import copy
9d2ecdbc 9import datetime
c1c9a79c 10import errno
31bd3925 11import fileinput
8222d8de 12import io
b82f815f 13import itertools
8694c600 14import json
62fec3b2 15import locale
083c9df9 16import operator
8222d8de 17import os
dca08720 18import platform
8222d8de
JMF
19import re
20import shutil
dca08720 21import subprocess
8222d8de
JMF
22import socket
23import sys
24import time
67134eab 25import tokenize
8222d8de 26import traceback
75822ca7 27import random
8222d8de 28
961ea474
S
29from string import ascii_letters
30
8c25f81b 31from .compat import (
82d8a8b6 32 compat_basestring,
dca08720 33 compat_cookiejar,
003c69a8 34 compat_get_terminal_size,
ce02ed60 35 compat_http_client,
4f026faf 36 compat_kwargs,
d0d9ade4 37 compat_numeric_types,
e9c0cdd3 38 compat_os_name,
ce02ed60 39 compat_str,
67134eab 40 compat_tokenize_tokenize,
ce02ed60
PH
41 compat_urllib_error,
42 compat_urllib_request,
8b172c2e 43 compat_urllib_request_DataHandler,
8c25f81b
PH
44)
45from .utils import (
eedb7ba5
S
46 age_restricted,
47 args_to_str,
ce02ed60
PH
48 ContentTooShortError,
49 date_from_str,
50 DateRange,
acd69589 51 DEFAULT_OUTTMPL,
ce02ed60 52 determine_ext,
b5559424 53 determine_protocol,
ce02ed60 54 DownloadError,
c0384f22 55 encode_compat_str,
ce02ed60 56 encodeFilename,
9b9c5355 57 error_to_compat_str,
590bc6f6 58 expand_path,
ce02ed60 59 ExtractorError,
02dbf93f 60 format_bytes,
525ef922 61 formatSeconds,
773f291d 62 GeoRestrictedError,
c9969434 63 int_or_none,
773f291d 64 ISO3166Utils,
ce02ed60 65 locked_file,
dca08720 66 make_HTTPS_handler,
ce02ed60 67 MaxDownloadsReached,
cd6fc19e 68 orderedSet,
b7ab0590 69 PagedList,
083c9df9 70 parse_filesize,
91410c9b 71 PerRequestProxyHandler,
dca08720 72 platform_name,
eedb7ba5 73 PostProcessingError,
ce02ed60 74 preferredencoding,
eedb7ba5 75 prepend_extension,
51fb4995 76 register_socks_protocols,
cfb56d1a 77 render_table,
eedb7ba5 78 replace_extension,
ce02ed60
PH
79 SameFileError,
80 sanitize_filename,
1bb5c511 81 sanitize_path,
dcf77cf1 82 sanitize_url,
67dda517 83 sanitized_Request,
e5660ee6 84 std_headers,
1211bb6d 85 str_or_none,
ce02ed60 86 subtitles_filename,
ce02ed60 87 UnavailableVideoError,
29eb5174 88 url_basename,
58b1f00d 89 version_tuple,
ce02ed60
PH
90 write_json_file,
91 write_string,
1bab3437 92 YoutubeDLCookieJar,
6a3f4c3f 93 YoutubeDLCookieProcessor,
dca08720 94 YoutubeDLHandler,
fca6dba8 95 YoutubeDLRedirectHandler,
ce02ed60 96)
a0e07d31 97from .cache import Cache
e0986e31 98from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
4c54b89e 99from .extractor.openload import PhantomJSwrapper
3bc2ddcc 100from .downloader import get_suitable_downloader
4c83c967 101from .downloader.rtmp import rtmpdump_version
4f026faf 102from .postprocessor import (
f17f8651 103 FFmpegFixupM3u8PP,
62cd676c 104 FFmpegFixupM4aPP,
6271f1ca 105 FFmpegFixupStretchedPP,
4f026faf
PH
106 FFmpegMergerPP,
107 FFmpegPostProcessor,
57df9f53 108 FFmpegSubtitlesConvertorPP,
4f026faf
PH
109 get_postprocessor,
110)
dca08720 111from .version import __version__
8222d8de 112
e9c0cdd3
YCH
113if compat_os_name == 'nt':
114 import ctypes
115
ecdec191
JB
116class ArchiveTree(object):
117 def __init__(self, line):
118 self.left = None
119 self.right = None
120 self.line = line
121
122 def at_insert(self, line):
1de7ea76
JB
123# print("at_insert: ", line)
124 cur = self
125 while True:
126# print("comparing ", line, cur.line)
127 if cur.line:
128 if line < cur.line:
129 if cur.left is None:
130 cur.left = ArchiveTree(line)
131 return
132 else:
133 cur = cur.left
134 continue
135 elif line > cur.line:
136 if cur.right is None:
137 cur.right = ArchiveTree(line)
138 return
139 else:
140 cur = cur.right
141 continue
ecdec191 142 else:
1de7ea76
JB
143 # Duplicate line found
144 return
145 else:
146 cur.line = line
147 return
ecdec191
JB
148
149 def at_exist(self, line):
ecdec191
JB
150 if self.line is None:
151 return False
152 if line < self.line:
153 if self.left is None:
154 return False
155 return self.left.at_exist(line)
156 elif line > self.line:
157 if self.right is None:
158 return False
159 return self.right.at_exist(line)
160 else:
161 return True
162
8222d8de
JMF
163
164class YoutubeDL(object):
165 """YoutubeDL class.
166
167 YoutubeDL objects are the ones responsible of downloading the
168 actual video file and writing it to disk if the user has requested
169 it, among some other tasks. In most cases there should be one per
170 program. As, given a video URL, the downloader doesn't know how to
171 extract all the needed information, task that InfoExtractors do, it
172 has to pass the URL to one of them.
173
174 For this, YoutubeDL objects have a method that allows
175 InfoExtractors to be registered in a given order. When it is passed
176 a URL, the YoutubeDL object handles it to the first InfoExtractor it
177 finds that reports being able to handle it. The InfoExtractor extracts
178 all the information about the video or videos the URL refers to, and
179 YoutubeDL process the extracted information, possibly using a File
180 Downloader to download the video.
181
182 YoutubeDL objects accept a lot of parameters. In order not to saturate
183 the object constructor with arguments, it receives a dictionary of
184 options instead. These options are available through the params
185 attribute for the InfoExtractors to use. The YoutubeDL also
186 registers itself as the downloader in charge for the InfoExtractors
187 that are added to it, so this is a "mutual registration".
188
189 Available options:
190
191 username: Username for authentication purposes.
192 password: Password for authentication purposes.
180940e0 193 videopassword: Password for accessing a video.
1da50aa3
S
194 ap_mso: Adobe Pass multiple-system operator identifier.
195 ap_username: Multiple-system operator account username.
196 ap_password: Multiple-system operator account password.
8222d8de
JMF
197 usenetrc: Use netrc for authentication instead.
198 verbose: Print additional info to stdout.
199 quiet: Do not print messages to stdout.
ad8915b7 200 no_warnings: Do not print out anything for warnings.
8222d8de
JMF
201 forceurl: Force printing final URL.
202 forcetitle: Force printing title.
203 forceid: Force printing ID.
204 forcethumbnail: Force printing thumbnail URL.
205 forcedescription: Force printing description.
206 forcefilename: Force printing final filename.
525ef922 207 forceduration: Force printing duration.
8694c600 208 forcejson: Force printing info_dict as JSON.
63e0be34
PH
209 dump_single_json: Force printing the info_dict of the whole playlist
210 (or video) as a single JSON line.
8222d8de 211 simulate: Do not download the video files.
d8600787 212 format: Video format code. See options.py for more information.
8222d8de
JMF
213 outtmpl: Template for output names.
214 restrictfilenames: Do not allow "&" and spaces in file names
215 ignoreerrors: Do not stop on download errors.
d22dec74 216 force_generic_extractor: Force downloader to use the generic extractor
8222d8de
JMF
217 nooverwrites: Prevent overwriting files.
218 playliststart: Playlist item to start at.
219 playlistend: Playlist item to end at.
c14e88f0 220 playlist_items: Specific indices of playlist to download.
ff815fe6 221 playlistreverse: Download playlist items in reverse order.
75822ca7 222 playlistrandom: Download playlist items in random order.
8222d8de
JMF
223 matchtitle: Download only matching titles.
224 rejecttitle: Reject downloads for matching titles.
8bf9319e 225 logger: Log messages to a logging.Logger instance.
8222d8de
JMF
226 logtostderr: Log messages to stderr instead of stdout.
227 writedescription: Write the video description to a .description file
228 writeinfojson: Write the video description to a .info.json file
1fb07d10 229 writeannotations: Write the video annotations to a .annotations.xml file
8222d8de 230 writethumbnail: Write the thumbnail image to a file
ec82d85a 231 write_all_thumbnails: Write all thumbnail formats to files
8222d8de 232 writesubtitles: Write the video subtitles to a file
741dd8ea 233 writeautomaticsub: Write the automatically generated subtitles to a file
8222d8de 234 allsubtitles: Downloads all the subtitles of the video
0b7f3118 235 (requires writesubtitles or writeautomaticsub)
8222d8de 236 listsubtitles: Lists all available subtitles for the video
a504ced0 237 subtitlesformat: The format code for subtitles
aa6a10c4 238 subtitleslangs: List of languages of the subtitles to download
8222d8de
JMF
239 keepvideo: Keep the video file after post-processing
240 daterange: A DateRange object, download only if the upload_date is in the range.
241 skip_download: Skip the actual download of the video file
c35f9e72 242 cachedir: Location of the cache files in the filesystem.
a0e07d31 243 False to disable filesystem cache.
47192f92 244 noplaylist: Download single video instead of a playlist if in doubt.
8dbe9899
PH
245 age_limit: An integer representing the user's age in years.
246 Unsuitable videos for the given age are skipped.
5fe18bdb
PH
247 min_views: An integer representing the minimum view count the video
248 must have in order to not be skipped.
249 Videos without view count information are always
250 downloaded. None for no limit.
251 max_views: An integer representing the maximum view count.
252 Videos that are more popular than that are not
253 downloaded.
254 Videos without view count information are always
255 downloaded. None for no limit.
256 download_archive: File name of a file where all downloads are recorded.
c1c9a79c
PH
257 Videos already present in the file are not downloaded
258 again.
dca08720 259 cookiefile: File name where cookies should be read from and dumped to.
a1ee09e8 260 nocheckcertificate:Do not verify SSL certificates
7e8c0af0
PH
261 prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
262 At the moment, this is only supported by YouTube.
a1ee09e8 263 proxy: URL of the proxy server to use
38cce791 264 geo_verification_proxy: URL of the proxy to use for IP address verification
504f20dd 265 on geo-restricted sites.
e344693b 266 socket_timeout: Time to wait for unresponsive hosts, in seconds
0783b09b
PH
267 bidi_workaround: Work around buggy terminals without bidirectional text
268 support, using fridibi
a0ddb8a2 269 debug_printtraffic:Print out sent and received HTTP traffic
7b0817e8 270 include_ads: Download ads as well
04b4d394
PH
271 default_search: Prepend this string if an input url is not valid.
272 'auto' for elaborate guessing
62fec3b2 273 encoding: Use this encoding instead of the system-specified.
e8ee972c 274 extract_flat: Do not resolve URLs, return the immediate result.
057a5206
PH
275 Pass in 'in_playlist' to only show this behavior for
276 playlist items.
4f026faf 277 postprocessors: A list of dictionaries, each with an entry
71b640cc 278 * key: The name of the postprocessor. See
cefecac1 279 youtube_dlc/postprocessor/__init__.py for a list.
4f026faf
PH
280 as well as any further keyword arguments for the
281 postprocessor.
71b640cc
PH
282 progress_hooks: A list of functions that get called on download
283 progress, with a dictionary with the entries
5cda4eda 284 * status: One of "downloading", "error", or "finished".
ee69b99a 285 Check this first and ignore unknown values.
71b640cc 286
5cda4eda 287 If status is one of "downloading", or "finished", the
ee69b99a
PH
288 following properties may also be present:
289 * filename: The final filename (always present)
5cda4eda 290 * tmpfilename: The filename we're currently writing to
71b640cc
PH
291 * downloaded_bytes: Bytes on disk
292 * total_bytes: Size of the whole file, None if unknown
5cda4eda
PH
293 * total_bytes_estimate: Guess of the eventual file size,
294 None if unavailable.
295 * elapsed: The number of seconds since download started.
71b640cc
PH
296 * eta: The estimated time in seconds, None if unknown
297 * speed: The download speed in bytes/second, None if
298 unknown
5cda4eda
PH
299 * fragment_index: The counter of the currently
300 downloaded video fragment.
301 * fragment_count: The number of fragments (= individual
302 files that will be merged)
71b640cc
PH
303
304 Progress hooks are guaranteed to be called at least once
305 (with status "finished") if the download is successful.
45598f15 306 merge_output_format: Extension to use when merging formats.
6271f1ca
PH
307 fixup: Automatically correct known faults of the file.
308 One of:
309 - "never": do nothing
310 - "warn": only emit a warning
311 - "detect_or_warn": check whether we can do anything
62cd676c 312 about it, warn otherwise (default)
504f20dd 313 source_address: Client-side IP address to bind to.
6ec6cb4e 314 call_home: Boolean, true iff we are allowed to contact the
cefecac1 315 youtube-dlc servers for debugging.
7aa589a5
S
316 sleep_interval: Number of seconds to sleep before each download when
317 used alone or a lower bound of a range for randomized
318 sleep before each download (minimum possible number
319 of seconds to sleep) when used along with
320 max_sleep_interval.
321 max_sleep_interval:Upper bound of a range for randomized sleep before each
322 download (maximum possible number of seconds to sleep).
323 Must only be used along with sleep_interval.
324 Actual sleep time will be a random float from range
325 [sleep_interval; max_sleep_interval].
cfb56d1a
PH
326 listformats: Print an overview of available video formats and exit.
327 list_thumbnails: Print a table of all thumbnails and exit.
347de493
PH
328 match_filter: A function that gets called with the info_dict of
329 every video.
330 If it returns a message, the video is ignored.
331 If it returns None, the video is downloaded.
332 match_filter_func in utils.py is one example for this.
7e5db8c9 333 no_color: Do not emit color codes in output.
0a840f58 334 geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
504f20dd 335 HTTP header
0a840f58 336 geo_bypass_country:
773f291d
S
337 Two-letter ISO 3166-2 country code that will be used for
338 explicit geographic restriction bypassing via faking
504f20dd 339 X-Forwarded-For HTTP header
5f95927a
S
340 geo_bypass_ip_block:
341 IP range in CIDR notation that will be used similarly to
504f20dd 342 geo_bypass_country
71b640cc 343
85729c51
PH
344 The following options determine which downloader is picked:
345 external_downloader: Executable of the external downloader to call.
346 None or unset for standard (built-in) downloader.
bf09af3a
S
347 hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
348 if True, otherwise use ffmpeg/avconv if False, otherwise
349 use downloader suggested by extractor if None.
fe7e0c98 350
8222d8de 351 The following parameters are not used by YoutubeDL itself, they are used by
cefecac1 352 the downloader (see youtube_dlc/downloader/common.py):
8222d8de 353 nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
881e6a1f 354 noresizebuffer, retries, continuedl, noprogress, consoletitle,
b54d4a5c
S
355 xattr_set_filesize, external_downloader_args, hls_use_mpegts,
356 http_chunk_size.
76b1bd67
JMF
357
358 The following options are used by the post processors:
d4a24f40
S
359 prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
360 otherwise prefer ffmpeg.
c0b7d117
S
361 ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
362 to the binary or its containing directory.
f72b0a60
S
363 postprocessor_args: A list of additional command-line arguments for the
364 postprocessor.
3836b02c 365
3600fd59
S
366 The following options are used by the Youtube extractor:
367 youtube_include_dash_manifest: If True (default), DASH manifests and related
368 data will be downloaded and processed by extractor.
369 You can reduce network I/O by disabling it if you don't
370 care about DASH.
8222d8de
JMF
371 """
372
c9969434
S
373 _NUMERIC_FIELDS = set((
374 'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
375 'timestamp', 'upload_year', 'upload_month', 'upload_day',
376 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
377 'average_rating', 'comment_count', 'age_limit',
378 'start_time', 'end_time',
379 'chapter_number', 'season_number', 'episode_number',
380 'track_number', 'disc_number', 'release_year',
381 'playlist_index',
382 ))
383
8222d8de
JMF
384 params = None
385 _ies = []
386 _pps = []
387 _download_retcode = None
388 _num_downloads = None
389 _screen_file = None
390
3511266b 391 def __init__(self, params=None, auto_init=True):
8222d8de 392 """Create a FileDownloader object with the given options."""
e9f9a10f
JMF
393 if params is None:
394 params = {}
8222d8de 395 self._ies = []
56c73665 396 self._ies_instances = {}
8222d8de 397 self._pps = []
933605d7 398 self._progress_hooks = []
8222d8de
JMF
399 self._download_retcode = 0
400 self._num_downloads = 0
401 self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
0783b09b 402 self._err_file = sys.stderr
4abf617b
S
403 self.params = {
404 # Default parameters
405 'nocheckcertificate': False,
406 }
407 self.params.update(params)
a0e07d31 408 self.cache = Cache(self)
ecdec191
JB
409 self.archive = ArchiveTree(None)
410
411 """Preload the archive, if any is specified"""
412 def preload_download_archive(self):
413 fn = self.params.get('download_archive')
414 if fn is None:
415 return False
416 try:
417 with locked_file(fn, 'r', encoding='utf-8') as archive_file:
418 for line in archive_file:
419 self.archive.at_insert(line.strip())
420 except IOError as ioe:
421 if ioe.errno != errno.ENOENT:
422 raise
423 return True
34308b30 424
be5df5ee
S
425 def check_deprecated(param, option, suggestion):
426 if self.params.get(param) is not None:
427 self.report_warning(
428 '%s is deprecated. Use %s instead.' % (option, suggestion))
429 return True
430 return False
431
1de7ea76
JB
432 if self.params.get('verbose'):
433 self.to_stdout('[debug] Loading archive file %r' % self.params.get('download_archive'))
434
ecdec191
JB
435 preload_download_archive(self)
436
be5df5ee 437 if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
38cce791
YCH
438 if self.params.get('geo_verification_proxy') is None:
439 self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
440
be5df5ee
S
441 check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
442 check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
443 check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
444
0783b09b 445 if params.get('bidi_workaround', False):
1c088fa8
PH
446 try:
447 import pty
448 master, slave = pty.openpty()
003c69a8 449 width = compat_get_terminal_size().columns
1c088fa8
PH
450 if width is None:
451 width_args = []
452 else:
453 width_args = ['-w', str(width)]
5d681e96 454 sp_kwargs = dict(
1c088fa8
PH
455 stdin=subprocess.PIPE,
456 stdout=slave,
457 stderr=self._err_file)
5d681e96
PH
458 try:
459 self._output_process = subprocess.Popen(
460 ['bidiv'] + width_args, **sp_kwargs
461 )
462 except OSError:
5d681e96
PH
463 self._output_process = subprocess.Popen(
464 ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
465 self._output_channel = os.fdopen(master, 'rb')
1c088fa8 466 except OSError as ose:
66e7ace1 467 if ose.errno == errno.ENOENT:
6febd1c1 468 self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
1c088fa8
PH
469 else:
470 raise
0783b09b 471
3089bc74
S
472 if (sys.platform != 'win32'
473 and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
474 and not params.get('restrictfilenames', False)):
e9137224 475 # Unicode filesystem API will throw errors (#1474, #13027)
34308b30 476 self.report_warning(
6febd1c1 477 'Assuming --restrict-filenames since file system encoding '
1b725173 478 'cannot encode all characters. '
6febd1c1 479 'Set the LC_ALL environment variable to fix this.')
4a98cdbf 480 self.params['restrictfilenames'] = True
34308b30 481
486dd09e
PH
482 if isinstance(params.get('outtmpl'), bytes):
483 self.report_warning(
484 'Parameter outtmpl is bytes, but should be a unicode string. '
485 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
486
dca08720
PH
487 self._setup_opener()
488
3511266b
PH
489 if auto_init:
490 self.print_debug_header()
491 self.add_default_info_extractors()
492
4f026faf
PH
493 for pp_def_raw in self.params.get('postprocessors', []):
494 pp_class = get_postprocessor(pp_def_raw['key'])
495 pp_def = dict(pp_def_raw)
496 del pp_def['key']
497 pp = pp_class(self, **compat_kwargs(pp_def))
498 self.add_post_processor(pp)
499
71b640cc
PH
500 for ph in self.params.get('progress_hooks', []):
501 self.add_progress_hook(ph)
502
51fb4995
YCH
503 register_socks_protocols()
504
7d4111ed
PH
505 def warn_if_short_id(self, argv):
506 # short YouTube ID starting with dash?
507 idxs = [
508 i for i, a in enumerate(argv)
509 if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
510 if idxs:
511 correct_argv = (
cefecac1 512 ['youtube-dlc']
3089bc74
S
513 + [a for i, a in enumerate(argv) if i not in idxs]
514 + ['--'] + [argv[i] for i in idxs]
7d4111ed
PH
515 )
516 self.report_warning(
517 'Long argument string detected. '
518 'Use -- to separate parameters and URLs, like this:\n%s\n' %
519 args_to_str(correct_argv))
520
8222d8de
JMF
521 def add_info_extractor(self, ie):
522 """Add an InfoExtractor object to the end of the list."""
523 self._ies.append(ie)
e52d7f85
JMF
524 if not isinstance(ie, type):
525 self._ies_instances[ie.ie_key()] = ie
526 ie.set_downloader(self)
8222d8de 527
56c73665
JMF
528 def get_info_extractor(self, ie_key):
529 """
530 Get an instance of an IE with name ie_key, it will try to get one from
531 the _ies list, if there's no instance it will create a new one and add
532 it to the extractor list.
533 """
534 ie = self._ies_instances.get(ie_key)
535 if ie is None:
536 ie = get_info_extractor(ie_key)()
537 self.add_info_extractor(ie)
538 return ie
539
023fa8c4
JMF
540 def add_default_info_extractors(self):
541 """
542 Add the InfoExtractors returned by gen_extractors to the end of the list
543 """
e52d7f85 544 for ie in gen_extractor_classes():
023fa8c4
JMF
545 self.add_info_extractor(ie)
546
8222d8de
JMF
547 def add_post_processor(self, pp):
548 """Add a PostProcessor object to the end of the chain."""
549 self._pps.append(pp)
550 pp.set_downloader(self)
551
933605d7
JMF
552 def add_progress_hook(self, ph):
553 """Add the progress hook (currently only for the file downloader)"""
554 self._progress_hooks.append(ph)
8ab470f1 555
1c088fa8 556 def _bidi_workaround(self, message):
5d681e96 557 if not hasattr(self, '_output_channel'):
1c088fa8
PH
558 return message
559
5d681e96 560 assert hasattr(self, '_output_process')
11b85ce6 561 assert isinstance(message, compat_str)
6febd1c1
PH
562 line_count = message.count('\n') + 1
563 self._output_process.stdin.write((message + '\n').encode('utf-8'))
5d681e96 564 self._output_process.stdin.flush()
6febd1c1 565 res = ''.join(self._output_channel.readline().decode('utf-8')
9e1a5b84 566 for _ in range(line_count))
6febd1c1 567 return res[:-len('\n')]
1c088fa8 568
8222d8de 569 def to_screen(self, message, skip_eol=False):
0783b09b
PH
570 """Print message to stdout if not in quiet mode."""
571 return self.to_stdout(message, skip_eol, check_quiet=True)
572
734f90bb 573 def _write_string(self, s, out=None):
b58ddb32 574 write_string(s, out=out, encoding=self.params.get('encoding'))
734f90bb 575
0783b09b 576 def to_stdout(self, message, skip_eol=False, check_quiet=False):
8222d8de 577 """Print message to stdout if not in quiet mode."""
8bf9319e 578 if self.params.get('logger'):
43afe285 579 self.params['logger'].debug(message)
0783b09b 580 elif not check_quiet or not self.params.get('quiet', False):
1c088fa8 581 message = self._bidi_workaround(message)
6febd1c1 582 terminator = ['\n', ''][skip_eol]
8222d8de 583 output = message + terminator
1c088fa8 584
734f90bb 585 self._write_string(output, self._screen_file)
8222d8de
JMF
586
587 def to_stderr(self, message):
588 """Print message to stderr."""
11b85ce6 589 assert isinstance(message, compat_str)
8bf9319e 590 if self.params.get('logger'):
43afe285
IB
591 self.params['logger'].error(message)
592 else:
1c088fa8 593 message = self._bidi_workaround(message)
6febd1c1 594 output = message + '\n'
734f90bb 595 self._write_string(output, self._err_file)
8222d8de 596
1e5b9a95
PH
597 def to_console_title(self, message):
598 if not self.params.get('consoletitle', False):
599 return
4bede0d8
C
600 if compat_os_name == 'nt':
601 if ctypes.windll.kernel32.GetConsoleWindow():
602 # c_wchar_p() might not be necessary if `message` is
603 # already of type unicode()
604 ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
1e5b9a95 605 elif 'TERM' in os.environ:
734f90bb 606 self._write_string('\033]0;%s\007' % message, self._screen_file)
1e5b9a95 607
bdde425c
PH
608 def save_console_title(self):
609 if not self.params.get('consoletitle', False):
610 return
94c3442e
S
611 if self.params.get('simulate', False):
612 return
4bede0d8 613 if compat_os_name != 'nt' and 'TERM' in os.environ:
efd6c574 614 # Save the title on stack
734f90bb 615 self._write_string('\033[22;0t', self._screen_file)
bdde425c
PH
616
617 def restore_console_title(self):
618 if not self.params.get('consoletitle', False):
619 return
94c3442e
S
620 if self.params.get('simulate', False):
621 return
4bede0d8 622 if compat_os_name != 'nt' and 'TERM' in os.environ:
efd6c574 623 # Restore the title from stack
734f90bb 624 self._write_string('\033[23;0t', self._screen_file)
bdde425c
PH
625
626 def __enter__(self):
627 self.save_console_title()
628 return self
629
630 def __exit__(self, *args):
631 self.restore_console_title()
f89197d7 632
dca08720 633 if self.params.get('cookiefile') is not None:
1bab3437 634 self.cookiejar.save(ignore_discard=True, ignore_expires=True)
bdde425c 635
8222d8de
JMF
636 def trouble(self, message=None, tb=None):
637 """Determine action to take when a download problem appears.
638
639 Depending on if the downloader has been configured to ignore
640 download errors or not, this method may throw an exception or
641 not when errors are found, after printing the message.
642
643 tb, if given, is additional traceback information.
644 """
645 if message is not None:
646 self.to_stderr(message)
647 if self.params.get('verbose'):
648 if tb is None:
649 if sys.exc_info()[0]: # if .trouble has been called from an except block
6febd1c1 650 tb = ''
8222d8de 651 if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
6febd1c1 652 tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
c0384f22 653 tb += encode_compat_str(traceback.format_exc())
8222d8de
JMF
654 else:
655 tb_data = traceback.format_list(traceback.extract_stack())
6febd1c1 656 tb = ''.join(tb_data)
8222d8de
JMF
657 self.to_stderr(tb)
658 if not self.params.get('ignoreerrors', False):
659 if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
660 exc_info = sys.exc_info()[1].exc_info
661 else:
662 exc_info = sys.exc_info()
663 raise DownloadError(message, exc_info)
664 self._download_retcode = 1
665
666 def report_warning(self, message):
667 '''
668 Print the message to stderr, it will be prefixed with 'WARNING:'
669 If stderr is a tty file the 'WARNING:' will be colored
670 '''
6d07ce01
JMF
671 if self.params.get('logger') is not None:
672 self.params['logger'].warning(message)
8222d8de 673 else:
ad8915b7
PH
674 if self.params.get('no_warnings'):
675 return
e9c0cdd3 676 if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
6d07ce01
JMF
677 _msg_header = '\033[0;33mWARNING:\033[0m'
678 else:
679 _msg_header = 'WARNING:'
680 warning_message = '%s %s' % (_msg_header, message)
681 self.to_stderr(warning_message)
8222d8de
JMF
682
683 def report_error(self, message, tb=None):
684 '''
685 Do the same as trouble, but prefixes the message with 'ERROR:', colored
686 in red if stderr is a tty file.
687 '''
e9c0cdd3 688 if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
6febd1c1 689 _msg_header = '\033[0;31mERROR:\033[0m'
8222d8de 690 else:
6febd1c1
PH
691 _msg_header = 'ERROR:'
692 error_message = '%s %s' % (_msg_header, message)
8222d8de
JMF
693 self.trouble(error_message, tb)
694
8222d8de
JMF
695 def report_file_already_downloaded(self, file_name):
696 """Report file has already been fully downloaded."""
697 try:
6febd1c1 698 self.to_screen('[download] %s has already been downloaded' % file_name)
ce02ed60 699 except UnicodeEncodeError:
6febd1c1 700 self.to_screen('[download] The file has already been downloaded')
8222d8de 701
8222d8de
JMF
702 def prepare_filename(self, info_dict):
703 """Generate the output filename."""
704 try:
705 template_dict = dict(info_dict)
706
707 template_dict['epoch'] = int(time.time())
708 autonumber_size = self.params.get('autonumber_size')
709 if autonumber_size is None:
710 autonumber_size = 5
89db639d 711 template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
17b75c0d
PH
712 if template_dict.get('resolution') is None:
713 if template_dict.get('width') and template_dict.get('height'):
714 template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
715 elif template_dict.get('height'):
805ef3c6 716 template_dict['resolution'] = '%sp' % template_dict['height']
17b75c0d 717 elif template_dict.get('width'):
51ce9117 718 template_dict['resolution'] = '%dx?' % template_dict['width']
8222d8de 719
586a91b6 720 sanitize = lambda k, v: sanitize_filename(
45598aab 721 compat_str(v),
1bb5c511 722 restricted=self.params.get('restrictfilenames'),
40df485f 723 is_id=(k == 'id' or k.endswith('_id')))
d0d9ade4 724 template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
45598aab 725 for k, v in template_dict.items()
f0e14fdd 726 if v is not None and not isinstance(v, (list, tuple, dict)))
6febd1c1 727 template_dict = collections.defaultdict(lambda: 'NA', template_dict)
8222d8de 728
b3613d36 729 outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
d0d9ade4 730
89db639d
S
731 # For fields playlist_index and autonumber convert all occurrences
732 # of %(field)s to %(field)0Nd for backward compatibility
733 field_size_compat_map = {
734 'playlist_index': len(str(template_dict['n_entries'])),
735 'autonumber': autonumber_size,
736 }
737 FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
738 mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
739 if mobj:
740 outtmpl = re.sub(
741 FIELD_SIZE_COMPAT_RE,
742 r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
743 outtmpl)
744
d0d9ade4
S
745 # Missing numeric fields used together with integer presentation types
746 # in format specification will break the argument substitution since
747 # string 'NA' is returned for missing fields. We will patch output
748 # template for missing fields to meet string presentation type.
c9969434 749 for numeric_field in self._NUMERIC_FIELDS:
d0d9ade4
S
750 if numeric_field not in template_dict:
751 # As of [1] format syntax is:
752 # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
753 # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
754 FORMAT_RE = r'''(?x)
755 (?<!%)
756 %
757 \({0}\) # mapping key
758 (?:[#0\-+ ]+)? # conversion flags (optional)
759 (?:\d+)? # minimum field width (optional)
760 (?:\.\d+)? # precision (optional)
761 [hlL]? # length modifier (optional)
762 [diouxXeEfFgGcrs%] # conversion type
763 '''
764 outtmpl = re.sub(
765 FORMAT_RE.format(numeric_field),
766 r'%({0})s'.format(numeric_field), outtmpl)
767
15da37c7
S
768 # expand_path translates '%%' into '%' and '$$' into '$'
769 # correspondingly that is not what we want since we need to keep
770 # '%%' intact for template dict substitution step. Working around
771 # with boundary-alike separator hack.
961ea474 772 sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
15da37c7
S
773 outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
774
775 # outtmpl should be expand_path'ed before template dict substitution
776 # because meta fields may contain env variables we don't want to
777 # be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
778 # title "Hello $PATH", we don't want `$PATH` to be expanded.
779 filename = expand_path(outtmpl).replace(sep, '') % template_dict
780
3a0d2f52
S
781 # Temporary fix for #4787
782 # 'Treat' all problem characters by passing filename through preferredencoding
783 # to workaround encoding issues with subprocess on python2 @ Windows
784 if sys.version_info < (3, 0) and sys.platform == 'win32':
785 filename = encodeFilename(filename, True).decode(preferredencoding())
b3613d36 786 return sanitize_path(filename)
8222d8de 787 except ValueError as err:
6febd1c1 788 self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
8222d8de
JMF
789 return None
790
442c37b7 791 def _match_entry(self, info_dict, incomplete):
ecdec191 792 """ Returns None if the file should be downloaded """
8222d8de 793
6febd1c1 794 video_title = info_dict.get('title', info_dict.get('id', 'video'))
7012b23c
PH
795 if 'title' in info_dict:
796 # This can happen when we're just evaluating the playlist
797 title = info_dict['title']
798 matchtitle = self.params.get('matchtitle', False)
799 if matchtitle:
800 if not re.search(matchtitle, title, re.IGNORECASE):
6febd1c1 801 return '"' + title + '" title did not match pattern "' + matchtitle + '"'
7012b23c
PH
802 rejecttitle = self.params.get('rejecttitle', False)
803 if rejecttitle:
804 if re.search(rejecttitle, title, re.IGNORECASE):
6febd1c1 805 return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
d800609c 806 date = info_dict.get('upload_date')
8222d8de
JMF
807 if date is not None:
808 dateRange = self.params.get('daterange', DateRange())
809 if date not in dateRange:
6febd1c1 810 return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
d800609c 811 view_count = info_dict.get('view_count')
5fe18bdb
PH
812 if view_count is not None:
813 min_views = self.params.get('min_views')
814 if min_views is not None and view_count < min_views:
6febd1c1 815 return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
5fe18bdb
PH
816 max_views = self.params.get('max_views')
817 if max_views is not None and view_count > max_views:
6febd1c1 818 return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
05900629 819 if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
347de493 820 return 'Skipping "%s" because it is age restricted' % video_title
c1c9a79c 821 if self.in_download_archive(info_dict):
6febd1c1 822 return '%s has already been recorded in archive' % video_title
347de493 823
442c37b7
PH
824 if not incomplete:
825 match_filter = self.params.get('match_filter')
826 if match_filter is not None:
827 ret = match_filter(info_dict)
828 if ret is not None:
829 return ret
347de493 830
8222d8de 831 return None
fe7e0c98 832
b6c45014
JMF
833 @staticmethod
834 def add_extra_info(info_dict, extra_info):
835 '''Set the keys from extra_info in info dict if they are missing'''
836 for key, value in extra_info.items():
837 info_dict.setdefault(key, value)
838
7fc3fa05 839 def extract_info(self, url, download=True, ie_key=None, extra_info={},
61aa5ba3 840 process=True, force_generic_extractor=False):
8222d8de
JMF
841 '''
842 Returns a list with a dictionary for each video we find.
843 If 'download', also downloads the videos.
844 extra_info is a dict containing the extra values to add to each result
613b2d9d 845 '''
fe7e0c98 846
61aa5ba3 847 if not ie_key and force_generic_extractor:
d22dec74
S
848 ie_key = 'Generic'
849
8222d8de 850 if ie_key:
56c73665 851 ies = [self.get_info_extractor(ie_key)]
8222d8de
JMF
852 else:
853 ies = self._ies
854
855 for ie in ies:
856 if not ie.suitable(url):
857 continue
858
e52d7f85 859 ie = self.get_info_extractor(ie.ie_key())
8222d8de 860 if not ie.working():
6febd1c1
PH
861 self.report_warning('The program functionality for this site has been marked as broken, '
862 'and will probably not work.')
8222d8de
JMF
863
864 try:
865 ie_result = ie.extract(url)
5f6a1245 866 if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
8222d8de
JMF
867 break
868 if isinstance(ie_result, list):
869 # Backwards compatibility: old IE result format
8222d8de
JMF
870 ie_result = {
871 '_type': 'compat_list',
872 'entries': ie_result,
873 }
ea38e55f 874 self.add_default_extra_info(ie_result, ie, url)
7fc3fa05
PH
875 if process:
876 return self.process_ie_result(ie_result, download, extra_info)
877 else:
878 return ie_result
773f291d
S
879 except GeoRestrictedError as e:
880 msg = e.msg
881 if e.countries:
882 msg += '\nThis video is available in %s.' % ', '.join(
883 map(ISO3166Utils.short2full, e.countries))
884 msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
885 self.report_error(msg)
886 break
fb043a6e 887 except ExtractorError as e: # An error we somewhat expected
2c74e6fa 888 self.report_error(compat_str(e), e.format_traceback())
8222d8de 889 break
d3e5bbf4
PH
890 except MaxDownloadsReached:
891 raise
8222d8de
JMF
892 except Exception as e:
893 if self.params.get('ignoreerrors', False):
9b9c5355 894 self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
8222d8de
JMF
895 break
896 else:
897 raise
898 else:
1a489545 899 self.report_error('no suitable InfoExtractor for URL %s' % url)
fe7e0c98 900
ea38e55f
PH
901 def add_default_extra_info(self, ie_result, ie, url):
902 self.add_extra_info(ie_result, {
903 'extractor': ie.IE_NAME,
904 'webpage_url': url,
905 'webpage_url_basename': url_basename(url),
906 'extractor_key': ie.ie_key(),
907 })
908
8222d8de
JMF
909 def process_ie_result(self, ie_result, download=True, extra_info={}):
910 """
911 Take the result of the ie(may be modified) and resolve all unresolved
912 references (URLs, playlist items).
913
914 It will also download the videos if 'download'.
915 Returns the resolved ie_result.
916 """
e8ee972c
PH
917 result_type = ie_result.get('_type', 'video')
918
057a5206 919 if result_type in ('url', 'url_transparent'):
134c6ea8 920 ie_result['url'] = sanitize_url(ie_result['url'])
057a5206 921 extract_flat = self.params.get('extract_flat', False)
3089bc74
S
922 if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
923 or extract_flat is True):
d06daf23
S
924 self.__forced_printings(
925 ie_result, self.prepare_filename(ie_result),
926 incomplete=True)
e8ee972c
PH
927 return ie_result
928
8222d8de 929 if result_type == 'video':
b6c45014 930 self.add_extra_info(ie_result, extra_info)
feee2ecf 931 return self.process_video_result(ie_result, download=download)
8222d8de
JMF
932 elif result_type == 'url':
933 # We have to add extra_info to the results because it may be
934 # contained in a playlist
935 return self.extract_info(ie_result['url'],
936 download,
937 ie_key=ie_result.get('ie_key'),
938 extra_info=extra_info)
7fc3fa05
PH
939 elif result_type == 'url_transparent':
940 # Use the information from the embedding page
941 info = self.extract_info(
942 ie_result['url'], ie_key=ie_result.get('ie_key'),
943 extra_info=extra_info, download=False, process=False)
944
1640eb09
S
945 # extract_info may return None when ignoreerrors is enabled and
946 # extraction failed with an error, don't crash and return early
947 # in this case
948 if not info:
949 return info
950
412c617d
PH
951 force_properties = dict(
952 (k, v) for k, v in ie_result.items() if v is not None)
0396806f 953 for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
412c617d
PH
954 if f in force_properties:
955 del force_properties[f]
956 new_result = info.copy()
957 new_result.update(force_properties)
7fc3fa05 958
0563f7ac
S
959 # Extracted info may not be a video result (i.e.
960 # info.get('_type', 'video') != video) but rather an url or
961 # url_transparent. In such cases outer metadata (from ie_result)
962 # should be propagated to inner one (info). For this to happen
963 # _type of info should be overridden with url_transparent. This
067aa17e 964 # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
0563f7ac
S
965 if new_result.get('_type') == 'url':
966 new_result['_type'] = 'url_transparent'
7fc3fa05
PH
967
968 return self.process_ie_result(
969 new_result, download=download, extra_info=extra_info)
40fcba5e 970 elif result_type in ('playlist', 'multi_video'):
8222d8de 971 # We process each entry in the playlist
d800609c 972 playlist = ie_result.get('title') or ie_result.get('id')
6febd1c1 973 self.to_screen('[download] Downloading playlist: %s' % playlist)
8222d8de
JMF
974
975 playlist_results = []
976
8222d8de 977 playliststart = self.params.get('playliststart', 1) - 1
d800609c 978 playlistend = self.params.get('playlistend')
a19fd00c 979 # For backwards compatibility, interpret -1 as whole list
8222d8de 980 if playlistend == -1:
a19fd00c 981 playlistend = None
8222d8de 982
d800609c 983 playlistitems_str = self.params.get('playlist_items')
c14e88f0
PH
984 playlistitems = None
985 if playlistitems_str is not None:
986 def iter_playlistitems(format):
987 for string_segment in format.split(','):
988 if '-' in string_segment:
989 start, end = string_segment.split('-')
990 for item in range(int(start), int(end) + 1):
991 yield int(item)
992 else:
993 yield int(string_segment)
cd6fc19e 994 playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
c14e88f0 995
b82f815f 996 ie_entries = ie_result['entries']
7e85e872
S
997
998 def make_playlistitems_entries(list_ie_entries):
999 num_entries = len(list_ie_entries)
1000 return [
1001 list_ie_entries[i - 1] for i in playlistitems
1002 if -num_entries <= i - 1 < num_entries]
1003
1004 def report_download(num_entries):
1005 self.to_screen(
1006 '[%s] playlist %s: Downloading %d videos' %
1007 (ie_result['extractor'], playlist, num_entries))
1008
b82f815f
PH
1009 if isinstance(ie_entries, list):
1010 n_all_entries = len(ie_entries)
c14e88f0 1011 if playlistitems:
7e85e872 1012 entries = make_playlistitems_entries(ie_entries)
c14e88f0
PH
1013 else:
1014 entries = ie_entries[playliststart:playlistend]
b7ab0590
PH
1015 n_entries = len(entries)
1016 self.to_screen(
611c1dd9 1017 '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
b7ab0590 1018 (ie_result['extractor'], playlist, n_all_entries, n_entries))
b82f815f 1019 elif isinstance(ie_entries, PagedList):
c14e88f0
PH
1020 if playlistitems:
1021 entries = []
1022 for item in playlistitems:
1023 entries.extend(ie_entries.getslice(
1024 item - 1, item
1025 ))
1026 else:
1027 entries = ie_entries.getslice(
1028 playliststart, playlistend)
b7ab0590 1029 n_entries = len(entries)
7e85e872 1030 report_download(n_entries)
b82f815f 1031 else: # iterable
c14e88f0 1032 if playlistitems:
5871ebac
S
1033 entries = make_playlistitems_entries(list(itertools.islice(
1034 ie_entries, 0, max(playlistitems))))
c14e88f0
PH
1035 else:
1036 entries = list(itertools.islice(
1037 ie_entries, playliststart, playlistend))
b82f815f 1038 n_entries = len(entries)
7e85e872 1039 report_download(n_entries)
8222d8de 1040
ff815fe6
MS
1041 if self.params.get('playlistreverse', False):
1042 entries = entries[::-1]
1043
75822ca7
TC
1044 if self.params.get('playlistrandom', False):
1045 random.shuffle(entries)
1046
0016b84e
S
1047 x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
1048
fe7e0c98 1049 for i, entry in enumerate(entries, 1):
734ea11e 1050 self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
0016b84e
S
1051 # This __x_forwarded_for_ip thing is a bit ugly but requires
1052 # minimal changes
1053 if x_forwarded_for:
1054 entry['__x_forwarded_for_ip'] = x_forwarded_for
8222d8de 1055 extra = {
c6b4132a 1056 'n_entries': n_entries,
fe7e0c98 1057 'playlist': playlist,
a1cf99d0
PH
1058 'playlist_id': ie_result.get('id'),
1059 'playlist_title': ie_result.get('title'),
3961c6cb
S
1060 'playlist_uploader': ie_result.get('uploader'),
1061 'playlist_uploader_id': ie_result.get('uploader_id'),
de1121d7 1062 'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
b6c45014 1063 'extractor': ie_result['extractor'],
9103bbc5 1064 'webpage_url': ie_result['webpage_url'],
29eb5174 1065 'webpage_url_basename': url_basename(ie_result['webpage_url']),
be97abc2 1066 'extractor_key': ie_result['extractor_key'],
fe7e0c98 1067 }
7012b23c 1068
442c37b7 1069 reason = self._match_entry(entry, incomplete=True)
7012b23c 1070 if reason is not None:
6febd1c1 1071 self.to_screen('[download] ' + reason)
7012b23c
PH
1072 continue
1073
8222d8de
JMF
1074 entry_result = self.process_ie_result(entry,
1075 download=download,
1076 extra_info=extra)
1077 playlist_results.append(entry_result)
1078 ie_result['entries'] = playlist_results
371c3b79 1079 self.to_screen('[download] Finished downloading playlist: %s' % playlist)
8222d8de
JMF
1080 return ie_result
1081 elif result_type == 'compat_list':
c9bf4114
PH
1082 self.report_warning(
1083 'Extractor %s returned a compat_list result. '
1084 'It needs to be updated.' % ie_result.get('extractor'))
5f6a1245 1085
8222d8de 1086 def _fixup(r):
9e1a5b84
JW
1087 self.add_extra_info(
1088 r,
9103bbc5
JMF
1089 {
1090 'extractor': ie_result['extractor'],
1091 'webpage_url': ie_result['webpage_url'],
29eb5174 1092 'webpage_url_basename': url_basename(ie_result['webpage_url']),
be97abc2 1093 'extractor_key': ie_result['extractor_key'],
9e1a5b84
JW
1094 }
1095 )
8222d8de
JMF
1096 return r
1097 ie_result['entries'] = [
b6c45014 1098 self.process_ie_result(_fixup(r), download, extra_info)
8222d8de
JMF
1099 for r in ie_result['entries']
1100 ]
1101 return ie_result
1102 else:
1103 raise Exception('Invalid result type: %s' % result_type)
1104
67134eab
JMF
1105 def _build_format_filter(self, filter_spec):
1106 " Returns a function to filter the formats according to the filter_spec "
083c9df9
PH
1107
1108 OPERATORS = {
1109 '<': operator.lt,
1110 '<=': operator.le,
1111 '>': operator.gt,
1112 '>=': operator.ge,
1113 '=': operator.eq,
1114 '!=': operator.ne,
1115 }
67134eab 1116 operator_rex = re.compile(r'''(?x)\s*
a03a3c80 1117 (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
083c9df9
PH
1118 \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
1119 (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
67134eab 1120 $
083c9df9 1121 ''' % '|'.join(map(re.escape, OPERATORS.keys())))
67134eab 1122 m = operator_rex.search(filter_spec)
9ddb6925
S
1123 if m:
1124 try:
1125 comparison_value = int(m.group('value'))
1126 except ValueError:
1127 comparison_value = parse_filesize(m.group('value'))
1128 if comparison_value is None:
1129 comparison_value = parse_filesize(m.group('value') + 'B')
1130 if comparison_value is None:
1131 raise ValueError(
1132 'Invalid value %r in format specification %r' % (
67134eab 1133 m.group('value'), filter_spec))
9ddb6925
S
1134 op = OPERATORS[m.group('op')]
1135
083c9df9 1136 if not m:
9ddb6925
S
1137 STR_OPERATORS = {
1138 '=': operator.eq,
10d33b34
YCH
1139 '^=': lambda attr, value: attr.startswith(value),
1140 '$=': lambda attr, value: attr.endswith(value),
1141 '*=': lambda attr, value: value in attr,
9ddb6925 1142 }
67134eab 1143 str_operator_rex = re.compile(r'''(?x)
d5aacf9a 1144 \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id)
2cc779f4 1145 \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
b0df5223 1146 \s*(?P<value>[a-zA-Z0-9._-]+)
67134eab 1147 \s*$
9ddb6925 1148 ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
67134eab 1149 m = str_operator_rex.search(filter_spec)
9ddb6925
S
1150 if m:
1151 comparison_value = m.group('value')
2cc779f4
S
1152 str_op = STR_OPERATORS[m.group('op')]
1153 if m.group('negation'):
e118a879 1154 op = lambda attr, value: not str_op(attr, value)
2cc779f4
S
1155 else:
1156 op = str_op
083c9df9 1157
9ddb6925 1158 if not m:
67134eab 1159 raise ValueError('Invalid filter specification %r' % filter_spec)
083c9df9
PH
1160
1161 def _filter(f):
1162 actual_value = f.get(m.group('key'))
1163 if actual_value is None:
1164 return m.group('none_inclusive')
1165 return op(actual_value, comparison_value)
67134eab
JMF
1166 return _filter
1167
0017d9ad 1168 def _default_format_spec(self, info_dict, download=True):
0017d9ad 1169
af0f7428
S
1170 def can_merge():
1171 merger = FFmpegMergerPP(self)
1172 return merger.available and merger.can_merge()
1173
1174 def prefer_best():
0017d9ad 1175 if self.params.get('simulate', False):
af0f7428 1176 return False
0017d9ad 1177 if not download:
0017d9ad 1178 return False
af0f7428
S
1179 if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
1180 return True
0017d9ad 1181 if info_dict.get('is_live'):
af0f7428
S
1182 return True
1183 if not can_merge():
1184 return True
1185 return False
1186
1187 req_format_list = ['bestvideo+bestaudio', 'best']
1188 if prefer_best():
1189 req_format_list.reverse()
0017d9ad
S
1190 return '/'.join(req_format_list)
1191
67134eab
JMF
1192 def build_format_selector(self, format_spec):
1193 def syntax_error(note, start):
1194 message = (
1195 'Invalid format specification: '
1196 '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
1197 return SyntaxError(message)
1198
1199 PICKFIRST = 'PICKFIRST'
1200 MERGE = 'MERGE'
1201 SINGLE = 'SINGLE'
0130afb7 1202 GROUP = 'GROUP'
67134eab
JMF
1203 FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
1204
1205 def _parse_filter(tokens):
1206 filter_parts = []
1207 for type, string, start, _, _ in tokens:
1208 if type == tokenize.OP and string == ']':
1209 return ''.join(filter_parts)
1210 else:
1211 filter_parts.append(string)
1212
232541df 1213 def _remove_unused_ops(tokens):
17cc1534 1214 # Remove operators that we don't use and join them with the surrounding strings
232541df
JMF
1215 # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
1216 ALLOWED_OPS = ('/', '+', ',', '(', ')')
1217 last_string, last_start, last_end, last_line = None, None, None, None
1218 for type, string, start, end, line in tokens:
1219 if type == tokenize.OP and string == '[':
1220 if last_string:
1221 yield tokenize.NAME, last_string, last_start, last_end, last_line
1222 last_string = None
1223 yield type, string, start, end, line
1224 # everything inside brackets will be handled by _parse_filter
1225 for type, string, start, end, line in tokens:
1226 yield type, string, start, end, line
1227 if type == tokenize.OP and string == ']':
1228 break
1229 elif type == tokenize.OP and string in ALLOWED_OPS:
1230 if last_string:
1231 yield tokenize.NAME, last_string, last_start, last_end, last_line
1232 last_string = None
1233 yield type, string, start, end, line
1234 elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
1235 if not last_string:
1236 last_string = string
1237 last_start = start
1238 last_end = end
1239 else:
1240 last_string += string
1241 if last_string:
1242 yield tokenize.NAME, last_string, last_start, last_end, last_line
1243
cf2ac6df 1244 def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
67134eab
JMF
1245 selectors = []
1246 current_selector = None
1247 for type, string, start, _, _ in tokens:
1248 # ENCODING is only defined in python 3.x
1249 if type == getattr(tokenize, 'ENCODING', None):
1250 continue
1251 elif type in [tokenize.NAME, tokenize.NUMBER]:
1252 current_selector = FormatSelector(SINGLE, string, [])
1253 elif type == tokenize.OP:
cf2ac6df
JMF
1254 if string == ')':
1255 if not inside_group:
1256 # ')' will be handled by the parentheses group
1257 tokens.restore_last_token()
67134eab 1258 break
cf2ac6df 1259 elif inside_merge and string in ['/', ',']:
0130afb7
JMF
1260 tokens.restore_last_token()
1261 break
cf2ac6df
JMF
1262 elif inside_choice and string == ',':
1263 tokens.restore_last_token()
1264 break
1265 elif string == ',':
0a31a350
JMF
1266 if not current_selector:
1267 raise syntax_error('"," must follow a format selector', start)
67134eab
JMF
1268 selectors.append(current_selector)
1269 current_selector = None
1270 elif string == '/':
d96d604e
JMF
1271 if not current_selector:
1272 raise syntax_error('"/" must follow a format selector', start)
67134eab 1273 first_choice = current_selector
cf2ac6df 1274 second_choice = _parse_format_selection(tokens, inside_choice=True)
f5f4a27a 1275 current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
67134eab
JMF
1276 elif string == '[':
1277 if not current_selector:
1278 current_selector = FormatSelector(SINGLE, 'best', [])
1279 format_filter = _parse_filter(tokens)
1280 current_selector.filters.append(format_filter)
0130afb7
JMF
1281 elif string == '(':
1282 if current_selector:
1283 raise syntax_error('Unexpected "("', start)
cf2ac6df
JMF
1284 group = _parse_format_selection(tokens, inside_group=True)
1285 current_selector = FormatSelector(GROUP, group, [])
67134eab 1286 elif string == '+':
d03cfdce 1287 if not current_selector:
1288 raise syntax_error('Unexpected "+"', start)
1289 selector_1 = current_selector
1290 selector_2 = _parse_format_selection(tokens, inside_merge=True)
1291 if not selector_2:
1292 raise syntax_error('Expected a selector', start)
1293 current_selector = FormatSelector(MERGE, (selector_1, selector_2), [])
67134eab
JMF
1294 else:
1295 raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
1296 elif type == tokenize.ENDMARKER:
1297 break
1298 if current_selector:
1299 selectors.append(current_selector)
1300 return selectors
1301
1302 def _build_selector_function(selector):
1303 if isinstance(selector, list):
1304 fs = [_build_selector_function(s) for s in selector]
1305
317f7ab6 1306 def selector_function(ctx):
67134eab 1307 for f in fs:
317f7ab6 1308 for format in f(ctx):
67134eab
JMF
1309 yield format
1310 return selector_function
0130afb7
JMF
1311 elif selector.type == GROUP:
1312 selector_function = _build_selector_function(selector.selector)
67134eab
JMF
1313 elif selector.type == PICKFIRST:
1314 fs = [_build_selector_function(s) for s in selector.selector]
1315
317f7ab6 1316 def selector_function(ctx):
67134eab 1317 for f in fs:
317f7ab6 1318 picked_formats = list(f(ctx))
67134eab
JMF
1319 if picked_formats:
1320 return picked_formats
1321 return []
1322 elif selector.type == SINGLE:
1323 format_spec = selector.selector
1324
317f7ab6
S
1325 def selector_function(ctx):
1326 formats = list(ctx['formats'])
bb8e5536
JMF
1327 if not formats:
1328 return
5acfa126
JMF
1329 if format_spec == 'all':
1330 for f in formats:
1331 yield f
1332 elif format_spec in ['best', 'worst', None]:
67134eab
JMF
1333 format_idx = 0 if format_spec == 'worst' else -1
1334 audiovideo_formats = [
1335 f for f in formats
1336 if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
1337 if audiovideo_formats:
1338 yield audiovideo_formats[format_idx]
317f7ab6
S
1339 # for extractors with incomplete formats (audio only (soundcloud)
1340 # or video only (imgur)) we will fallback to best/worst
1341 # {video,audio}-only format
1342 elif ctx['incomplete_formats']:
67134eab
JMF
1343 yield formats[format_idx]
1344 elif format_spec == 'bestaudio':
1345 audio_formats = [
1346 f for f in formats
1347 if f.get('vcodec') == 'none']
1348 if audio_formats:
1349 yield audio_formats[-1]
1350 elif format_spec == 'worstaudio':
1351 audio_formats = [
1352 f for f in formats
1353 if f.get('vcodec') == 'none']
1354 if audio_formats:
1355 yield audio_formats[0]
1356 elif format_spec == 'bestvideo':
1357 video_formats = [
1358 f for f in formats
1359 if f.get('acodec') == 'none']
1360 if video_formats:
1361 yield video_formats[-1]
1362 elif format_spec == 'worstvideo':
1363 video_formats = [
1364 f for f in formats
1365 if f.get('acodec') == 'none']
1366 if video_formats:
1367 yield video_formats[0]
1368 else:
1369 extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
1370 if format_spec in extensions:
1371 filter_f = lambda f: f['ext'] == format_spec
1372 else:
1373 filter_f = lambda f: f['format_id'] == format_spec
1374 matches = list(filter(filter_f, formats))
1375 if matches:
1376 yield matches[-1]
1377 elif selector.type == MERGE:
d03cfdce 1378 def _merge(formats_pair):
1379 format_1, format_2 = formats_pair
1380
1381 formats_info = []
1382 formats_info.extend(format_1.get('requested_formats', (format_1,)))
1383 formats_info.extend(format_2.get('requested_formats', (format_2,)))
1384
1385 video_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('vcodec') != 'none']
1386 audio_fmts = [fmt_info for fmt_info in formats_info if fmt_info.get('acodec') != 'none']
1387
1388 the_only_video = video_fmts[0] if len(video_fmts) == 1 else None
1389 the_only_audio = audio_fmts[0] if len(audio_fmts) == 1 else None
1390
1391 output_ext = self.params.get('merge_output_format')
1392 if not output_ext:
1393 if the_only_video:
1394 output_ext = the_only_video['ext']
1395 elif the_only_audio and not video_fmts:
1396 output_ext = the_only_audio['ext']
1397 else:
1398 output_ext = 'mkv'
1399
1400 new_dict = {
67134eab 1401 'requested_formats': formats_info,
d03cfdce 1402 'format': '+'.join(fmt_info.get('format') for fmt_info in formats_info),
1403 'format_id': '+'.join(fmt_info.get('format_id') for fmt_info in formats_info),
67134eab
JMF
1404 'ext': output_ext,
1405 }
d03cfdce 1406
1407 if the_only_video:
1408 new_dict.update({
1409 'width': the_only_video.get('width'),
1410 'height': the_only_video.get('height'),
1411 'resolution': the_only_video.get('resolution'),
1412 'fps': the_only_video.get('fps'),
1413 'vcodec': the_only_video.get('vcodec'),
1414 'vbr': the_only_video.get('vbr'),
1415 'stretched_ratio': the_only_video.get('stretched_ratio'),
1416 })
1417
1418 if the_only_audio:
1419 new_dict.update({
1420 'acodec': the_only_audio.get('acodec'),
1421 'abr': the_only_audio.get('abr'),
1422 })
1423
1424 return new_dict
1425
1426 selector_1, selector_2 = map(_build_selector_function, selector.selector)
083c9df9 1427
317f7ab6
S
1428 def selector_function(ctx):
1429 for pair in itertools.product(
d03cfdce 1430 selector_1(copy.deepcopy(ctx)), selector_2(copy.deepcopy(ctx))):
67134eab 1431 yield _merge(pair)
083c9df9 1432
67134eab 1433 filters = [self._build_format_filter(f) for f in selector.filters]
083c9df9 1434
317f7ab6
S
1435 def final_selector(ctx):
1436 ctx_copy = copy.deepcopy(ctx)
67134eab 1437 for _filter in filters:
317f7ab6
S
1438 ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
1439 return selector_function(ctx_copy)
67134eab 1440 return final_selector
083c9df9 1441
67134eab 1442 stream = io.BytesIO(format_spec.encode('utf-8'))
0130afb7 1443 try:
232541df 1444 tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
0130afb7
JMF
1445 except tokenize.TokenError:
1446 raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
1447
1448 class TokenIterator(object):
1449 def __init__(self, tokens):
1450 self.tokens = tokens
1451 self.counter = 0
1452
1453 def __iter__(self):
1454 return self
1455
1456 def __next__(self):
1457 if self.counter >= len(self.tokens):
1458 raise StopIteration()
1459 value = self.tokens[self.counter]
1460 self.counter += 1
1461 return value
1462
1463 next = __next__
1464
1465 def restore_last_token(self):
1466 self.counter -= 1
1467
1468 parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
67134eab 1469 return _build_selector_function(parsed_selector)
a9c58ad9 1470
e5660ee6
JMF
1471 def _calc_headers(self, info_dict):
1472 res = std_headers.copy()
1473
1474 add_headers = info_dict.get('http_headers')
1475 if add_headers:
1476 res.update(add_headers)
1477
1478 cookies = self._calc_cookies(info_dict)
1479 if cookies:
1480 res['Cookie'] = cookies
1481
0016b84e
S
1482 if 'X-Forwarded-For' not in res:
1483 x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
1484 if x_forwarded_for_ip:
1485 res['X-Forwarded-For'] = x_forwarded_for_ip
1486
e5660ee6
JMF
1487 return res
1488
1489 def _calc_cookies(self, info_dict):
5c2266df 1490 pr = sanitized_Request(info_dict['url'])
e5660ee6 1491 self.cookiejar.add_cookie_header(pr)
662435f7 1492 return pr.get_header('Cookie')
e5660ee6 1493
dd82ffea
JMF
1494 def process_video_result(self, info_dict, download=True):
1495 assert info_dict.get('_type', 'video') == 'video'
1496
bec1fad2
PH
1497 if 'id' not in info_dict:
1498 raise ExtractorError('Missing "id" field in extractor result')
1499 if 'title' not in info_dict:
1500 raise ExtractorError('Missing "title" field in extractor result')
1501
c9969434
S
1502 def report_force_conversion(field, field_not, conversion):
1503 self.report_warning(
1504 '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
1505 % (field, field_not, conversion))
1506
1507 def sanitize_string_field(info, string_field):
1508 field = info.get(string_field)
1509 if field is None or isinstance(field, compat_str):
1510 return
1511 report_force_conversion(string_field, 'a string', 'string')
1512 info[string_field] = compat_str(field)
1513
1514 def sanitize_numeric_fields(info):
1515 for numeric_field in self._NUMERIC_FIELDS:
1516 field = info.get(numeric_field)
1517 if field is None or isinstance(field, compat_numeric_types):
1518 continue
1519 report_force_conversion(numeric_field, 'numeric', 'int')
1520 info[numeric_field] = int_or_none(field)
1521
1522 sanitize_string_field(info_dict, 'id')
1523 sanitize_numeric_fields(info_dict)
be6217b2 1524
dd82ffea
JMF
1525 if 'playlist' not in info_dict:
1526 # It isn't part of a playlist
1527 info_dict['playlist'] = None
1528 info_dict['playlist_index'] = None
1529
d5519808 1530 thumbnails = info_dict.get('thumbnails')
cfb56d1a
PH
1531 if thumbnails is None:
1532 thumbnail = info_dict.get('thumbnail')
1533 if thumbnail:
a7a14d95 1534 info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
d5519808 1535 if thumbnails:
be6d7229 1536 thumbnails.sort(key=lambda t: (
d37708fc
RA
1537 t.get('preference') if t.get('preference') is not None else -1,
1538 t.get('width') if t.get('width') is not None else -1,
1539 t.get('height') if t.get('height') is not None else -1,
1540 t.get('id') if t.get('id') is not None else '', t.get('url')))
f6c24009 1541 for i, t in enumerate(thumbnails):
dcf77cf1 1542 t['url'] = sanitize_url(t['url'])
9603e8a7 1543 if t.get('width') and t.get('height'):
d5519808 1544 t['resolution'] = '%dx%d' % (t['width'], t['height'])
f6c24009
PH
1545 if t.get('id') is None:
1546 t['id'] = '%d' % i
d5519808 1547
b7b72db9 1548 if self.params.get('list_thumbnails'):
1549 self.list_thumbnails(info_dict)
1550 return
1551
536a55da
S
1552 thumbnail = info_dict.get('thumbnail')
1553 if thumbnail:
1554 info_dict['thumbnail'] = sanitize_url(thumbnail)
1555 elif thumbnails:
d5519808
PH
1556 info_dict['thumbnail'] = thumbnails[-1]['url']
1557
c9ae7b95 1558 if 'display_id' not in info_dict and 'id' in info_dict:
0afef30b
PH
1559 info_dict['display_id'] = info_dict['id']
1560
955c4514 1561 if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
a55e36f4
S
1562 # Working around out-of-range timestamp values (e.g. negative ones on Windows,
1563 # see http://bugs.python.org/issue1646728)
1564 try:
1565 upload_date = datetime.datetime.utcfromtimestamp(info_dict['timestamp'])
1566 info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
1567 except (ValueError, OverflowError, OSError):
1568 pass
9d2ecdbc 1569
33d2fc2f
S
1570 # Auto generate title fields corresponding to the *_number fields when missing
1571 # in order to always have clean titles. This is very common for TV series.
1572 for field in ('chapter', 'season', 'episode'):
1573 if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
1574 info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
1575
05108a49
S
1576 for cc_kind in ('subtitles', 'automatic_captions'):
1577 cc = info_dict.get(cc_kind)
1578 if cc:
1579 for _, subtitle in cc.items():
1580 for subtitle_format in subtitle:
1581 if subtitle_format.get('url'):
1582 subtitle_format['url'] = sanitize_url(subtitle_format['url'])
1583 if subtitle_format.get('ext') is None:
1584 subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
1585
1586 automatic_captions = info_dict.get('automatic_captions')
4bba3716 1587 subtitles = info_dict.get('subtitles')
4bba3716 1588
a504ced0 1589 if self.params.get('listsubtitles', False):
360e1ca5 1590 if 'automatic_captions' in info_dict:
05108a49
S
1591 self.list_subtitles(
1592 info_dict['id'], automatic_captions, 'automatic captions')
4bba3716 1593 self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
a504ced0 1594 return
05108a49 1595
360e1ca5 1596 info_dict['requested_subtitles'] = self.process_subtitles(
05108a49 1597 info_dict['id'], subtitles, automatic_captions)
a504ced0 1598
dd82ffea
JMF
1599 # We now pick which formats have to be downloaded
1600 if info_dict.get('formats') is None:
1601 # There's only one format available
1602 formats = [info_dict]
1603 else:
1604 formats = info_dict['formats']
1605
db95dc13
PH
1606 if not formats:
1607 raise ExtractorError('No video formats found!')
1608
73af5cc8
S
1609 def is_wellformed(f):
1610 url = f.get('url')
a5ac0c47 1611 if not url:
73af5cc8
S
1612 self.report_warning(
1613 '"url" field is missing or empty - skipping format, '
1614 'there is an error in extractor')
a5ac0c47
S
1615 return False
1616 if isinstance(url, bytes):
1617 sanitize_string_field(f, 'url')
1618 return True
73af5cc8
S
1619
1620 # Filter out malformed formats for better extraction robustness
1621 formats = list(filter(is_wellformed, formats))
1622
181c7053
S
1623 formats_dict = {}
1624
dd82ffea 1625 # We check that all the formats have the format and format_id fields
db95dc13 1626 for i, format in enumerate(formats):
c9969434
S
1627 sanitize_string_field(format, 'format_id')
1628 sanitize_numeric_fields(format)
dcf77cf1 1629 format['url'] = sanitize_url(format['url'])
e74e3b63 1630 if not format.get('format_id'):
8016c922 1631 format['format_id'] = compat_str(i)
e2effb08
S
1632 else:
1633 # Sanitize format_id from characters used in format selector expression
ec85ded8 1634 format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
181c7053
S
1635 format_id = format['format_id']
1636 if format_id not in formats_dict:
1637 formats_dict[format_id] = []
1638 formats_dict[format_id].append(format)
1639
1640 # Make sure all formats have unique format_id
1641 for format_id, ambiguous_formats in formats_dict.items():
1642 if len(ambiguous_formats) > 1:
1643 for i, format in enumerate(ambiguous_formats):
1644 format['format_id'] = '%s-%d' % (format_id, i)
1645
1646 for i, format in enumerate(formats):
8c51aa65 1647 if format.get('format') is None:
6febd1c1 1648 format['format'] = '{id} - {res}{note}'.format(
8c51aa65
JMF
1649 id=format['format_id'],
1650 res=self.format_resolution(format),
6febd1c1 1651 note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
8c51aa65 1652 )
c1002e96 1653 # Automatically determine file extension if missing
5b1d8575 1654 if format.get('ext') is None:
cce929ea 1655 format['ext'] = determine_ext(format['url']).lower()
b5559424
S
1656 # Automatically determine protocol if missing (useful for format
1657 # selection purposes)
6f0be937 1658 if format.get('protocol') is None:
b5559424 1659 format['protocol'] = determine_protocol(format)
e5660ee6
JMF
1660 # Add HTTP headers, so that external programs can use them from the
1661 # json output
1662 full_format_info = info_dict.copy()
1663 full_format_info.update(format)
1664 format['http_headers'] = self._calc_headers(full_format_info)
0016b84e
S
1665 # Remove private housekeeping stuff
1666 if '__x_forwarded_for_ip' in info_dict:
1667 del info_dict['__x_forwarded_for_ip']
dd82ffea 1668
4bcc7bd1 1669 # TODO Central sorting goes here
99e206d5 1670
f89197d7 1671 if formats[0] is not info_dict:
b3d9ef88
JMF
1672 # only set the 'formats' fields if the original info_dict list them
1673 # otherwise we end up with a circular reference, the first (and unique)
f89197d7 1674 # element in the 'formats' field in info_dict is info_dict itself,
dfb1b146 1675 # which can't be exported to json
b3d9ef88 1676 info_dict['formats'] = formats
cfb56d1a 1677 if self.params.get('listformats'):
bfaae0a7 1678 self.list_formats(info_dict)
1679 return
1680
de3ef3ed 1681 req_format = self.params.get('format')
a9c58ad9 1682 if req_format is None:
0017d9ad
S
1683 req_format = self._default_format_spec(info_dict, download=download)
1684 if self.params.get('verbose'):
1685 self.to_stdout('[debug] Default format spec: %s' % req_format)
1686
5acfa126 1687 format_selector = self.build_format_selector(req_format)
317f7ab6
S
1688
1689 # While in format selection we may need to have an access to the original
1690 # format set in order to calculate some metrics or do some processing.
1691 # For now we need to be able to guess whether original formats provided
1692 # by extractor are incomplete or not (i.e. whether extractor provides only
1693 # video-only or audio-only formats) for proper formats selection for
1694 # extractors with such incomplete formats (see
067aa17e 1695 # https://github.com/ytdl-org/youtube-dl/pull/5556).
317f7ab6
S
1696 # Since formats may be filtered during format selection and may not match
1697 # the original formats the results may be incorrect. Thus original formats
1698 # or pre-calculated metrics should be passed to format selection routines
1699 # as well.
1700 # We will pass a context object containing all necessary additional data
1701 # instead of just formats.
1702 # This fixes incorrect format selection issue (see
067aa17e 1703 # https://github.com/ytdl-org/youtube-dl/issues/10083).
2e221ca3 1704 incomplete_formats = (
317f7ab6 1705 # All formats are video-only or
3089bc74 1706 all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
317f7ab6 1707 # all formats are audio-only
3089bc74 1708 or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
317f7ab6
S
1709
1710 ctx = {
1711 'formats': formats,
1712 'incomplete_formats': incomplete_formats,
1713 }
1714
1715 formats_to_download = list(format_selector(ctx))
dd82ffea 1716 if not formats_to_download:
6febd1c1 1717 raise ExtractorError('requested format not available',
78a3a9f8 1718 expected=True)
dd82ffea
JMF
1719
1720 if download:
1721 if len(formats_to_download) > 1:
6febd1c1 1722 self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
dd82ffea
JMF
1723 for format in formats_to_download:
1724 new_info = dict(info_dict)
1725 new_info.update(format)
1726 self.process_info(new_info)
1727 # We update the info dict with the best quality format (backwards compatibility)
1728 info_dict.update(formats_to_download[-1])
1729 return info_dict
1730
98c70d6f 1731 def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
a504ced0 1732 """Select the requested subtitles and their format"""
98c70d6f
JMF
1733 available_subs = {}
1734 if normal_subtitles and self.params.get('writesubtitles'):
1735 available_subs.update(normal_subtitles)
1736 if automatic_captions and self.params.get('writeautomaticsub'):
1737 for lang, cap_info in automatic_captions.items():
360e1ca5
JMF
1738 if lang not in available_subs:
1739 available_subs[lang] = cap_info
1740
4d171848
JMF
1741 if (not self.params.get('writesubtitles') and not
1742 self.params.get('writeautomaticsub') or not
1743 available_subs):
1744 return None
a504ced0
JMF
1745
1746 if self.params.get('allsubtitles', False):
1747 requested_langs = available_subs.keys()
1748 else:
1749 if self.params.get('subtitleslangs', False):
1750 requested_langs = self.params.get('subtitleslangs')
1751 elif 'en' in available_subs:
1752 requested_langs = ['en']
1753 else:
1754 requested_langs = [list(available_subs.keys())[0]]
1755
1756 formats_query = self.params.get('subtitlesformat', 'best')
1757 formats_preference = formats_query.split('/') if formats_query else []
1758 subs = {}
1759 for lang in requested_langs:
1760 formats = available_subs.get(lang)
1761 if formats is None:
1762 self.report_warning('%s subtitles not available for %s' % (lang, video_id))
1763 continue
a504ced0
JMF
1764 for ext in formats_preference:
1765 if ext == 'best':
1766 f = formats[-1]
1767 break
1768 matches = list(filter(lambda f: f['ext'] == ext, formats))
1769 if matches:
1770 f = matches[-1]
1771 break
1772 else:
1773 f = formats[-1]
1774 self.report_warning(
1775 'No subtitle format found matching "%s" for language %s, '
1776 'using %s' % (formats_query, lang, f['ext']))
1777 subs[lang] = f
1778 return subs
1779
d06daf23
S
1780 def __forced_printings(self, info_dict, filename, incomplete):
1781 def print_mandatory(field):
1782 if (self.params.get('force%s' % field, False)
1783 and (not incomplete or info_dict.get(field) is not None)):
1784 self.to_stdout(info_dict[field])
1785
1786 def print_optional(field):
1787 if (self.params.get('force%s' % field, False)
1788 and info_dict.get(field) is not None):
1789 self.to_stdout(info_dict[field])
1790
1791 print_mandatory('title')
1792 print_mandatory('id')
1793 if self.params.get('forceurl', False) and not incomplete:
1794 if info_dict.get('requested_formats') is not None:
1795 for f in info_dict['requested_formats']:
1796 self.to_stdout(f['url'] + f.get('play_path', ''))
1797 else:
1798 # For RTMP URLs, also include the playpath
1799 self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
1800 print_optional('thumbnail')
1801 print_optional('description')
1802 if self.params.get('forcefilename', False) and filename is not None:
1803 self.to_stdout(filename)
1804 if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
1805 self.to_stdout(formatSeconds(info_dict['duration']))
1806 print_mandatory('format')
1807 if self.params.get('forcejson', False):
1808 self.to_stdout(json.dumps(info_dict))
1809
8222d8de
JMF
1810 def process_info(self, info_dict):
1811 """Process a single resolved IE result."""
1812
1813 assert info_dict.get('_type', 'video') == 'video'
fd288278
PH
1814
1815 max_downloads = self.params.get('max_downloads')
1816 if max_downloads is not None:
1817 if self._num_downloads >= int(max_downloads):
1818 raise MaxDownloadsReached()
8222d8de 1819
d06daf23 1820 # TODO: backward compatibility, to be removed
8222d8de 1821 info_dict['fulltitle'] = info_dict['title']
8222d8de 1822
11b85ce6 1823 if 'format' not in info_dict:
8222d8de
JMF
1824 info_dict['format'] = info_dict['ext']
1825
442c37b7 1826 reason = self._match_entry(info_dict, incomplete=False)
8222d8de 1827 if reason is not None:
6febd1c1 1828 self.to_screen('[download] ' + reason)
8222d8de
JMF
1829 return
1830
fd288278 1831 self._num_downloads += 1
8222d8de 1832
e72c7e41 1833 info_dict['_filename'] = filename = self.prepare_filename(info_dict)
8222d8de
JMF
1834
1835 # Forced printings
d06daf23 1836 self.__forced_printings(info_dict, filename, incomplete=False)
8222d8de
JMF
1837
1838 # Do nothing else if in simulate mode
1839 if self.params.get('simulate', False):
1840 return
1841
1842 if filename is None:
1843 return
1844
c5c9bf0c
S
1845 def ensure_dir_exists(path):
1846 try:
1847 dn = os.path.dirname(path)
1848 if dn and not os.path.exists(dn):
1849 os.makedirs(dn)
1850 return True
1851 except (OSError, IOError) as err:
1852 self.report_error('unable to create directory ' + error_to_compat_str(err))
1853 return False
1854
1855 if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
8222d8de
JMF
1856 return
1857
1858 if self.params.get('writedescription', False):
2699da80 1859 descfn = replace_extension(filename, 'description', info_dict.get('ext'))
7b6fefc9 1860 if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
6febd1c1 1861 self.to_screen('[info] Video description is already present')
f00fd51d
JMF
1862 elif info_dict.get('description') is None:
1863 self.report_warning('There\'s no description to write.')
7b6fefc9
PH
1864 else:
1865 try:
6febd1c1 1866 self.to_screen('[info] Writing video description to: ' + descfn)
7b6fefc9
PH
1867 with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
1868 descfile.write(info_dict['description'])
7b6fefc9 1869 except (OSError, IOError):
6febd1c1 1870 self.report_error('Cannot write description file ' + descfn)
7b6fefc9 1871 return
8222d8de 1872
1fb07d10 1873 if self.params.get('writeannotations', False):
98727e12 1874 annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
7b6fefc9 1875 if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
6febd1c1 1876 self.to_screen('[info] Video annotations are already present')
ffddb112
RA
1877 elif not info_dict.get('annotations'):
1878 self.report_warning('There are no annotations to write.')
7b6fefc9
PH
1879 else:
1880 try:
6febd1c1 1881 self.to_screen('[info] Writing video annotations to: ' + annofn)
7b6fefc9
PH
1882 with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
1883 annofile.write(info_dict['annotations'])
1884 except (KeyError, TypeError):
6febd1c1 1885 self.report_warning('There are no annotations to write.')
7b6fefc9 1886 except (OSError, IOError):
6febd1c1 1887 self.report_error('Cannot write annotations file: ' + annofn)
7b6fefc9 1888 return
1fb07d10 1889
98b69821 1890 def dl(name, info):
1891 fd = get_suitable_downloader(info, self.params)(self, self.params)
1892 for ph in self._progress_hooks:
1893 fd.add_progress_hook(ph)
1894 if self.params.get('verbose'):
1895 self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
1896 return fd.download(name, info)
1897
c4a91be7 1898 subtitles_are_requested = any([self.params.get('writesubtitles', False),
0b7f3118 1899 self.params.get('writeautomaticsub')])
c4a91be7 1900
c84dd8a9 1901 if subtitles_are_requested and info_dict.get('requested_subtitles'):
8222d8de
JMF
1902 # subtitles download errors are already managed as troubles in relevant IE
1903 # that way it will silently go on when used with unsupporting IE
c84dd8a9 1904 subtitles = info_dict['requested_subtitles']
a504ced0
JMF
1905 for sub_lang, sub_info in subtitles.items():
1906 sub_format = sub_info['ext']
824fa511 1907 sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
5ff1bc0c
RA
1908 if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
1909 self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
a504ced0 1910 else:
5ff1bc0c
RA
1911 if sub_info.get('data') is not None:
1912 try:
1913 # Use newline='' to prevent conversion of newline characters
067aa17e 1914 # See https://github.com/ytdl-org/youtube-dl/issues/10268
5ff1bc0c
RA
1915 with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
1916 subfile.write(sub_info['data'])
1917 except (OSError, IOError):
1918 self.report_error('Cannot write subtitles file ' + sub_filename)
1919 return
7b6fefc9 1920 else:
5ff1bc0c 1921 try:
98b69821 1922 dl(sub_filename, sub_info)
7627f548 1923 except (ExtractorError, IOError, OSError, ValueError,
1924 compat_urllib_error.URLError,
1925 compat_http_client.HTTPException,
1926 socket.error) as err:
5ff1bc0c
RA
1927 self.report_warning('Unable to download subtitle for "%s": %s' %
1928 (sub_lang, error_to_compat_str(err)))
1929 continue
8222d8de 1930
57df9f53
U
1931 if self.params.get('skip_download', False):
1932 if self.params.get('convertsubtitles', False):
1933 subconv = FFmpegSubtitlesConvertorPP(self, format=self.params.get('convertsubtitles'))
1934 filename_real_ext = os.path.splitext(filename)[1][1:]
1935 filename_wo_ext = (
1936 os.path.splitext(filename)[0]
1937 if filename_real_ext == info_dict['ext']
1938 else filename)
1939 afilename = '%s.%s' % (filename_wo_ext, self.params.get('convertsubtitles'))
1940 if subconv.available:
1941 info_dict.setdefault('__postprocessors', [])
1942 # info_dict['__postprocessors'].append(subconv)
1943 if os.path.exists(encodeFilename(afilename)):
f791b419
U
1944 self.to_screen(
1945 '[download] %s has already been downloaded and '
1946 'converted' % afilename)
57df9f53
U
1947 else:
1948 try:
1949 self.post_process(filename, info_dict)
1950 except (PostProcessingError) as err:
1951 self.report_error('postprocessing: %s' % str(err))
1952 return
1953
8222d8de 1954 if self.params.get('writeinfojson', False):
b29e0000 1955 infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
7b6fefc9 1956 if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
6febd1c1 1957 self.to_screen('[info] Video description metadata is already present')
7b6fefc9 1958 else:
6febd1c1 1959 self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
7b6fefc9 1960 try:
cb202fd2 1961 write_json_file(self.filter_requested_info(info_dict), infofn)
7b6fefc9 1962 except (OSError, IOError):
6febd1c1 1963 self.report_error('Cannot write metadata to JSON file ' + infofn)
7b6fefc9 1964 return
8222d8de 1965
ec82d85a 1966 self._write_thumbnails(info_dict, filename)
8222d8de
JMF
1967
1968 if not self.params.get('skip_download', False):
4340deca 1969 try:
4340deca
P
1970 if info_dict.get('requested_formats') is not None:
1971 downloaded = []
1972 success = True
d47aeb22 1973 merger = FFmpegMergerPP(self)
f740fae2 1974 if not merger.available:
4340deca
P
1975 postprocessors = []
1976 self.report_warning('You have requested multiple '
1977 'formats but ffmpeg or avconv are not installed.'
4a5a898a 1978 ' The formats won\'t be merged.')
6350728b 1979 else:
4340deca 1980 postprocessors = [merger]
81cd954a
S
1981
1982 def compatible_formats(formats):
d03cfdce 1983 # TODO: some formats actually allow this (mkv, webm, ogg, mp4), but not all of them.
1984 video_formats = [format for format in formats if format.get('vcodec') != 'none']
1985 audio_formats = [format for format in formats if format.get('acodec') != 'none']
1986 if len(video_formats) > 2 or len(audio_formats) > 2:
1987 return False
1988
81cd954a 1989 # Check extension
d03cfdce 1990 exts = set(format.get('ext') for format in formats)
1991 COMPATIBLE_EXTS = (
1992 set(('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma')),
1993 set(('webm',)),
1994 )
1995 for ext_sets in COMPATIBLE_EXTS:
1996 if ext_sets.issuperset(exts):
1997 return True
81cd954a
S
1998 # TODO: Check acodec/vcodec
1999 return False
2000
38c6902b
S
2001 filename_real_ext = os.path.splitext(filename)[1][1:]
2002 filename_wo_ext = (
2003 os.path.splitext(filename)[0]
2004 if filename_real_ext == info_dict['ext']
2005 else filename)
81cd954a 2006 requested_formats = info_dict['requested_formats']
c0dea0a7 2007 if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
38c6902b 2008 info_dict['ext'] = 'mkv'
4a5a898a
S
2009 self.report_warning(
2010 'Requested formats are incompatible for merge and will be merged into mkv.')
38c6902b
S
2011 # Ensure filename always has a correct extension for successful merge
2012 filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
5b5fbc08
JMF
2013 if os.path.exists(encodeFilename(filename)):
2014 self.to_screen(
2015 '[download] %s has already been downloaded and '
2016 'merged' % filename)
2017 else:
81cd954a 2018 for f in requested_formats:
5b5fbc08
JMF
2019 new_info = dict(info_dict)
2020 new_info.update(f)
c5c9bf0c
S
2021 fname = prepend_extension(
2022 self.prepare_filename(new_info),
2023 'f%s' % f['format_id'], new_info['ext'])
2024 if not ensure_dir_exists(fname):
2025 return
5b5fbc08
JMF
2026 downloaded.append(fname)
2027 partial_success = dl(fname, new_info)
2028 success = success and partial_success
2029 info_dict['__postprocessors'] = postprocessors
2030 info_dict['__files_to_merge'] = downloaded
4340deca
P
2031 else:
2032 # Just a single file
2033 success = dl(filename, info_dict)
2034 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
7960b056 2035 self.report_error('unable to download video data: %s' % error_to_compat_str(err))
4340deca
P
2036 return
2037 except (OSError, IOError) as err:
2038 raise UnavailableVideoError(err)
2039 except (ContentTooShortError, ) as err:
2040 self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
2041 return
8222d8de 2042
e38cafe9 2043 if success and filename != '-':
6271f1ca 2044 # Fixup content
62cd676c
PH
2045 fixup_policy = self.params.get('fixup')
2046 if fixup_policy is None:
2047 fixup_policy = 'detect_or_warn'
2048
d1e4a464
S
2049 INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
2050
6271f1ca
PH
2051 stretched_ratio = info_dict.get('stretched_ratio')
2052 if stretched_ratio is not None and stretched_ratio != 1:
6271f1ca
PH
2053 if fixup_policy == 'warn':
2054 self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
2055 info_dict['id'], stretched_ratio))
2056 elif fixup_policy == 'detect_or_warn':
2057 stretched_pp = FFmpegFixupStretchedPP(self)
2058 if stretched_pp.available:
2059 info_dict.setdefault('__postprocessors', [])
2060 info_dict['__postprocessors'].append(stretched_pp)
2061 else:
2062 self.report_warning(
d1e4a464
S
2063 '%s: Non-uniform pixel ratio (%s). %s'
2064 % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
6271f1ca 2065 else:
62cd676c
PH
2066 assert fixup_policy in ('ignore', 'never')
2067
3089bc74
S
2068 if (info_dict.get('requested_formats') is None
2069 and info_dict.get('container') == 'm4a_dash'):
62cd676c 2070 if fixup_policy == 'warn':
d1e4a464
S
2071 self.report_warning(
2072 '%s: writing DASH m4a. '
2073 'Only some players support this container.'
2074 % info_dict['id'])
62cd676c
PH
2075 elif fixup_policy == 'detect_or_warn':
2076 fixup_pp = FFmpegFixupM4aPP(self)
2077 if fixup_pp.available:
2078 info_dict.setdefault('__postprocessors', [])
2079 info_dict['__postprocessors'].append(fixup_pp)
2080 else:
2081 self.report_warning(
d1e4a464
S
2082 '%s: writing DASH m4a. '
2083 'Only some players support this container. %s'
2084 % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
62cd676c
PH
2085 else:
2086 assert fixup_policy in ('ignore', 'never')
6271f1ca 2087
3089bc74
S
2088 if (info_dict.get('protocol') == 'm3u8_native'
2089 or info_dict.get('protocol') == 'm3u8'
2090 and self.params.get('hls_prefer_native')):
f17f8651 2091 if fixup_policy == 'warn':
a02682fd 2092 self.report_warning('%s: malformed AAC bitstream detected.' % (
f17f8651 2093 info_dict['id']))
2094 elif fixup_policy == 'detect_or_warn':
2095 fixup_pp = FFmpegFixupM3u8PP(self)
2096 if fixup_pp.available:
2097 info_dict.setdefault('__postprocessors', [])
2098 info_dict['__postprocessors'].append(fixup_pp)
2099 else:
2100 self.report_warning(
a02682fd 2101 '%s: malformed AAC bitstream detected. %s'
d1e4a464 2102 % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
f17f8651 2103 else:
2104 assert fixup_policy in ('ignore', 'never')
2105
8222d8de
JMF
2106 try:
2107 self.post_process(filename, info_dict)
2108 except (PostProcessingError) as err:
6febd1c1 2109 self.report_error('postprocessing: %s' % str(err))
8222d8de 2110 return
cd58dc3e 2111 self.record_download_archive(info_dict)
8222d8de
JMF
2112
2113 def download(self, url_list):
2114 """Download a given list of URLs."""
acd69589 2115 outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
3089bc74
S
2116 if (len(url_list) > 1
2117 and outtmpl != '-'
2118 and '%' not in outtmpl
2119 and self.params.get('max_downloads') != 1):
acd69589 2120 raise SameFileError(outtmpl)
8222d8de
JMF
2121
2122 for url in url_list:
2123 try:
5f6a1245 2124 # It also downloads the videos
61aa5ba3
S
2125 res = self.extract_info(
2126 url, force_generic_extractor=self.params.get('force_generic_extractor', False))
8222d8de 2127 except UnavailableVideoError:
6febd1c1 2128 self.report_error('unable to download video')
8222d8de 2129 except MaxDownloadsReached:
6febd1c1 2130 self.to_screen('[info] Maximum number of downloaded files reached.')
8222d8de 2131 raise
63e0be34
PH
2132 else:
2133 if self.params.get('dump_single_json', False):
2134 self.to_stdout(json.dumps(res))
8222d8de
JMF
2135
2136 return self._download_retcode
2137
1dcc4c0c 2138 def download_with_info_file(self, info_filename):
31bd3925
JMF
2139 with contextlib.closing(fileinput.FileInput(
2140 [info_filename], mode='r',
2141 openhook=fileinput.hook_encoded('utf-8'))) as f:
2142 # FileInput doesn't have a read method, we can't call json.load
cb202fd2 2143 info = self.filter_requested_info(json.loads('\n'.join(f)))
d4943898
JMF
2144 try:
2145 self.process_ie_result(info, download=True)
2146 except DownloadError:
2147 webpage_url = info.get('webpage_url')
2148 if webpage_url is not None:
6febd1c1 2149 self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
d4943898
JMF
2150 return self.download([webpage_url])
2151 else:
2152 raise
2153 return self._download_retcode
1dcc4c0c 2154
cb202fd2
S
2155 @staticmethod
2156 def filter_requested_info(info_dict):
2157 return dict(
2158 (k, v) for k, v in info_dict.items()
2159 if k not in ['requested_formats', 'requested_subtitles'])
2160
8222d8de
JMF
2161 def post_process(self, filename, ie_info):
2162 """Run all the postprocessors on the given file."""
2163 info = dict(ie_info)
2164 info['filepath'] = filename
6350728b
JMF
2165 pps_chain = []
2166 if ie_info.get('__postprocessors') is not None:
2167 pps_chain.extend(ie_info['__postprocessors'])
2168 pps_chain.extend(self._pps)
2169 for pp in pps_chain:
71646e46 2170 files_to_delete = []
8222d8de 2171 try:
592e97e8 2172 files_to_delete, info = pp.run(info)
8222d8de 2173 except PostProcessingError as e:
bbcbf4d4 2174 self.report_error(e.msg)
592e97e8 2175 if files_to_delete and not self.params.get('keepvideo', False):
d03cfdce 2176 for old_filename in set(files_to_delete):
f3ff1a36 2177 self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
592e97e8
JMF
2178 try:
2179 os.remove(encodeFilename(old_filename))
2180 except (IOError, OSError):
2181 self.report_warning('Unable to remove downloaded original file')
c1c9a79c 2182
5db07df6 2183 def _make_archive_id(self, info_dict):
e9fef7ee
S
2184 video_id = info_dict.get('id')
2185 if not video_id:
2186 return
5db07df6
PH
2187 # Future-proof against any change in case
2188 # and backwards compatibility with prior versions
e9fef7ee 2189 extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
7012b23c 2190 if extractor is None:
1211bb6d
S
2191 url = str_or_none(info_dict.get('url'))
2192 if not url:
2193 return
e9fef7ee
S
2194 # Try to find matching extractor for the URL and take its ie_key
2195 for ie in self._ies:
1211bb6d 2196 if ie.suitable(url):
e9fef7ee
S
2197 extractor = ie.ie_key()
2198 break
2199 else:
2200 return
2201 return extractor.lower() + ' ' + video_id
5db07df6
PH
2202
2203 def in_download_archive(self, info_dict):
2204 fn = self.params.get('download_archive')
2205 if fn is None:
2206 return False
2207
2208 vid_id = self._make_archive_id(info_dict)
e9fef7ee 2209 if not vid_id:
7012b23c 2210 return False # Incomplete video information
5db07df6 2211
ecdec191 2212 return self.archive.at_exist(vid_id)
c1c9a79c
PH
2213
2214 def record_download_archive(self, info_dict):
2215 fn = self.params.get('download_archive')
2216 if fn is None:
2217 return
5db07df6
PH
2218 vid_id = self._make_archive_id(info_dict)
2219 assert vid_id
c1c9a79c 2220 with locked_file(fn, 'a', encoding='utf-8') as archive_file:
6febd1c1 2221 archive_file.write(vid_id + '\n')
ecdec191 2222 self.archive.at_insert(vid_id)
dd82ffea 2223
8c51aa65 2224 @staticmethod
8abeeb94 2225 def format_resolution(format, default='unknown'):
fb04e403
PH
2226 if format.get('vcodec') == 'none':
2227 return 'audio only'
f49d89ee
PH
2228 if format.get('resolution') is not None:
2229 return format['resolution']
8c51aa65
JMF
2230 if format.get('height') is not None:
2231 if format.get('width') is not None:
6febd1c1 2232 res = '%sx%s' % (format['width'], format['height'])
8c51aa65 2233 else:
6febd1c1 2234 res = '%sp' % format['height']
f49d89ee 2235 elif format.get('width') is not None:
388ae76b 2236 res = '%dx?' % format['width']
8c51aa65 2237 else:
8abeeb94 2238 res = default
8c51aa65
JMF
2239 return res
2240
c57f7757
PH
2241 def _format_note(self, fdict):
2242 res = ''
2243 if fdict.get('ext') in ['f4f', 'f4m']:
2244 res += '(unsupported) '
32f90364
PH
2245 if fdict.get('language'):
2246 if res:
2247 res += ' '
9016d76f 2248 res += '[%s] ' % fdict['language']
c57f7757
PH
2249 if fdict.get('format_note') is not None:
2250 res += fdict['format_note'] + ' '
2251 if fdict.get('tbr') is not None:
2252 res += '%4dk ' % fdict['tbr']
2253 if fdict.get('container') is not None:
2254 if res:
2255 res += ', '
2256 res += '%s container' % fdict['container']
3089bc74
S
2257 if (fdict.get('vcodec') is not None
2258 and fdict.get('vcodec') != 'none'):
c57f7757
PH
2259 if res:
2260 res += ', '
2261 res += fdict['vcodec']
91c7271a 2262 if fdict.get('vbr') is not None:
c57f7757
PH
2263 res += '@'
2264 elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
2265 res += 'video@'
2266 if fdict.get('vbr') is not None:
2267 res += '%4dk' % fdict['vbr']
fbb21cf5 2268 if fdict.get('fps') is not None:
5d583bdf
S
2269 if res:
2270 res += ', '
2271 res += '%sfps' % fdict['fps']
c57f7757
PH
2272 if fdict.get('acodec') is not None:
2273 if res:
2274 res += ', '
2275 if fdict['acodec'] == 'none':
2276 res += 'video only'
2277 else:
2278 res += '%-5s' % fdict['acodec']
2279 elif fdict.get('abr') is not None:
2280 if res:
2281 res += ', '
2282 res += 'audio'
2283 if fdict.get('abr') is not None:
2284 res += '@%3dk' % fdict['abr']
2285 if fdict.get('asr') is not None:
2286 res += ' (%5dHz)' % fdict['asr']
2287 if fdict.get('filesize') is not None:
2288 if res:
2289 res += ', '
2290 res += format_bytes(fdict['filesize'])
9732d77e
PH
2291 elif fdict.get('filesize_approx') is not None:
2292 if res:
2293 res += ', '
2294 res += '~' + format_bytes(fdict['filesize_approx'])
c57f7757 2295 return res
91c7271a 2296
c57f7757 2297 def list_formats(self, info_dict):
94badb25 2298 formats = info_dict.get('formats', [info_dict])
b81a359e
PH
2299 table = [
2300 [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
2301 for f in formats
e65566a9 2302 if f.get('preference') is None or f['preference'] >= -1000]
94badb25 2303 if len(formats) > 1:
b81a359e 2304 table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
57dd9a8f 2305
b81a359e 2306 header_line = ['format code', 'extension', 'resolution', 'note']
cfb56d1a 2307 self.to_screen(
b81a359e
PH
2308 '[info] Available formats for %s:\n%s' %
2309 (info_dict['id'], render_table(header_line, table)))
cfb56d1a
PH
2310
2311 def list_thumbnails(self, info_dict):
2312 thumbnails = info_dict.get('thumbnails')
2313 if not thumbnails:
b7b72db9 2314 self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
2315 return
cfb56d1a
PH
2316
2317 self.to_screen(
2318 '[info] Thumbnails for %s:' % info_dict['id'])
2319 self.to_screen(render_table(
2320 ['ID', 'width', 'height', 'URL'],
2321 [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
dca08720 2322
360e1ca5 2323 def list_subtitles(self, video_id, subtitles, name='subtitles'):
a504ced0 2324 if not subtitles:
360e1ca5 2325 self.to_screen('%s has no %s' % (video_id, name))
a504ced0 2326 return
a504ced0 2327 self.to_screen(
edab9dbf
JMF
2328 'Available %s for %s:' % (name, video_id))
2329 self.to_screen(render_table(
2330 ['Language', 'formats'],
2331 [[lang, ', '.join(f['ext'] for f in reversed(formats))]
2332 for lang, formats in subtitles.items()]))
a504ced0 2333
dca08720
PH
2334 def urlopen(self, req):
2335 """ Start an HTTP download """
82d8a8b6 2336 if isinstance(req, compat_basestring):
67dda517 2337 req = sanitized_Request(req)
19a41fc6 2338 return self._opener.open(req, timeout=self._socket_timeout)
dca08720
PH
2339
2340 def print_debug_header(self):
2341 if not self.params.get('verbose'):
2342 return
62fec3b2 2343
4192b51c 2344 if type('') is not compat_str:
067aa17e 2345 # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
4192b51c
PH
2346 self.report_warning(
2347 'Your Python is broken! Update to a newer and supported version')
2348
c6afed48
PH
2349 stdout_encoding = getattr(
2350 sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
b0472057 2351 encoding_str = (
734f90bb
PH
2352 '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
2353 locale.getpreferredencoding(),
2354 sys.getfilesystemencoding(),
c6afed48 2355 stdout_encoding,
b0472057 2356 self.get_encoding()))
4192b51c 2357 write_string(encoding_str, encoding=None)
734f90bb 2358
cefecac1 2359 self._write_string('[debug] youtube-dlc version ' + __version__ + '\n')
e0986e31
JMF
2360 if _LAZY_LOADER:
2361 self._write_string('[debug] Lazy loading extractors enabled' + '\n')
dca08720
PH
2362 try:
2363 sp = subprocess.Popen(
2364 ['git', 'rev-parse', '--short', 'HEAD'],
2365 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2366 cwd=os.path.dirname(os.path.abspath(__file__)))
2367 out, err = sp.communicate()
2368 out = out.decode().strip()
2369 if re.match('[0-9a-f]+', out):
734f90bb 2370 self._write_string('[debug] Git HEAD: ' + out + '\n')
70a1165b 2371 except Exception:
dca08720
PH
2372 try:
2373 sys.exc_clear()
70a1165b 2374 except Exception:
dca08720 2375 pass
b300cda4
S
2376
2377 def python_implementation():
2378 impl_name = platform.python_implementation()
2379 if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
2380 return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
2381 return impl_name
2382
2383 self._write_string('[debug] Python version %s (%s) - %s\n' % (
2384 platform.python_version(), python_implementation(),
2385 platform_name()))
d28b5171 2386
73fac4e9 2387 exe_versions = FFmpegPostProcessor.get_versions(self)
4c83c967 2388 exe_versions['rtmpdump'] = rtmpdump_version()
feee8d32 2389 exe_versions['phantomjs'] = PhantomJSwrapper._version()
d28b5171
PH
2390 exe_str = ', '.join(
2391 '%s %s' % (exe, v)
2392 for exe, v in sorted(exe_versions.items())
2393 if v
2394 )
2395 if not exe_str:
2396 exe_str = 'none'
2397 self._write_string('[debug] exe versions: %s\n' % exe_str)
dca08720
PH
2398
2399 proxy_map = {}
2400 for handler in self._opener.handlers:
2401 if hasattr(handler, 'proxies'):
2402 proxy_map.update(handler.proxies)
734f90bb 2403 self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
dca08720 2404
58b1f00d
PH
2405 if self.params.get('call_home', False):
2406 ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
2407 self._write_string('[debug] Public IP address: %s\n' % ipaddr)
2408 latest_version = self.urlopen(
2409 'https://yt-dl.org/latest/version').read().decode('utf-8')
2410 if version_tuple(latest_version) > version_tuple(__version__):
2411 self.report_warning(
2412 'You are using an outdated version (newest version: %s)! '
2413 'See https://yt-dl.org/update if you need help updating.' %
2414 latest_version)
2415
e344693b 2416 def _setup_opener(self):
6ad14cab 2417 timeout_val = self.params.get('socket_timeout')
19a41fc6 2418 self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
6ad14cab 2419
dca08720
PH
2420 opts_cookiefile = self.params.get('cookiefile')
2421 opts_proxy = self.params.get('proxy')
2422
2423 if opts_cookiefile is None:
2424 self.cookiejar = compat_cookiejar.CookieJar()
2425 else:
590bc6f6 2426 opts_cookiefile = expand_path(opts_cookiefile)
1bab3437 2427 self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
dca08720 2428 if os.access(opts_cookiefile, os.R_OK):
1d88b3e6 2429 self.cookiejar.load(ignore_discard=True, ignore_expires=True)
dca08720 2430
6a3f4c3f 2431 cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
dca08720
PH
2432 if opts_proxy is not None:
2433 if opts_proxy == '':
2434 proxies = {}
2435 else:
2436 proxies = {'http': opts_proxy, 'https': opts_proxy}
2437 else:
2438 proxies = compat_urllib_request.getproxies()
067aa17e 2439 # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
dca08720
PH
2440 if 'http' in proxies and 'https' not in proxies:
2441 proxies['https'] = proxies['http']
91410c9b 2442 proxy_handler = PerRequestProxyHandler(proxies)
a0ddb8a2
PH
2443
2444 debuglevel = 1 if self.params.get('debug_printtraffic') else 0
be4a824d
PH
2445 https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
2446 ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
fca6dba8 2447 redirect_handler = YoutubeDLRedirectHandler()
8b172c2e 2448 data_handler = compat_urllib_request_DataHandler()
6240b0a2
JMF
2449
2450 # When passing our own FileHandler instance, build_opener won't add the
2451 # default FileHandler and allows us to disable the file protocol, which
2452 # can be used for malicious purposes (see
067aa17e 2453 # https://github.com/ytdl-org/youtube-dl/issues/8227)
6240b0a2
JMF
2454 file_handler = compat_urllib_request.FileHandler()
2455
2456 def file_open(*args, **kwargs):
cefecac1 2457 raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dlc for security reasons')
6240b0a2
JMF
2458 file_handler.file_open = file_open
2459
2460 opener = compat_urllib_request.build_opener(
fca6dba8 2461 proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
2461f79d 2462
dca08720
PH
2463 # Delete the default user-agent header, which would otherwise apply in
2464 # cases where our custom HTTP handler doesn't come into play
067aa17e 2465 # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
dca08720
PH
2466 opener.addheaders = []
2467 self._opener = opener
62fec3b2
PH
2468
2469 def encode(self, s):
2470 if isinstance(s, bytes):
2471 return s # Already encoded
2472
2473 try:
2474 return s.encode(self.get_encoding())
2475 except UnicodeEncodeError as err:
2476 err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
2477 raise
2478
2479 def get_encoding(self):
2480 encoding = self.params.get('encoding')
2481 if encoding is None:
2482 encoding = preferredencoding()
2483 return encoding
ec82d85a
PH
2484
2485 def _write_thumbnails(self, info_dict, filename):
2486 if self.params.get('writethumbnail', False):
2487 thumbnails = info_dict.get('thumbnails')
2488 if thumbnails:
2489 thumbnails = [thumbnails[-1]]
2490 elif self.params.get('write_all_thumbnails', False):
2491 thumbnails = info_dict.get('thumbnails')
2492 else:
2493 return
2494
2495 if not thumbnails:
2496 # No thumbnails present, so return immediately
2497 return
2498
2499 for t in thumbnails:
2500 thumb_ext = determine_ext(t['url'], 'jpg')
2501 suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
2502 thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
82245a6d 2503 t['filename'] = thumb_filename = os.path.splitext(filename)[0] + suffix + '.' + thumb_ext
ec82d85a
PH
2504
2505 if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
2506 self.to_screen('[%s] %s: Thumbnail %sis already present' %
2507 (info_dict['extractor'], info_dict['id'], thumb_display_id))
2508 else:
2509 self.to_screen('[%s] %s: Downloading thumbnail %s...' %
2510 (info_dict['extractor'], info_dict['id'], thumb_display_id))
2511 try:
2512 uf = self.urlopen(t['url'])
d3d89c32 2513 with open(encodeFilename(thumb_filename), 'wb') as thumbf:
ec82d85a
PH
2514 shutil.copyfileobj(uf, thumbf)
2515 self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
2516 (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
2517 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
2518 self.report_warning('Unable to download thumbnail "%s": %s' %
9b9c5355 2519 (t['url'], error_to_compat_str(err)))