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.

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