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.

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