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.

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