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.

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