You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1412 lines
61 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
10 years ago
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import json
  9. import locale
  10. import os
  11. import platform
  12. import re
  13. import shutil
  14. import subprocess
  15. import socket
  16. import sys
  17. import time
  18. import traceback
  19. if os.name == 'nt':
  20. import ctypes
  21. from .compat import (
  22. compat_cookiejar,
  23. compat_expanduser,
  24. compat_http_client,
  25. compat_str,
  26. compat_urllib_error,
  27. compat_urllib_request,
  28. )
  29. from .utils import (
  30. escape_url,
  31. ContentTooShortError,
  32. date_from_str,
  33. DateRange,
  34. DEFAULT_OUTTMPL,
  35. determine_ext,
  36. DownloadError,
  37. encodeFilename,
  38. ExtractorError,
  39. format_bytes,
  40. formatSeconds,
  41. get_term_width,
  42. locked_file,
  43. make_HTTPS_handler,
  44. MaxDownloadsReached,
  45. PagedList,
  46. PostProcessingError,
  47. platform_name,
  48. preferredencoding,
  49. SameFileError,
  50. sanitize_filename,
  51. subtitles_filename,
  52. takewhile_inclusive,
  53. UnavailableVideoError,
  54. url_basename,
  55. write_json_file,
  56. write_string,
  57. YoutubeDLHandler,
  58. prepend_extension,
  59. )
  60. from .cache import Cache
  61. from .extractor import get_info_extractor, gen_extractors
  62. from .downloader import get_suitable_downloader
  63. from .downloader.rtmp import rtmpdump_version
  64. from .postprocessor import FFmpegMergerPP, FFmpegPostProcessor
  65. from .version import __version__
  66. class YoutubeDL(object):
  67. """YoutubeDL class.
  68. YoutubeDL objects are the ones responsible of downloading the
  69. actual video file and writing it to disk if the user has requested
  70. it, among some other tasks. In most cases there should be one per
  71. program. As, given a video URL, the downloader doesn't know how to
  72. extract all the needed information, task that InfoExtractors do, it
  73. has to pass the URL to one of them.
  74. For this, YoutubeDL objects have a method that allows
  75. InfoExtractors to be registered in a given order. When it is passed
  76. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  77. finds that reports being able to handle it. The InfoExtractor extracts
  78. all the information about the video or videos the URL refers to, and
  79. YoutubeDL process the extracted information, possibly using a File
  80. Downloader to download the video.
  81. YoutubeDL objects accept a lot of parameters. In order not to saturate
  82. the object constructor with arguments, it receives a dictionary of
  83. options instead. These options are available through the params
  84. attribute for the InfoExtractors to use. The YoutubeDL also
  85. registers itself as the downloader in charge for the InfoExtractors
  86. that are added to it, so this is a "mutual registration".
  87. Available options:
  88. username: Username for authentication purposes.
  89. password: Password for authentication purposes.
  90. videopassword: Password for acces a video.
  91. usenetrc: Use netrc for authentication instead.
  92. verbose: Print additional info to stdout.
  93. quiet: Do not print messages to stdout.
  94. no_warnings: Do not print out anything for warnings.
  95. forceurl: Force printing final URL.
  96. forcetitle: Force printing title.
  97. forceid: Force printing ID.
  98. forcethumbnail: Force printing thumbnail URL.
  99. forcedescription: Force printing description.
  100. forcefilename: Force printing final filename.
  101. forceduration: Force printing duration.
  102. forcejson: Force printing info_dict as JSON.
  103. dump_single_json: Force printing the info_dict of the whole playlist
  104. (or video) as a single JSON line.
  105. simulate: Do not download the video files.
  106. format: Video format code.
  107. format_limit: Highest quality format to try.
  108. outtmpl: Template for output names.
  109. restrictfilenames: Do not allow "&" and spaces in file names
  110. ignoreerrors: Do not stop on download errors.
  111. nooverwrites: Prevent overwriting files.
  112. playliststart: Playlist item to start at.
  113. playlistend: Playlist item to end at.
  114. matchtitle: Download only matching titles.
  115. rejecttitle: Reject downloads for matching titles.
  116. logger: Log messages to a logging.Logger instance.
  117. logtostderr: Log messages to stderr instead of stdout.
  118. writedescription: Write the video description to a .description file
  119. writeinfojson: Write the video description to a .info.json file
  120. writeannotations: Write the video annotations to a .annotations.xml file
  121. writethumbnail: Write the thumbnail image to a file
  122. writesubtitles: Write the video subtitles to a file
  123. writeautomaticsub: Write the automatic subtitles to a file
  124. allsubtitles: Downloads all the subtitles of the video
  125. (requires writesubtitles or writeautomaticsub)
  126. listsubtitles: Lists all available subtitles for the video
  127. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  128. subtitleslangs: List of languages of the subtitles to download
  129. keepvideo: Keep the video file after post-processing
  130. daterange: A DateRange object, download only if the upload_date is in the range.
  131. skip_download: Skip the actual download of the video file
  132. cachedir: Location of the cache files in the filesystem.
  133. False to disable filesystem cache.
  134. noplaylist: Download single video instead of a playlist if in doubt.
  135. age_limit: An integer representing the user's age in years.
  136. Unsuitable videos for the given age are skipped.
  137. min_views: An integer representing the minimum view count the video
  138. must have in order to not be skipped.
  139. Videos without view count information are always
  140. downloaded. None for no limit.
  141. max_views: An integer representing the maximum view count.
  142. Videos that are more popular than that are not
  143. downloaded.
  144. Videos without view count information are always
  145. downloaded. None for no limit.
  146. download_archive: File name of a file where all downloads are recorded.
  147. Videos already present in the file are not downloaded
  148. again.
  149. cookiefile: File name where cookies should be read from and dumped to.
  150. nocheckcertificate:Do not verify SSL certificates
  151. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  152. At the moment, this is only supported by YouTube.
  153. proxy: URL of the proxy server to use
  154. socket_timeout: Time to wait for unresponsive hosts, in seconds
  155. bidi_workaround: Work around buggy terminals without bidirectional text
  156. support, using fridibi
  157. debug_printtraffic:Print out sent and received HTTP traffic
  158. include_ads: Download ads as well
  159. default_search: Prepend this string if an input url is not valid.
  160. 'auto' for elaborate guessing
  161. encoding: Use this encoding instead of the system-specified.
  162. extract_flat: Do not resolve URLs, return the immediate result.
  163. Pass in 'in_playlist' to only show this behavior for
  164. playlist items.
  165. The following parameters are not used by YoutubeDL itself, they are used by
  166. the FileDownloader:
  167. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  168. noresizebuffer, retries, continuedl, noprogress, consoletitle
  169. The following options are used by the post processors:
  170. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  171. otherwise prefer avconv.
  172. exec_cmd: Arbitrary command to run after downloading
  173. """
  174. params = None
  175. _ies = []
  176. _pps = []
  177. _download_retcode = None
  178. _num_downloads = None
  179. _screen_file = None
  180. def __init__(self, params=None, auto_init=True):
  181. """Create a FileDownloader object with the given options."""
  182. if params is None:
  183. params = {}
  184. self._ies = []
  185. self._ies_instances = {}
  186. self._pps = []
  187. self._progress_hooks = []
  188. self._download_retcode = 0
  189. self._num_downloads = 0
  190. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  191. self._err_file = sys.stderr
  192. self.params = params
  193. self.cache = Cache(self)
  194. if params.get('bidi_workaround', False):
  195. try:
  196. import pty
  197. master, slave = pty.openpty()
  198. width = get_term_width()
  199. if width is None:
  200. width_args = []
  201. else:
  202. width_args = ['-w', str(width)]
  203. sp_kwargs = dict(
  204. stdin=subprocess.PIPE,
  205. stdout=slave,
  206. stderr=self._err_file)
  207. try:
  208. self._output_process = subprocess.Popen(
  209. ['bidiv'] + width_args, **sp_kwargs
  210. )
  211. except OSError:
  212. self._output_process = subprocess.Popen(
  213. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  214. self._output_channel = os.fdopen(master, 'rb')
  215. except OSError as ose:
  216. if ose.errno == 2:
  217. 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.')
  218. else:
  219. raise
  220. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  221. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  222. and not params.get('restrictfilenames', False)):
  223. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  224. self.report_warning(
  225. 'Assuming --restrict-filenames since file system encoding '
  226. 'cannot encode all characters. '
  227. 'Set the LC_ALL environment variable to fix this.')
  228. self.params['restrictfilenames'] = True
  229. if '%(stitle)s' in self.params.get('outtmpl', ''):
  230. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  231. self._setup_opener()
  232. if auto_init:
  233. self.print_debug_header()
  234. self.add_default_info_extractors()
  235. def add_info_extractor(self, ie):
  236. """Add an InfoExtractor object to the end of the list."""
  237. self._ies.append(ie)
  238. self._ies_instances[ie.ie_key()] = ie
  239. ie.set_downloader(self)
  240. def get_info_extractor(self, ie_key):
  241. """
  242. Get an instance of an IE with name ie_key, it will try to get one from
  243. the _ies list, if there's no instance it will create a new one and add
  244. it to the extractor list.
  245. """
  246. ie = self._ies_instances.get(ie_key)
  247. if ie is None:
  248. ie = get_info_extractor(ie_key)()
  249. self.add_info_extractor(ie)
  250. return ie
  251. def add_default_info_extractors(self):
  252. """
  253. Add the InfoExtractors returned by gen_extractors to the end of the list
  254. """
  255. for ie in gen_extractors():
  256. self.add_info_extractor(ie)
  257. def add_post_processor(self, pp):
  258. """Add a PostProcessor object to the end of the chain."""
  259. self._pps.append(pp)
  260. pp.set_downloader(self)
  261. def add_progress_hook(self, ph):
  262. """Add the progress hook (currently only for the file downloader)"""
  263. self._progress_hooks.append(ph)
  264. def _bidi_workaround(self, message):
  265. if not hasattr(self, '_output_channel'):
  266. return message
  267. assert hasattr(self, '_output_process')
  268. assert isinstance(message, compat_str)
  269. line_count = message.count('\n') + 1
  270. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  271. self._output_process.stdin.flush()
  272. res = ''.join(self._output_channel.readline().decode('utf-8')
  273. for _ in range(line_count))
  274. return res[:-len('\n')]
  275. def to_screen(self, message, skip_eol=False):
  276. """Print message to stdout if not in quiet mode."""
  277. return self.to_stdout(message, skip_eol, check_quiet=True)
  278. def _write_string(self, s, out=None):
  279. write_string(s, out=out, encoding=self.params.get('encoding'))
  280. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  281. """Print message to stdout if not in quiet mode."""
  282. if self.params.get('logger'):
  283. self.params['logger'].debug(message)
  284. elif not check_quiet or not self.params.get('quiet', False):
  285. message = self._bidi_workaround(message)
  286. terminator = ['\n', ''][skip_eol]
  287. output = message + terminator
  288. self._write_string(output, self._screen_file)
  289. def to_stderr(self, message):
  290. """Print message to stderr."""
  291. assert isinstance(message, compat_str)
  292. if self.params.get('logger'):
  293. self.params['logger'].error(message)
  294. else:
  295. message = self._bidi_workaround(message)
  296. output = message + '\n'
  297. self._write_string(output, self._err_file)
  298. def to_console_title(self, message):
  299. if not self.params.get('consoletitle', False):
  300. return
  301. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  302. # c_wchar_p() might not be necessary if `message` is
  303. # already of type unicode()
  304. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  305. elif 'TERM' in os.environ:
  306. self._write_string('\033]0;%s\007' % message, self._screen_file)
  307. def save_console_title(self):
  308. if not self.params.get('consoletitle', False):
  309. return
  310. if 'TERM' in os.environ:
  311. # Save the title on stack
  312. self._write_string('\033[22;0t', self._screen_file)
  313. def restore_console_title(self):
  314. if not self.params.get('consoletitle', False):
  315. return
  316. if 'TERM' in os.environ:
  317. # Restore the title from stack
  318. self._write_string('\033[23;0t', self._screen_file)
  319. def __enter__(self):
  320. self.save_console_title()
  321. return self
  322. def __exit__(self, *args):
  323. self.restore_console_title()
  324. if self.params.get('cookiefile') is not None:
  325. self.cookiejar.save()
  326. def trouble(self, message=None, tb=None):
  327. """Determine action to take when a download problem appears.
  328. Depending on if the downloader has been configured to ignore
  329. download errors or not, this method may throw an exception or
  330. not when errors are found, after printing the message.
  331. tb, if given, is additional traceback information.
  332. """
  333. if message is not None:
  334. self.to_stderr(message)
  335. if self.params.get('verbose'):
  336. if tb is None:
  337. if sys.exc_info()[0]: # if .trouble has been called from an except block
  338. tb = ''
  339. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  340. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  341. tb += compat_str(traceback.format_exc())
  342. else:
  343. tb_data = traceback.format_list(traceback.extract_stack())
  344. tb = ''.join(tb_data)
  345. self.to_stderr(tb)
  346. if not self.params.get('ignoreerrors', False):
  347. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  348. exc_info = sys.exc_info()[1].exc_info
  349. else:
  350. exc_info = sys.exc_info()
  351. raise DownloadError(message, exc_info)
  352. self._download_retcode = 1
  353. def report_warning(self, message):
  354. '''
  355. Print the message to stderr, it will be prefixed with 'WARNING:'
  356. If stderr is a tty file the 'WARNING:' will be colored
  357. '''
  358. if self.params.get('logger') is not None:
  359. self.params['logger'].warning(message)
  360. else:
  361. if self.params.get('no_warnings'):
  362. return
  363. if self._err_file.isatty() and os.name != 'nt':
  364. _msg_header = '\033[0;33mWARNING:\033[0m'
  365. else:
  366. _msg_header = 'WARNING:'
  367. warning_message = '%s %s' % (_msg_header, message)
  368. self.to_stderr(warning_message)
  369. def report_error(self, message, tb=None):
  370. '''
  371. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  372. in red if stderr is a tty file.
  373. '''
  374. if self._err_file.isatty() and os.name != 'nt':
  375. _msg_header = '\033[0;31mERROR:\033[0m'
  376. else:
  377. _msg_header = 'ERROR:'
  378. error_message = '%s %s' % (_msg_header, message)
  379. self.trouble(error_message, tb)
  380. def report_file_already_downloaded(self, file_name):
  381. """Report file has already been fully downloaded."""
  382. try:
  383. self.to_screen('[download] %s has already been downloaded' % file_name)
  384. except UnicodeEncodeError:
  385. self.to_screen('[download] The file has already been downloaded')
  386. def prepare_filename(self, info_dict):
  387. """Generate the output filename."""
  388. try:
  389. template_dict = dict(info_dict)
  390. template_dict['epoch'] = int(time.time())
  391. autonumber_size = self.params.get('autonumber_size')
  392. if autonumber_size is None:
  393. autonumber_size = 5
  394. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  395. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  396. if template_dict.get('playlist_index') is not None:
  397. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  398. if template_dict.get('resolution') is None:
  399. if template_dict.get('width') and template_dict.get('height'):
  400. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  401. elif template_dict.get('height'):
  402. template_dict['resolution'] = '%sp' % template_dict['height']
  403. elif template_dict.get('width'):
  404. template_dict['resolution'] = '?x%d' % template_dict['width']
  405. sanitize = lambda k, v: sanitize_filename(
  406. compat_str(v),
  407. restricted=self.params.get('restrictfilenames'),
  408. is_id=(k == 'id'))
  409. template_dict = dict((k, sanitize(k, v))
  410. for k, v in template_dict.items()
  411. if v is not None)
  412. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  413. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  414. tmpl = compat_expanduser(outtmpl)
  415. filename = tmpl % template_dict
  416. return filename
  417. except ValueError as err:
  418. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  419. return None
  420. def _match_entry(self, info_dict):
  421. """ Returns None iff the file should be downloaded """
  422. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  423. if 'title' in info_dict:
  424. # This can happen when we're just evaluating the playlist
  425. title = info_dict['title']
  426. matchtitle = self.params.get('matchtitle', False)
  427. if matchtitle:
  428. if not re.search(matchtitle, title, re.IGNORECASE):
  429. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  430. rejecttitle = self.params.get('rejecttitle', False)
  431. if rejecttitle:
  432. if re.search(rejecttitle, title, re.IGNORECASE):
  433. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  434. date = info_dict.get('upload_date', None)
  435. if date is not None:
  436. dateRange = self.params.get('daterange', DateRange())
  437. if date not in dateRange:
  438. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  439. view_count = info_dict.get('view_count', None)
  440. if view_count is not None:
  441. min_views = self.params.get('min_views')
  442. if min_views is not None and view_count < min_views:
  443. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  444. max_views = self.params.get('max_views')
  445. if max_views is not None and view_count > max_views:
  446. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  447. age_limit = self.params.get('age_limit')
  448. if age_limit is not None:
  449. actual_age_limit = info_dict.get('age_limit')
  450. if actual_age_limit is None:
  451. actual_age_limit = 0
  452. if age_limit < actual_age_limit:
  453. return 'Skipping "' + title + '" because it is age restricted'
  454. if self.in_download_archive(info_dict):
  455. return '%s has already been recorded in archive' % video_title
  456. return None
  457. @staticmethod
  458. def add_extra_info(info_dict, extra_info):
  459. '''Set the keys from extra_info in info dict if they are missing'''
  460. for key, value in extra_info.items():
  461. info_dict.setdefault(key, value)
  462. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  463. process=True):
  464. '''
  465. Returns a list with a dictionary for each video we find.
  466. If 'download', also downloads the videos.
  467. extra_info is a dict containing the extra values to add to each result
  468. '''
  469. if ie_key:
  470. ies = [self.get_info_extractor(ie_key)]
  471. else:
  472. ies = self._ies
  473. for ie in ies:
  474. if not ie.suitable(url):
  475. continue
  476. if not ie.working():
  477. self.report_warning('The program functionality for this site has been marked as broken, '
  478. 'and will probably not work.')
  479. try:
  480. ie_result = ie.extract(url)
  481. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  482. break
  483. if isinstance(ie_result, list):
  484. # Backwards compatibility: old IE result format
  485. ie_result = {
  486. '_type': 'compat_list',
  487. 'entries': ie_result,
  488. }
  489. self.add_default_extra_info(ie_result, ie, url)
  490. if process:
  491. return self.process_ie_result(ie_result, download, extra_info)
  492. else:
  493. return ie_result
  494. except ExtractorError as de: # An error we somewhat expected
  495. self.report_error(compat_str(de), de.format_traceback())
  496. break
  497. except MaxDownloadsReached:
  498. raise
  499. except Exception as e:
  500. if self.params.get('ignoreerrors', False):
  501. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  502. break
  503. else:
  504. raise
  505. else:
  506. self.report_error('no suitable InfoExtractor for URL %s' % url)
  507. def add_default_extra_info(self, ie_result, ie, url):
  508. self.add_extra_info(ie_result, {
  509. 'extractor': ie.IE_NAME,
  510. 'webpage_url': url,
  511. 'webpage_url_basename': url_basename(url),
  512. 'extractor_key': ie.ie_key(),
  513. })
  514. def process_ie_result(self, ie_result, download=True, extra_info={}):
  515. """
  516. Take the result of the ie(may be modified) and resolve all unresolved
  517. references (URLs, playlist items).
  518. It will also download the videos if 'download'.
  519. Returns the resolved ie_result.
  520. """
  521. result_type = ie_result.get('_type', 'video')
  522. if result_type in ('url', 'url_transparent'):
  523. extract_flat = self.params.get('extract_flat', False)
  524. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  525. extract_flat is True):
  526. if self.params.get('forcejson', False):
  527. self.to_stdout(json.dumps(ie_result))
  528. return ie_result
  529. if result_type == 'video':
  530. self.add_extra_info(ie_result, extra_info)
  531. return self.process_video_result(ie_result, download=download)
  532. elif result_type == 'url':
  533. # We have to add extra_info to the results because it may be
  534. # contained in a playlist
  535. return self.extract_info(ie_result['url'],
  536. download,
  537. ie_key=ie_result.get('ie_key'),
  538. extra_info=extra_info)
  539. elif result_type == 'url_transparent':
  540. # Use the information from the embedding page
  541. info = self.extract_info(
  542. ie_result['url'], ie_key=ie_result.get('ie_key'),
  543. extra_info=extra_info, download=False, process=False)
  544. def make_result(embedded_info):
  545. new_result = ie_result.copy()
  546. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  547. 'entries', 'ie_key', 'duration',
  548. 'subtitles', 'annotations', 'format',
  549. 'thumbnail', 'thumbnails'):
  550. if f in new_result:
  551. del new_result[f]
  552. if f in embedded_info:
  553. new_result[f] = embedded_info[f]
  554. return new_result
  555. new_result = make_result(info)
  556. assert new_result.get('_type') != 'url_transparent'
  557. if new_result.get('_type') == 'compat_list':
  558. new_result['entries'] = [
  559. make_result(e) for e in new_result['entries']]
  560. return self.process_ie_result(
  561. new_result, download=download, extra_info=extra_info)
  562. elif result_type == 'playlist':
  563. # We process each entry in the playlist
  564. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  565. self.to_screen('[download] Downloading playlist: %s' % playlist)
  566. playlist_results = []
  567. playliststart = self.params.get('playliststart', 1) - 1
  568. playlistend = self.params.get('playlistend', None)
  569. # For backwards compatibility, interpret -1 as whole list
  570. if playlistend == -1:
  571. playlistend = None
  572. if isinstance(ie_result['entries'], list):
  573. n_all_entries = len(ie_result['entries'])
  574. entries = ie_result['entries'][playliststart:playlistend]
  575. n_entries = len(entries)
  576. self.to_screen(
  577. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  578. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  579. else:
  580. assert isinstance(ie_result['entries'], PagedList)
  581. entries = ie_result['entries'].getslice(
  582. playliststart, playlistend)
  583. n_entries = len(entries)
  584. self.to_screen(
  585. "[%s] playlist %s: Downloading %d videos" %
  586. (ie_result['extractor'], playlist, n_entries))
  587. for i, entry in enumerate(entries, 1):
  588. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  589. extra = {
  590. 'n_entries': n_entries,
  591. 'playlist': playlist,
  592. 'playlist_id': ie_result.get('id'),
  593. 'playlist_title': ie_result.get('title'),
  594. 'playlist_index': i + playliststart,
  595. 'extractor': ie_result['extractor'],
  596. 'webpage_url': ie_result['webpage_url'],
  597. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  598. 'extractor_key': ie_result['extractor_key'],
  599. }
  600. reason = self._match_entry(entry)
  601. if reason is not None:
  602. self.to_screen('[download] ' + reason)
  603. continue
  604. entry_result = self.process_ie_result(entry,
  605. download=download,
  606. extra_info=extra)
  607. playlist_results.append(entry_result)
  608. ie_result['entries'] = playlist_results
  609. return ie_result
  610. elif result_type == 'compat_list':
  611. self.report_warning(
  612. 'Extractor %s returned a compat_list result. '
  613. 'It needs to be updated.' % ie_result.get('extractor'))
  614. def _fixup(r):
  615. self.add_extra_info(r,
  616. {
  617. 'extractor': ie_result['extractor'],
  618. 'webpage_url': ie_result['webpage_url'],
  619. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  620. 'extractor_key': ie_result['extractor_key'],
  621. })
  622. return r
  623. ie_result['entries'] = [
  624. self.process_ie_result(_fixup(r), download, extra_info)
  625. for r in ie_result['entries']
  626. ]
  627. return ie_result
  628. else:
  629. raise Exception('Invalid result type: %s' % result_type)
  630. def select_format(self, format_spec, available_formats):
  631. if format_spec == 'best' or format_spec is None:
  632. return available_formats[-1]
  633. elif format_spec == 'worst':
  634. return available_formats[0]
  635. elif format_spec == 'bestaudio':
  636. audio_formats = [
  637. f for f in available_formats
  638. if f.get('vcodec') == 'none']
  639. if audio_formats:
  640. return audio_formats[-1]
  641. elif format_spec == 'worstaudio':
  642. audio_formats = [
  643. f for f in available_formats
  644. if f.get('vcodec') == 'none']
  645. if audio_formats:
  646. return audio_formats[0]
  647. elif format_spec == 'bestvideo':
  648. video_formats = [
  649. f for f in available_formats
  650. if f.get('acodec') == 'none']
  651. if video_formats:
  652. return video_formats[-1]
  653. elif format_spec == 'worstvideo':
  654. video_formats = [
  655. f for f in available_formats
  656. if f.get('acodec') == 'none']
  657. if video_formats:
  658. return video_formats[0]
  659. else:
  660. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a']
  661. if format_spec in extensions:
  662. filter_f = lambda f: f['ext'] == format_spec
  663. else:
  664. filter_f = lambda f: f['format_id'] == format_spec
  665. matches = list(filter(filter_f, available_formats))
  666. if matches:
  667. return matches[-1]
  668. return None
  669. def process_video_result(self, info_dict, download=True):
  670. assert info_dict.get('_type', 'video') == 'video'
  671. if 'id' not in info_dict:
  672. raise ExtractorError('Missing "id" field in extractor result')
  673. if 'title' not in info_dict:
  674. raise ExtractorError('Missing "title" field in extractor result')
  675. if 'playlist' not in info_dict:
  676. # It isn't part of a playlist
  677. info_dict['playlist'] = None
  678. info_dict['playlist_index'] = None
  679. thumbnails = info_dict.get('thumbnails')
  680. if thumbnails:
  681. thumbnails.sort(key=lambda t: (
  682. t.get('width'), t.get('height'), t.get('url')))
  683. for t in thumbnails:
  684. if 'width' in t and 'height' in t:
  685. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  686. if thumbnails and 'thumbnail' not in info_dict:
  687. info_dict['thumbnail'] = thumbnails[-1]['url']
  688. if 'display_id' not in info_dict and 'id' in info_dict:
  689. info_dict['display_id'] = info_dict['id']
  690. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  691. upload_date = datetime.datetime.utcfromtimestamp(
  692. info_dict['timestamp'])
  693. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  694. # This extractors handle format selection themselves
  695. if info_dict['extractor'] in ['Youku']:
  696. if download:
  697. self.process_info(info_dict)
  698. return info_dict
  699. # We now pick which formats have to be downloaded
  700. if info_dict.get('formats') is None:
  701. # There's only one format available
  702. formats = [info_dict]
  703. else:
  704. formats = info_dict['formats']
  705. if not formats:
  706. raise ExtractorError('No video formats found!')
  707. # We check that all the formats have the format and format_id fields
  708. for i, format in enumerate(formats):
  709. if 'url' not in format:
  710. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  711. if format.get('format_id') is None:
  712. format['format_id'] = compat_str(i)
  713. if format.get('format') is None:
  714. format['format'] = '{id} - {res}{note}'.format(
  715. id=format['format_id'],
  716. res=self.format_resolution(format),
  717. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  718. )
  719. # Automatically determine file extension if missing
  720. if 'ext' not in format:
  721. format['ext'] = determine_ext(format['url']).lower()
  722. format_limit = self.params.get('format_limit', None)
  723. if format_limit:
  724. formats = list(takewhile_inclusive(
  725. lambda f: f['format_id'] != format_limit, formats
  726. ))
  727. # TODO Central sorting goes here
  728. if formats[0] is not info_dict:
  729. # only set the 'formats' fields if the original info_dict list them
  730. # otherwise we end up with a circular reference, the first (and unique)
  731. # element in the 'formats' field in info_dict is info_dict itself,
  732. # wich can't be exported to json
  733. info_dict['formats'] = formats
  734. if self.params.get('listformats', None):
  735. self.list_formats(info_dict)
  736. return
  737. req_format = self.params.get('format')
  738. if req_format is None:
  739. req_format = 'best'
  740. formats_to_download = []
  741. # The -1 is for supporting YoutubeIE
  742. if req_format in ('-1', 'all'):
  743. formats_to_download = formats
  744. else:
  745. for rfstr in req_format.split(','):
  746. # We can accept formats requested in the format: 34/5/best, we pick
  747. # the first that is available, starting from left
  748. req_formats = rfstr.split('/')
  749. for rf in req_formats:
  750. if re.match(r'.+?\+.+?', rf) is not None:
  751. # Two formats have been requested like '137+139'
  752. format_1, format_2 = rf.split('+')
  753. formats_info = (self.select_format(format_1, formats),
  754. self.select_format(format_2, formats))
  755. if all(formats_info):
  756. # The first format must contain the video and the
  757. # second the audio
  758. if formats_info[0].get('vcodec') == 'none':
  759. self.report_error('The first format must '
  760. 'contain the video, try using '
  761. '"-f %s+%s"' % (format_2, format_1))
  762. return
  763. selected_format = {
  764. 'requested_formats': formats_info,
  765. 'format': rf,
  766. 'ext': formats_info[0]['ext'],
  767. }
  768. else:
  769. selected_format = None
  770. else:
  771. selected_format = self.select_format(rf, formats)
  772. if selected_format is not None:
  773. formats_to_download.append(selected_format)
  774. break
  775. if not formats_to_download:
  776. raise ExtractorError('requested format not available',
  777. expected=True)
  778. if download:
  779. if len(formats_to_download) > 1:
  780. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  781. for format in formats_to_download:
  782. new_info = dict(info_dict)
  783. new_info.update(format)
  784. self.process_info(new_info)
  785. # We update the info dict with the best quality format (backwards compatibility)
  786. info_dict.update(formats_to_download[-1])
  787. return info_dict
  788. def process_info(self, info_dict):
  789. """Process a single resolved IE result."""
  790. assert info_dict.get('_type', 'video') == 'video'
  791. max_downloads = self.params.get('max_downloads')
  792. if max_downloads is not None:
  793. if self._num_downloads >= int(max_downloads):
  794. raise MaxDownloadsReached()
  795. info_dict['fulltitle'] = info_dict['title']
  796. if len(info_dict['title']) > 200:
  797. info_dict['title'] = info_dict['title'][:197] + '...'
  798. # Keep for backwards compatibility
  799. info_dict['stitle'] = info_dict['title']
  800. if 'format' not in info_dict:
  801. info_dict['format'] = info_dict['ext']
  802. reason = self._match_entry(info_dict)
  803. if reason is not None:
  804. self.to_screen('[download] ' + reason)
  805. return
  806. self._num_downloads += 1
  807. filename = self.prepare_filename(info_dict)
  808. # Forced printings
  809. if self.params.get('forcetitle', False):
  810. self.to_stdout(info_dict['fulltitle'])
  811. if self.params.get('forceid', False):
  812. self.to_stdout(info_dict['id'])
  813. if self.params.get('forceurl', False):
  814. # For RTMP URLs, also include the playpath
  815. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  816. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  817. self.to_stdout(info_dict['thumbnail'])
  818. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  819. self.to_stdout(info_dict['description'])
  820. if self.params.get('forcefilename', False) and filename is not None:
  821. self.to_stdout(filename)
  822. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  823. self.to_stdout(formatSeconds(info_dict['duration']))
  824. if self.params.get('forceformat', False):
  825. self.to_stdout(info_dict['format'])
  826. if self.params.get('forcejson', False):
  827. info_dict['_filename'] = filename
  828. self.to_stdout(json.dumps(info_dict))
  829. if self.params.get('dump_single_json', False):
  830. info_dict['_filename'] = filename
  831. # Do nothing else if in simulate mode
  832. if self.params.get('simulate', False):
  833. return
  834. if filename is None:
  835. return
  836. try:
  837. dn = os.path.dirname(encodeFilename(filename))
  838. if dn and not os.path.exists(dn):
  839. os.makedirs(dn)
  840. except (OSError, IOError) as err:
  841. self.report_error('unable to create directory ' + compat_str(err))
  842. return
  843. if self.params.get('writedescription', False):
  844. descfn = filename + '.description'
  845. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  846. self.to_screen('[info] Video description is already present')
  847. else:
  848. try:
  849. self.to_screen('[info] Writing video description to: ' + descfn)
  850. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  851. descfile.write(info_dict['description'])
  852. except (KeyError, TypeError):
  853. self.report_warning('There\'s no description to write.')
  854. except (OSError, IOError):
  855. self.report_error('Cannot write description file ' + descfn)
  856. return
  857. if self.params.get('writeannotations', False):
  858. annofn = filename + '.annotations.xml'
  859. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  860. self.to_screen('[info] Video annotations are already present')
  861. else:
  862. try:
  863. self.to_screen('[info] Writing video annotations to: ' + annofn)
  864. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  865. annofile.write(info_dict['annotations'])
  866. except (KeyError, TypeError):
  867. self.report_warning('There are no annotations to write.')
  868. except (OSError, IOError):
  869. self.report_error('Cannot write annotations file: ' + annofn)
  870. return
  871. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  872. self.params.get('writeautomaticsub')])
  873. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  874. # subtitles download errors are already managed as troubles in relevant IE
  875. # that way it will silently go on when used with unsupporting IE
  876. subtitles = info_dict['subtitles']
  877. sub_format = self.params.get('subtitlesformat', 'srt')
  878. for sub_lang in subtitles.keys():
  879. sub = subtitles[sub_lang]
  880. if sub is None:
  881. continue
  882. try:
  883. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  884. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  885. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  886. else:
  887. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  888. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  889. subfile.write(sub)
  890. except (OSError, IOError):
  891. self.report_error('Cannot write subtitles file ' + sub_filename)
  892. return
  893. if self.params.get('writeinfojson', False):
  894. infofn = os.path.splitext(filename)[0] + '.info.json'
  895. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  896. self.to_screen('[info] Video description metadata is already present')
  897. else:
  898. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  899. try:
  900. write_json_file(info_dict, infofn)
  901. except (OSError, IOError):
  902. self.report_error('Cannot write metadata to JSON file ' + infofn)
  903. return
  904. if self.params.get('writethumbnail', False):
  905. if info_dict.get('thumbnail') is not None:
  906. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  907. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  908. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  909. self.to_screen('[%s] %s: Thumbnail is already present' %
  910. (info_dict['extractor'], info_dict['id']))
  911. else:
  912. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  913. (info_dict['extractor'], info_dict['id']))
  914. try:
  915. uf = self.urlopen(info_dict['thumbnail'])
  916. with open(thumb_filename, 'wb') as thumbf:
  917. shutil.copyfileobj(uf, thumbf)
  918. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  919. (info_dict['extractor'], info_dict['id'], thumb_filename))
  920. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  921. self.report_warning('Unable to download thumbnail "%s": %s' %
  922. (info_dict['thumbnail'], compat_str(err)))
  923. if not self.params.get('skip_download', False):
  924. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  925. success = True
  926. else:
  927. try:
  928. def dl(name, info):
  929. fd = get_suitable_downloader(info)(self, self.params)
  930. for ph in self._progress_hooks:
  931. fd.add_progress_hook(ph)
  932. if self.params.get('verbose'):
  933. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  934. return fd.download(name, info)
  935. if info_dict.get('requested_formats') is not None:
  936. downloaded = []
  937. success = True
  938. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  939. if not merger._executable:
  940. postprocessors = []
  941. self.report_warning('You have requested multiple '
  942. 'formats but ffmpeg or avconv are not installed.'
  943. ' The formats won\'t be merged')
  944. else:
  945. postprocessors = [merger]
  946. for f in info_dict['requested_formats']:
  947. new_info = dict(info_dict)
  948. new_info.update(f)
  949. fname = self.prepare_filename(new_info)
  950. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  951. downloaded.append(fname)
  952. partial_success = dl(fname, new_info)
  953. success = success and partial_success
  954. info_dict['__postprocessors'] = postprocessors
  955. info_dict['__files_to_merge'] = downloaded
  956. else:
  957. # Just a single file
  958. success = dl(filename, info_dict)
  959. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  960. self.report_error('unable to download video data: %s' % str(err))
  961. return
  962. except (OSError, IOError) as err:
  963. raise UnavailableVideoError(err)
  964. except (ContentTooShortError, ) as err:
  965. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  966. return
  967. if success:
  968. try:
  969. self.post_process(filename, info_dict)
  970. except (PostProcessingError) as err:
  971. self.report_error('postprocessing: %s' % str(err))
  972. return
  973. self.record_download_archive(info_dict)
  974. def download(self, url_list):
  975. """Download a given list of URLs."""
  976. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  977. if (len(url_list) > 1 and
  978. '%' not in outtmpl
  979. and self.params.get('max_downloads') != 1):
  980. raise SameFileError(outtmpl)
  981. for url in url_list:
  982. try:
  983. #It also downloads the videos
  984. res = self.extract_info(url)
  985. except UnavailableVideoError:
  986. self.report_error('unable to download video')
  987. except MaxDownloadsReached:
  988. self.to_screen('[info] Maximum number of downloaded files reached.')
  989. raise
  990. else:
  991. if self.params.get('dump_single_json', False):
  992. self.to_stdout(json.dumps(res))
  993. return self._download_retcode
  994. def download_with_info_file(self, info_filename):
  995. with io.open(info_filename, 'r', encoding='utf-8') as f:
  996. info = json.load(f)
  997. try:
  998. self.process_ie_result(info, download=True)
  999. except DownloadError:
  1000. webpage_url = info.get('webpage_url')
  1001. if webpage_url is not None:
  1002. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1003. return self.download([webpage_url])
  1004. else:
  1005. raise
  1006. return self._download_retcode
  1007. def post_process(self, filename, ie_info):
  1008. """Run all the postprocessors on the given file."""
  1009. info = dict(ie_info)
  1010. info['filepath'] = filename
  1011. keep_video = None
  1012. pps_chain = []
  1013. if ie_info.get('__postprocessors') is not None:
  1014. pps_chain.extend(ie_info['__postprocessors'])
  1015. pps_chain.extend(self._pps)
  1016. for pp in pps_chain:
  1017. try:
  1018. keep_video_wish, new_info = pp.run(info)
  1019. if keep_video_wish is not None:
  1020. if keep_video_wish:
  1021. keep_video = keep_video_wish
  1022. elif keep_video is None:
  1023. # No clear decision yet, let IE decide
  1024. keep_video = keep_video_wish
  1025. except PostProcessingError as e:
  1026. self.report_error(e.msg)
  1027. if keep_video is False and not self.params.get('keepvideo', False):
  1028. try:
  1029. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1030. os.remove(encodeFilename(filename))
  1031. except (IOError, OSError):
  1032. self.report_warning('Unable to remove downloaded video file')
  1033. def _make_archive_id(self, info_dict):
  1034. # Future-proof against any change in case
  1035. # and backwards compatibility with prior versions
  1036. extractor = info_dict.get('extractor_key')
  1037. if extractor is None:
  1038. if 'id' in info_dict:
  1039. extractor = info_dict.get('ie_key') # key in a playlist
  1040. if extractor is None:
  1041. return None # Incomplete video information
  1042. return extractor.lower() + ' ' + info_dict['id']
  1043. def in_download_archive(self, info_dict):
  1044. fn = self.params.get('download_archive')
  1045. if fn is None:
  1046. return False
  1047. vid_id = self._make_archive_id(info_dict)
  1048. if vid_id is None:
  1049. return False # Incomplete video information
  1050. try:
  1051. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1052. for line in archive_file:
  1053. if line.strip() == vid_id:
  1054. return True
  1055. except IOError as ioe:
  1056. if ioe.errno != errno.ENOENT:
  1057. raise
  1058. return False
  1059. def record_download_archive(self, info_dict):
  1060. fn = self.params.get('download_archive')
  1061. if fn is None:
  1062. return
  1063. vid_id = self._make_archive_id(info_dict)
  1064. assert vid_id
  1065. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1066. archive_file.write(vid_id + '\n')
  1067. @staticmethod
  1068. def format_resolution(format, default='unknown'):
  1069. if format.get('vcodec') == 'none':
  1070. return 'audio only'
  1071. if format.get('resolution') is not None:
  1072. return format['resolution']
  1073. if format.get('height') is not None:
  1074. if format.get('width') is not None:
  1075. res = '%sx%s' % (format['width'], format['height'])
  1076. else:
  1077. res = '%sp' % format['height']
  1078. elif format.get('width') is not None:
  1079. res = '?x%d' % format['width']
  1080. else:
  1081. res = default
  1082. return res
  1083. def _format_note(self, fdict):
  1084. res = ''
  1085. if fdict.get('ext') in ['f4f', 'f4m']:
  1086. res += '(unsupported) '
  1087. if fdict.get('format_note') is not None:
  1088. res += fdict['format_note'] + ' '
  1089. if fdict.get('tbr') is not None:
  1090. res += '%4dk ' % fdict['tbr']
  1091. if fdict.get('container') is not None:
  1092. if res:
  1093. res += ', '
  1094. res += '%s container' % fdict['container']
  1095. if (fdict.get('vcodec') is not None and
  1096. fdict.get('vcodec') != 'none'):
  1097. if res:
  1098. res += ', '
  1099. res += fdict['vcodec']
  1100. if fdict.get('vbr') is not None:
  1101. res += '@'
  1102. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1103. res += 'video@'
  1104. if fdict.get('vbr') is not None:
  1105. res += '%4dk' % fdict['vbr']
  1106. if fdict.get('fps') is not None:
  1107. res += ', %sfps' % fdict['fps']
  1108. if fdict.get('acodec') is not None:
  1109. if res:
  1110. res += ', '
  1111. if fdict['acodec'] == 'none':
  1112. res += 'video only'
  1113. else:
  1114. res += '%-5s' % fdict['acodec']
  1115. elif fdict.get('abr') is not None:
  1116. if res:
  1117. res += ', '
  1118. res += 'audio'
  1119. if fdict.get('abr') is not None:
  1120. res += '@%3dk' % fdict['abr']
  1121. if fdict.get('asr') is not None:
  1122. res += ' (%5dHz)' % fdict['asr']
  1123. if fdict.get('filesize') is not None:
  1124. if res:
  1125. res += ', '
  1126. res += format_bytes(fdict['filesize'])
  1127. elif fdict.get('filesize_approx') is not None:
  1128. if res:
  1129. res += ', '
  1130. res += '~' + format_bytes(fdict['filesize_approx'])
  1131. return res
  1132. def list_formats(self, info_dict):
  1133. def line(format, idlen=20):
  1134. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1135. format['format_id'],
  1136. format['ext'],
  1137. self.format_resolution(format),
  1138. self._format_note(format),
  1139. ))
  1140. formats = info_dict.get('formats', [info_dict])
  1141. idlen = max(len('format code'),
  1142. max(len(f['format_id']) for f in formats))
  1143. formats_s = [line(f, idlen) for f in formats]
  1144. if len(formats) > 1:
  1145. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1146. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1147. header_line = line({
  1148. 'format_id': 'format code', 'ext': 'extension',
  1149. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1150. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1151. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1152. def urlopen(self, req):
  1153. """ Start an HTTP download """
  1154. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1155. # always respected by websites, some tend to give out URLs with non percent-encoded
  1156. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1157. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1158. # To work around aforementioned issue we will replace request's original URL with
  1159. # percent-encoded one
  1160. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1161. url = req if req_is_string else req.get_full_url()
  1162. url_escaped = escape_url(url)
  1163. # Substitute URL if any change after escaping
  1164. if url != url_escaped:
  1165. if req_is_string:
  1166. req = url_escaped
  1167. else:
  1168. req = compat_urllib_request.Request(
  1169. url_escaped, data=req.data, headers=req.headers,
  1170. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1171. return self._opener.open(req, timeout=self._socket_timeout)
  1172. def print_debug_header(self):
  1173. if not self.params.get('verbose'):
  1174. return
  1175. if type('') is not compat_str:
  1176. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1177. self.report_warning(
  1178. 'Your Python is broken! Update to a newer and supported version')
  1179. stdout_encoding = getattr(
  1180. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  1181. encoding_str = (
  1182. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1183. locale.getpreferredencoding(),
  1184. sys.getfilesystemencoding(),
  1185. stdout_encoding,
  1186. self.get_encoding()))
  1187. write_string(encoding_str, encoding=None)
  1188. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1189. try:
  1190. sp = subprocess.Popen(
  1191. ['git', 'rev-parse', '--short', 'HEAD'],
  1192. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1193. cwd=os.path.dirname(os.path.abspath(__file__)))
  1194. out, err = sp.communicate()
  1195. out = out.decode().strip()
  1196. if re.match('[0-9a-f]+', out):
  1197. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1198. except:
  1199. try:
  1200. sys.exc_clear()
  1201. except:
  1202. pass
  1203. self._write_string('[debug] Python version %s - %s\n' % (
  1204. platform.python_version(), platform_name()))
  1205. exe_versions = FFmpegPostProcessor.get_versions()
  1206. exe_versions['rtmpdump'] = rtmpdump_version()
  1207. exe_str = ', '.join(
  1208. '%s %s' % (exe, v)
  1209. for exe, v in sorted(exe_versions.items())
  1210. if v
  1211. )
  1212. if not exe_str:
  1213. exe_str = 'none'
  1214. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1215. proxy_map = {}
  1216. for handler in self._opener.handlers:
  1217. if hasattr(handler, 'proxies'):
  1218. proxy_map.update(handler.proxies)
  1219. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1220. def _setup_opener(self):
  1221. timeout_val = self.params.get('socket_timeout')
  1222. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1223. opts_cookiefile = self.params.get('cookiefile')
  1224. opts_proxy = self.params.get('proxy')
  1225. if opts_cookiefile is None:
  1226. self.cookiejar = compat_cookiejar.CookieJar()
  1227. else:
  1228. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1229. opts_cookiefile)
  1230. if os.access(opts_cookiefile, os.R_OK):
  1231. self.cookiejar.load()
  1232. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1233. self.cookiejar)
  1234. if opts_proxy is not None:
  1235. if opts_proxy == '':
  1236. proxies = {}
  1237. else:
  1238. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1239. else:
  1240. proxies = compat_urllib_request.getproxies()
  1241. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1242. if 'http' in proxies and 'https' not in proxies:
  1243. proxies['https'] = proxies['http']
  1244. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1245. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1246. https_handler = make_HTTPS_handler(
  1247. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1248. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1249. opener = compat_urllib_request.build_opener(
  1250. https_handler, proxy_handler, cookie_processor, ydlh)
  1251. # Delete the default user-agent header, which would otherwise apply in
  1252. # cases where our custom HTTP handler doesn't come into play
  1253. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1254. opener.addheaders = []
  1255. self._opener = opener
  1256. def encode(self, s):
  1257. if isinstance(s, bytes):
  1258. return s # Already encoded
  1259. try:
  1260. return s.encode(self.get_encoding())
  1261. except UnicodeEncodeError as err:
  1262. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1263. raise
  1264. def get_encoding(self):
  1265. encoding = self.params.get('encoding')
  1266. if encoding is None:
  1267. encoding = preferredencoding()
  1268. return encoding