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