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.

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