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.

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