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.

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