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.

1398 lines
60 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_index': i + playliststart,
  593. 'extractor': ie_result['extractor'],
  594. 'webpage_url': ie_result['webpage_url'],
  595. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  596. 'extractor_key': ie_result['extractor_key'],
  597. }
  598. reason = self._match_entry(entry)
  599. if reason is not None:
  600. self.to_screen('[download] ' + reason)
  601. continue
  602. entry_result = self.process_ie_result(entry,
  603. download=download,
  604. extra_info=extra)
  605. playlist_results.append(entry_result)
  606. ie_result['entries'] = playlist_results
  607. return ie_result
  608. elif result_type == 'compat_list':
  609. def _fixup(r):
  610. self.add_extra_info(r,
  611. {
  612. 'extractor': ie_result['extractor'],
  613. 'webpage_url': ie_result['webpage_url'],
  614. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  615. 'extractor_key': ie_result['extractor_key'],
  616. })
  617. return r
  618. ie_result['entries'] = [
  619. self.process_ie_result(_fixup(r), download, extra_info)
  620. for r in ie_result['entries']
  621. ]
  622. return ie_result
  623. else:
  624. raise Exception('Invalid result type: %s' % result_type)
  625. def select_format(self, format_spec, available_formats):
  626. if format_spec == 'best' or format_spec is None:
  627. return available_formats[-1]
  628. elif format_spec == 'worst':
  629. return available_formats[0]
  630. elif format_spec == 'bestaudio':
  631. audio_formats = [
  632. f for f in available_formats
  633. if f.get('vcodec') == 'none']
  634. if audio_formats:
  635. return audio_formats[-1]
  636. elif format_spec == 'worstaudio':
  637. audio_formats = [
  638. f for f in available_formats
  639. if f.get('vcodec') == 'none']
  640. if audio_formats:
  641. return audio_formats[0]
  642. elif format_spec == 'bestvideo':
  643. video_formats = [
  644. f for f in available_formats
  645. if f.get('acodec') == 'none']
  646. if video_formats:
  647. return video_formats[-1]
  648. elif format_spec == 'worstvideo':
  649. video_formats = [
  650. f for f in available_formats
  651. if f.get('acodec') == 'none']
  652. if video_formats:
  653. return video_formats[0]
  654. else:
  655. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a']
  656. if format_spec in extensions:
  657. filter_f = lambda f: f['ext'] == format_spec
  658. else:
  659. filter_f = lambda f: f['format_id'] == format_spec
  660. matches = list(filter(filter_f, available_formats))
  661. if matches:
  662. return matches[-1]
  663. return None
  664. def process_video_result(self, info_dict, download=True):
  665. assert info_dict.get('_type', 'video') == 'video'
  666. if 'id' not in info_dict:
  667. raise ExtractorError('Missing "id" field in extractor result')
  668. if 'title' not in info_dict:
  669. raise ExtractorError('Missing "title" field in extractor result')
  670. if 'playlist' not in info_dict:
  671. # It isn't part of a playlist
  672. info_dict['playlist'] = None
  673. info_dict['playlist_index'] = None
  674. thumbnails = info_dict.get('thumbnails')
  675. if thumbnails:
  676. thumbnails.sort(key=lambda t: (
  677. t.get('width'), t.get('height'), t.get('url')))
  678. for t in thumbnails:
  679. if 'width' in t and 'height' in t:
  680. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  681. if thumbnails and 'thumbnail' not in info_dict:
  682. info_dict['thumbnail'] = thumbnails[-1]['url']
  683. if 'display_id' not in info_dict and 'id' in info_dict:
  684. info_dict['display_id'] = info_dict['id']
  685. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  686. upload_date = datetime.datetime.utcfromtimestamp(
  687. info_dict['timestamp'])
  688. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  689. # This extractors handle format selection themselves
  690. if info_dict['extractor'] in ['Youku']:
  691. if download:
  692. self.process_info(info_dict)
  693. return info_dict
  694. # We now pick which formats have to be downloaded
  695. if info_dict.get('formats') is None:
  696. # There's only one format available
  697. formats = [info_dict]
  698. else:
  699. formats = info_dict['formats']
  700. if not formats:
  701. raise ExtractorError('No video formats found!')
  702. # We check that all the formats have the format and format_id fields
  703. for i, format in enumerate(formats):
  704. if 'url' not in format:
  705. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  706. if format.get('format_id') is None:
  707. format['format_id'] = compat_str(i)
  708. if format.get('format') is None:
  709. format['format'] = '{id} - {res}{note}'.format(
  710. id=format['format_id'],
  711. res=self.format_resolution(format),
  712. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  713. )
  714. # Automatically determine file extension if missing
  715. if 'ext' not in format:
  716. format['ext'] = determine_ext(format['url']).lower()
  717. format_limit = self.params.get('format_limit', None)
  718. if format_limit:
  719. formats = list(takewhile_inclusive(
  720. lambda f: f['format_id'] != format_limit, formats
  721. ))
  722. # TODO Central sorting goes here
  723. if formats[0] is not info_dict:
  724. # only set the 'formats' fields if the original info_dict list them
  725. # otherwise we end up with a circular reference, the first (and unique)
  726. # element in the 'formats' field in info_dict is info_dict itself,
  727. # wich can't be exported to json
  728. info_dict['formats'] = formats
  729. if self.params.get('listformats', None):
  730. self.list_formats(info_dict)
  731. return
  732. req_format = self.params.get('format')
  733. if req_format is None:
  734. req_format = 'best'
  735. formats_to_download = []
  736. # The -1 is for supporting YoutubeIE
  737. if req_format in ('-1', 'all'):
  738. formats_to_download = formats
  739. else:
  740. for rfstr in req_format.split(','):
  741. # We can accept formats requested in the format: 34/5/best, we pick
  742. # the first that is available, starting from left
  743. req_formats = rfstr.split('/')
  744. for rf in req_formats:
  745. if re.match(r'.+?\+.+?', rf) is not None:
  746. # Two formats have been requested like '137+139'
  747. format_1, format_2 = rf.split('+')
  748. formats_info = (self.select_format(format_1, formats),
  749. self.select_format(format_2, formats))
  750. if all(formats_info):
  751. selected_format = {
  752. 'requested_formats': formats_info,
  753. 'format': rf,
  754. 'ext': formats_info[0]['ext'],
  755. }
  756. else:
  757. selected_format = None
  758. else:
  759. selected_format = self.select_format(rf, formats)
  760. if selected_format is not None:
  761. formats_to_download.append(selected_format)
  762. break
  763. if not formats_to_download:
  764. raise ExtractorError('requested format not available',
  765. expected=True)
  766. if download:
  767. if len(formats_to_download) > 1:
  768. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  769. for format in formats_to_download:
  770. new_info = dict(info_dict)
  771. new_info.update(format)
  772. self.process_info(new_info)
  773. # We update the info dict with the best quality format (backwards compatibility)
  774. info_dict.update(formats_to_download[-1])
  775. return info_dict
  776. def process_info(self, info_dict):
  777. """Process a single resolved IE result."""
  778. assert info_dict.get('_type', 'video') == 'video'
  779. max_downloads = self.params.get('max_downloads')
  780. if max_downloads is not None:
  781. if self._num_downloads >= int(max_downloads):
  782. raise MaxDownloadsReached()
  783. info_dict['fulltitle'] = info_dict['title']
  784. if len(info_dict['title']) > 200:
  785. info_dict['title'] = info_dict['title'][:197] + '...'
  786. # Keep for backwards compatibility
  787. info_dict['stitle'] = info_dict['title']
  788. if 'format' not in info_dict:
  789. info_dict['format'] = info_dict['ext']
  790. reason = self._match_entry(info_dict)
  791. if reason is not None:
  792. self.to_screen('[download] ' + reason)
  793. return
  794. self._num_downloads += 1
  795. filename = self.prepare_filename(info_dict)
  796. # Forced printings
  797. if self.params.get('forcetitle', False):
  798. self.to_stdout(info_dict['fulltitle'])
  799. if self.params.get('forceid', False):
  800. self.to_stdout(info_dict['id'])
  801. if self.params.get('forceurl', False):
  802. # For RTMP URLs, also include the playpath
  803. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  804. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  805. self.to_stdout(info_dict['thumbnail'])
  806. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  807. self.to_stdout(info_dict['description'])
  808. if self.params.get('forcefilename', False) and filename is not None:
  809. self.to_stdout(filename)
  810. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  811. self.to_stdout(formatSeconds(info_dict['duration']))
  812. if self.params.get('forceformat', False):
  813. self.to_stdout(info_dict['format'])
  814. if self.params.get('forcejson', False):
  815. info_dict['_filename'] = filename
  816. self.to_stdout(json.dumps(info_dict))
  817. if self.params.get('dump_single_json', False):
  818. info_dict['_filename'] = filename
  819. # Do nothing else if in simulate mode
  820. if self.params.get('simulate', False):
  821. return
  822. if filename is None:
  823. return
  824. try:
  825. dn = os.path.dirname(encodeFilename(filename))
  826. if dn and not os.path.exists(dn):
  827. os.makedirs(dn)
  828. except (OSError, IOError) as err:
  829. self.report_error('unable to create directory ' + compat_str(err))
  830. return
  831. if self.params.get('writedescription', False):
  832. descfn = filename + '.description'
  833. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  834. self.to_screen('[info] Video description is already present')
  835. else:
  836. try:
  837. self.to_screen('[info] Writing video description to: ' + descfn)
  838. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  839. descfile.write(info_dict['description'])
  840. except (KeyError, TypeError):
  841. self.report_warning('There\'s no description to write.')
  842. except (OSError, IOError):
  843. self.report_error('Cannot write description file ' + descfn)
  844. return
  845. if self.params.get('writeannotations', False):
  846. annofn = filename + '.annotations.xml'
  847. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  848. self.to_screen('[info] Video annotations are already present')
  849. else:
  850. try:
  851. self.to_screen('[info] Writing video annotations to: ' + annofn)
  852. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  853. annofile.write(info_dict['annotations'])
  854. except (KeyError, TypeError):
  855. self.report_warning('There are no annotations to write.')
  856. except (OSError, IOError):
  857. self.report_error('Cannot write annotations file: ' + annofn)
  858. return
  859. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  860. self.params.get('writeautomaticsub')])
  861. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  862. # subtitles download errors are already managed as troubles in relevant IE
  863. # that way it will silently go on when used with unsupporting IE
  864. subtitles = info_dict['subtitles']
  865. sub_format = self.params.get('subtitlesformat', 'srt')
  866. for sub_lang in subtitles.keys():
  867. sub = subtitles[sub_lang]
  868. if sub is None:
  869. continue
  870. try:
  871. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  872. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  873. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  874. else:
  875. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  876. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  877. subfile.write(sub)
  878. except (OSError, IOError):
  879. self.report_error('Cannot write subtitles file ' + sub_filename)
  880. return
  881. if self.params.get('writeinfojson', False):
  882. infofn = os.path.splitext(filename)[0] + '.info.json'
  883. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  884. self.to_screen('[info] Video description metadata is already present')
  885. else:
  886. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  887. try:
  888. write_json_file(info_dict, encodeFilename(infofn))
  889. except (OSError, IOError):
  890. self.report_error('Cannot write metadata to JSON file ' + infofn)
  891. return
  892. if self.params.get('writethumbnail', False):
  893. if info_dict.get('thumbnail') is not None:
  894. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  895. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  896. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  897. self.to_screen('[%s] %s: Thumbnail is already present' %
  898. (info_dict['extractor'], info_dict['id']))
  899. else:
  900. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  901. (info_dict['extractor'], info_dict['id']))
  902. try:
  903. uf = self.urlopen(info_dict['thumbnail'])
  904. with open(thumb_filename, 'wb') as thumbf:
  905. shutil.copyfileobj(uf, thumbf)
  906. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  907. (info_dict['extractor'], info_dict['id'], thumb_filename))
  908. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  909. self.report_warning('Unable to download thumbnail "%s": %s' %
  910. (info_dict['thumbnail'], compat_str(err)))
  911. if not self.params.get('skip_download', False):
  912. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  913. success = True
  914. else:
  915. try:
  916. def dl(name, info):
  917. fd = get_suitable_downloader(info)(self, self.params)
  918. for ph in self._progress_hooks:
  919. fd.add_progress_hook(ph)
  920. if self.params.get('verbose'):
  921. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  922. return fd.download(name, info)
  923. if info_dict.get('requested_formats') is not None:
  924. downloaded = []
  925. success = True
  926. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  927. if not merger._executable:
  928. postprocessors = []
  929. self.report_warning('You have requested multiple '
  930. 'formats but ffmpeg or avconv are not installed.'
  931. ' The formats won\'t be merged')
  932. else:
  933. postprocessors = [merger]
  934. for f in info_dict['requested_formats']:
  935. new_info = dict(info_dict)
  936. new_info.update(f)
  937. fname = self.prepare_filename(new_info)
  938. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  939. downloaded.append(fname)
  940. partial_success = dl(fname, new_info)
  941. success = success and partial_success
  942. info_dict['__postprocessors'] = postprocessors
  943. info_dict['__files_to_merge'] = downloaded
  944. else:
  945. # Just a single file
  946. success = dl(filename, info_dict)
  947. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  948. self.report_error('unable to download video data: %s' % str(err))
  949. return
  950. except (OSError, IOError) as err:
  951. raise UnavailableVideoError(err)
  952. except (ContentTooShortError, ) as err:
  953. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  954. return
  955. if success:
  956. try:
  957. self.post_process(filename, info_dict)
  958. except (PostProcessingError) as err:
  959. self.report_error('postprocessing: %s' % str(err))
  960. return
  961. self.record_download_archive(info_dict)
  962. def download(self, url_list):
  963. """Download a given list of URLs."""
  964. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  965. if (len(url_list) > 1 and
  966. '%' not in outtmpl
  967. and self.params.get('max_downloads') != 1):
  968. raise SameFileError(outtmpl)
  969. for url in url_list:
  970. try:
  971. #It also downloads the videos
  972. res = self.extract_info(url)
  973. except UnavailableVideoError:
  974. self.report_error('unable to download video')
  975. except MaxDownloadsReached:
  976. self.to_screen('[info] Maximum number of downloaded files reached.')
  977. raise
  978. else:
  979. if self.params.get('dump_single_json', False):
  980. self.to_stdout(json.dumps(res))
  981. return self._download_retcode
  982. def download_with_info_file(self, info_filename):
  983. with io.open(info_filename, 'r', encoding='utf-8') as f:
  984. info = json.load(f)
  985. try:
  986. self.process_ie_result(info, download=True)
  987. except DownloadError:
  988. webpage_url = info.get('webpage_url')
  989. if webpage_url is not None:
  990. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  991. return self.download([webpage_url])
  992. else:
  993. raise
  994. return self._download_retcode
  995. def post_process(self, filename, ie_info):
  996. """Run all the postprocessors on the given file."""
  997. info = dict(ie_info)
  998. info['filepath'] = filename
  999. keep_video = None
  1000. pps_chain = []
  1001. if ie_info.get('__postprocessors') is not None:
  1002. pps_chain.extend(ie_info['__postprocessors'])
  1003. pps_chain.extend(self._pps)
  1004. for pp in pps_chain:
  1005. try:
  1006. keep_video_wish, new_info = pp.run(info)
  1007. if keep_video_wish is not None:
  1008. if keep_video_wish:
  1009. keep_video = keep_video_wish
  1010. elif keep_video is None:
  1011. # No clear decision yet, let IE decide
  1012. keep_video = keep_video_wish
  1013. except PostProcessingError as e:
  1014. self.report_error(e.msg)
  1015. if keep_video is False and not self.params.get('keepvideo', False):
  1016. try:
  1017. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1018. os.remove(encodeFilename(filename))
  1019. except (IOError, OSError):
  1020. self.report_warning('Unable to remove downloaded video file')
  1021. def _make_archive_id(self, info_dict):
  1022. # Future-proof against any change in case
  1023. # and backwards compatibility with prior versions
  1024. extractor = info_dict.get('extractor_key')
  1025. if extractor is None:
  1026. if 'id' in info_dict:
  1027. extractor = info_dict.get('ie_key') # key in a playlist
  1028. if extractor is None:
  1029. return None # Incomplete video information
  1030. return extractor.lower() + ' ' + info_dict['id']
  1031. def in_download_archive(self, info_dict):
  1032. fn = self.params.get('download_archive')
  1033. if fn is None:
  1034. return False
  1035. vid_id = self._make_archive_id(info_dict)
  1036. if vid_id is None:
  1037. return False # Incomplete video information
  1038. try:
  1039. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1040. for line in archive_file:
  1041. if line.strip() == vid_id:
  1042. return True
  1043. except IOError as ioe:
  1044. if ioe.errno != errno.ENOENT:
  1045. raise
  1046. return False
  1047. def record_download_archive(self, info_dict):
  1048. fn = self.params.get('download_archive')
  1049. if fn is None:
  1050. return
  1051. vid_id = self._make_archive_id(info_dict)
  1052. assert vid_id
  1053. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1054. archive_file.write(vid_id + '\n')
  1055. @staticmethod
  1056. def format_resolution(format, default='unknown'):
  1057. if format.get('vcodec') == 'none':
  1058. return 'audio only'
  1059. if format.get('resolution') is not None:
  1060. return format['resolution']
  1061. if format.get('height') is not None:
  1062. if format.get('width') is not None:
  1063. res = '%sx%s' % (format['width'], format['height'])
  1064. else:
  1065. res = '%sp' % format['height']
  1066. elif format.get('width') is not None:
  1067. res = '?x%d' % format['width']
  1068. else:
  1069. res = default
  1070. return res
  1071. def _format_note(self, fdict):
  1072. res = ''
  1073. if fdict.get('ext') in ['f4f', 'f4m']:
  1074. res += '(unsupported) '
  1075. if fdict.get('format_note') is not None:
  1076. res += fdict['format_note'] + ' '
  1077. if fdict.get('tbr') is not None:
  1078. res += '%4dk ' % fdict['tbr']
  1079. if fdict.get('container') is not None:
  1080. if res:
  1081. res += ', '
  1082. res += '%s container' % fdict['container']
  1083. if (fdict.get('vcodec') is not None and
  1084. fdict.get('vcodec') != 'none'):
  1085. if res:
  1086. res += ', '
  1087. res += fdict['vcodec']
  1088. if fdict.get('vbr') is not None:
  1089. res += '@'
  1090. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1091. res += 'video@'
  1092. if fdict.get('vbr') is not None:
  1093. res += '%4dk' % fdict['vbr']
  1094. if fdict.get('fps') is not None:
  1095. res += ', %sfps' % fdict['fps']
  1096. if fdict.get('acodec') is not None:
  1097. if res:
  1098. res += ', '
  1099. if fdict['acodec'] == 'none':
  1100. res += 'video only'
  1101. else:
  1102. res += '%-5s' % fdict['acodec']
  1103. elif fdict.get('abr') is not None:
  1104. if res:
  1105. res += ', '
  1106. res += 'audio'
  1107. if fdict.get('abr') is not None:
  1108. res += '@%3dk' % fdict['abr']
  1109. if fdict.get('asr') is not None:
  1110. res += ' (%5dHz)' % fdict['asr']
  1111. if fdict.get('filesize') is not None:
  1112. if res:
  1113. res += ', '
  1114. res += format_bytes(fdict['filesize'])
  1115. elif fdict.get('filesize_approx') is not None:
  1116. if res:
  1117. res += ', '
  1118. res += '~' + format_bytes(fdict['filesize_approx'])
  1119. return res
  1120. def list_formats(self, info_dict):
  1121. def line(format, idlen=20):
  1122. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1123. format['format_id'],
  1124. format['ext'],
  1125. self.format_resolution(format),
  1126. self._format_note(format),
  1127. ))
  1128. formats = info_dict.get('formats', [info_dict])
  1129. idlen = max(len('format code'),
  1130. max(len(f['format_id']) for f in formats))
  1131. formats_s = [line(f, idlen) for f in formats]
  1132. if len(formats) > 1:
  1133. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1134. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1135. header_line = line({
  1136. 'format_id': 'format code', 'ext': 'extension',
  1137. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1138. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1139. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1140. def urlopen(self, req):
  1141. """ Start an HTTP download """
  1142. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1143. # always respected by websites, some tend to give out URLs with non percent-encoded
  1144. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1145. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1146. # To work around aforementioned issue we will replace request's original URL with
  1147. # percent-encoded one
  1148. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1149. url = req if req_is_string else req.get_full_url()
  1150. url_escaped = escape_url(url)
  1151. # Substitute URL if any change after escaping
  1152. if url != url_escaped:
  1153. if req_is_string:
  1154. req = url_escaped
  1155. else:
  1156. req = compat_urllib_request.Request(
  1157. url_escaped, data=req.data, headers=req.headers,
  1158. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1159. return self._opener.open(req, timeout=self._socket_timeout)
  1160. def print_debug_header(self):
  1161. if not self.params.get('verbose'):
  1162. return
  1163. if type('') is not compat_str:
  1164. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1165. self.report_warning(
  1166. 'Your Python is broken! Update to a newer and supported version')
  1167. encoding_str = (
  1168. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1169. locale.getpreferredencoding(),
  1170. sys.getfilesystemencoding(),
  1171. sys.stdout.encoding,
  1172. self.get_encoding()))
  1173. write_string(encoding_str, encoding=None)
  1174. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1175. try:
  1176. sp = subprocess.Popen(
  1177. ['git', 'rev-parse', '--short', 'HEAD'],
  1178. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1179. cwd=os.path.dirname(os.path.abspath(__file__)))
  1180. out, err = sp.communicate()
  1181. out = out.decode().strip()
  1182. if re.match('[0-9a-f]+', out):
  1183. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1184. except:
  1185. try:
  1186. sys.exc_clear()
  1187. except:
  1188. pass
  1189. self._write_string('[debug] Python version %s - %s\n' % (
  1190. platform.python_version(), platform_name()))
  1191. exe_versions = FFmpegPostProcessor.get_versions()
  1192. exe_versions['rtmpdump'] = rtmpdump_version()
  1193. exe_str = ', '.join(
  1194. '%s %s' % (exe, v)
  1195. for exe, v in sorted(exe_versions.items())
  1196. if v
  1197. )
  1198. if not exe_str:
  1199. exe_str = 'none'
  1200. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1201. proxy_map = {}
  1202. for handler in self._opener.handlers:
  1203. if hasattr(handler, 'proxies'):
  1204. proxy_map.update(handler.proxies)
  1205. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1206. def _setup_opener(self):
  1207. timeout_val = self.params.get('socket_timeout')
  1208. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1209. opts_cookiefile = self.params.get('cookiefile')
  1210. opts_proxy = self.params.get('proxy')
  1211. if opts_cookiefile is None:
  1212. self.cookiejar = compat_cookiejar.CookieJar()
  1213. else:
  1214. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1215. opts_cookiefile)
  1216. if os.access(opts_cookiefile, os.R_OK):
  1217. self.cookiejar.load()
  1218. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1219. self.cookiejar)
  1220. if opts_proxy is not None:
  1221. if opts_proxy == '':
  1222. proxies = {}
  1223. else:
  1224. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1225. else:
  1226. proxies = compat_urllib_request.getproxies()
  1227. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1228. if 'http' in proxies and 'https' not in proxies:
  1229. proxies['https'] = proxies['http']
  1230. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1231. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1232. https_handler = make_HTTPS_handler(
  1233. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1234. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1235. opener = compat_urllib_request.build_opener(
  1236. https_handler, proxy_handler, cookie_processor, ydlh)
  1237. # Delete the default user-agent header, which would otherwise apply in
  1238. # cases where our custom HTTP handler doesn't come into play
  1239. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1240. opener.addheaders = []
  1241. self._opener = opener
  1242. def encode(self, s):
  1243. if isinstance(s, bytes):
  1244. return s # Already encoded
  1245. try:
  1246. return s.encode(self.get_encoding())
  1247. except UnicodeEncodeError as err:
  1248. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1249. raise
  1250. def get_encoding(self):
  1251. encoding = self.params.get('encoding')
  1252. if encoding is None:
  1253. encoding = preferredencoding()
  1254. return encoding