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.

1263 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_default_extra_info(ie_result, ie, url)
  462. if process:
  463. return self.process_ie_result(ie_result, download, extra_info)
  464. else:
  465. return ie_result
  466. except ExtractorError as de: # An error we somewhat expected
  467. self.report_error(compat_str(de), de.format_traceback())
  468. break
  469. except MaxDownloadsReached:
  470. raise
  471. except Exception as e:
  472. if self.params.get('ignoreerrors', False):
  473. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  474. break
  475. else:
  476. raise
  477. else:
  478. self.report_error('no suitable InfoExtractor for URL %s' % url)
  479. def add_default_extra_info(self, ie_result, ie, url):
  480. self.add_extra_info(ie_result, {
  481. 'extractor': ie.IE_NAME,
  482. 'webpage_url': url,
  483. 'webpage_url_basename': url_basename(url),
  484. 'extractor_key': ie.ie_key(),
  485. })
  486. def process_ie_result(self, ie_result, download=True, extra_info={}):
  487. """
  488. Take the result of the ie(may be modified) and resolve all unresolved
  489. references (URLs, playlist items).
  490. It will also download the videos if 'download'.
  491. Returns the resolved ie_result.
  492. """
  493. result_type = ie_result.get('_type', 'video') # If not given we suppose it's a video, support the default old system
  494. if result_type == 'video':
  495. self.add_extra_info(ie_result, extra_info)
  496. return self.process_video_result(ie_result, download=download)
  497. elif result_type == 'url':
  498. # We have to add extra_info to the results because it may be
  499. # contained in a playlist
  500. return self.extract_info(ie_result['url'],
  501. download,
  502. ie_key=ie_result.get('ie_key'),
  503. extra_info=extra_info)
  504. elif result_type == 'url_transparent':
  505. # Use the information from the embedding page
  506. info = self.extract_info(
  507. ie_result['url'], ie_key=ie_result.get('ie_key'),
  508. extra_info=extra_info, download=False, process=False)
  509. def make_result(embedded_info):
  510. new_result = ie_result.copy()
  511. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  512. 'entries', 'ie_key', 'duration',
  513. 'subtitles', 'annotations', 'format',
  514. 'thumbnail', 'thumbnails'):
  515. if f in new_result:
  516. del new_result[f]
  517. if f in embedded_info:
  518. new_result[f] = embedded_info[f]
  519. return new_result
  520. new_result = make_result(info)
  521. assert new_result.get('_type') != 'url_transparent'
  522. if new_result.get('_type') == 'compat_list':
  523. new_result['entries'] = [
  524. make_result(e) for e in new_result['entries']]
  525. return self.process_ie_result(
  526. new_result, download=download, extra_info=extra_info)
  527. elif result_type == 'playlist':
  528. # We process each entry in the playlist
  529. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  530. self.to_screen('[download] Downloading playlist: %s' % playlist)
  531. playlist_results = []
  532. playliststart = self.params.get('playliststart', 1) - 1
  533. playlistend = self.params.get('playlistend', None)
  534. # For backwards compatibility, interpret -1 as whole list
  535. if playlistend == -1:
  536. playlistend = None
  537. if isinstance(ie_result['entries'], list):
  538. n_all_entries = len(ie_result['entries'])
  539. entries = ie_result['entries'][playliststart:playlistend]
  540. n_entries = len(entries)
  541. self.to_screen(
  542. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  543. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  544. else:
  545. assert isinstance(ie_result['entries'], PagedList)
  546. entries = ie_result['entries'].getslice(
  547. playliststart, playlistend)
  548. n_entries = len(entries)
  549. self.to_screen(
  550. "[%s] playlist %s: Downloading %d videos" %
  551. (ie_result['extractor'], playlist, n_entries))
  552. for i, entry in enumerate(entries, 1):
  553. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  554. extra = {
  555. 'playlist': playlist,
  556. 'playlist_index': i + playliststart,
  557. 'extractor': ie_result['extractor'],
  558. 'webpage_url': ie_result['webpage_url'],
  559. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  560. 'extractor_key': ie_result['extractor_key'],
  561. }
  562. reason = self._match_entry(entry)
  563. if reason is not None:
  564. self.to_screen('[download] ' + reason)
  565. continue
  566. entry_result = self.process_ie_result(entry,
  567. download=download,
  568. extra_info=extra)
  569. playlist_results.append(entry_result)
  570. ie_result['entries'] = playlist_results
  571. return ie_result
  572. elif result_type == 'compat_list':
  573. def _fixup(r):
  574. self.add_extra_info(r,
  575. {
  576. 'extractor': ie_result['extractor'],
  577. 'webpage_url': ie_result['webpage_url'],
  578. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  579. 'extractor_key': ie_result['extractor_key'],
  580. })
  581. return r
  582. ie_result['entries'] = [
  583. self.process_ie_result(_fixup(r), download, extra_info)
  584. for r in ie_result['entries']
  585. ]
  586. return ie_result
  587. else:
  588. raise Exception('Invalid result type: %s' % result_type)
  589. def select_format(self, format_spec, available_formats):
  590. if format_spec == 'best' or format_spec is None:
  591. return available_formats[-1]
  592. elif format_spec == 'worst':
  593. return available_formats[0]
  594. elif format_spec == 'bestaudio':
  595. audio_formats = [
  596. f for f in available_formats
  597. if f.get('vcodec') == 'none']
  598. if audio_formats:
  599. return audio_formats[-1]
  600. elif format_spec == 'worstaudio':
  601. audio_formats = [
  602. f for f in available_formats
  603. if f.get('vcodec') == 'none']
  604. if audio_formats:
  605. return audio_formats[0]
  606. elif format_spec == 'bestvideo':
  607. video_formats = [
  608. f for f in available_formats
  609. if f.get('acodec') == 'none']
  610. if video_formats:
  611. return video_formats[-1]
  612. elif format_spec == 'worstvideo':
  613. video_formats = [
  614. f for f in available_formats
  615. if f.get('acodec') == 'none']
  616. if video_formats:
  617. return video_formats[0]
  618. else:
  619. extensions = ['mp4', 'flv', 'webm', '3gp']
  620. if format_spec in extensions:
  621. filter_f = lambda f: f['ext'] == format_spec
  622. else:
  623. filter_f = lambda f: f['format_id'] == format_spec
  624. matches = list(filter(filter_f, available_formats))
  625. if matches:
  626. return matches[-1]
  627. return None
  628. def process_video_result(self, info_dict, download=True):
  629. assert info_dict.get('_type', 'video') == 'video'
  630. if 'playlist' not in info_dict:
  631. # It isn't part of a playlist
  632. info_dict['playlist'] = None
  633. info_dict['playlist_index'] = None
  634. if 'display_id' not in info_dict and 'id' in info_dict:
  635. info_dict['display_id'] = info_dict['id']
  636. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  637. upload_date = datetime.datetime.utcfromtimestamp(
  638. info_dict['timestamp'])
  639. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  640. # This extractors handle format selection themselves
  641. if info_dict['extractor'] in ['Youku']:
  642. if download:
  643. self.process_info(info_dict)
  644. return info_dict
  645. # We now pick which formats have to be downloaded
  646. if info_dict.get('formats') is None:
  647. # There's only one format available
  648. formats = [info_dict]
  649. else:
  650. formats = info_dict['formats']
  651. if not formats:
  652. raise ExtractorError('No video formats found!')
  653. # We check that all the formats have the format and format_id fields
  654. for i, format in enumerate(formats):
  655. if format.get('format_id') is None:
  656. format['format_id'] = compat_str(i)
  657. if format.get('format') is None:
  658. format['format'] = '{id} - {res}{note}'.format(
  659. id=format['format_id'],
  660. res=self.format_resolution(format),
  661. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  662. )
  663. # Automatically determine file extension if missing
  664. if 'ext' not in format:
  665. format['ext'] = determine_ext(format['url'])
  666. format_limit = self.params.get('format_limit', None)
  667. if format_limit:
  668. formats = list(takewhile_inclusive(
  669. lambda f: f['format_id'] != format_limit, formats
  670. ))
  671. # TODO Central sorting goes here
  672. if formats[0] is not info_dict:
  673. # only set the 'formats' fields if the original info_dict list them
  674. # otherwise we end up with a circular reference, the first (and unique)
  675. # element in the 'formats' field in info_dict is info_dict itself,
  676. # wich can't be exported to json
  677. info_dict['formats'] = formats
  678. if self.params.get('listformats', None):
  679. self.list_formats(info_dict)
  680. return
  681. req_format = self.params.get('format')
  682. if req_format is None:
  683. req_format = 'best'
  684. formats_to_download = []
  685. # The -1 is for supporting YoutubeIE
  686. if req_format in ('-1', 'all'):
  687. formats_to_download = formats
  688. else:
  689. # We can accept formats requested in the format: 34/5/best, we pick
  690. # the first that is available, starting from left
  691. req_formats = req_format.split('/')
  692. for rf in req_formats:
  693. if re.match(r'.+?\+.+?', rf) is not None:
  694. # Two formats have been requested like '137+139'
  695. format_1, format_2 = rf.split('+')
  696. formats_info = (self.select_format(format_1, formats),
  697. self.select_format(format_2, formats))
  698. if all(formats_info):
  699. selected_format = {
  700. 'requested_formats': formats_info,
  701. 'format': rf,
  702. 'ext': formats_info[0]['ext'],
  703. }
  704. else:
  705. selected_format = None
  706. else:
  707. selected_format = self.select_format(rf, formats)
  708. if selected_format is not None:
  709. formats_to_download = [selected_format]
  710. break
  711. if not formats_to_download:
  712. raise ExtractorError('requested format not available',
  713. expected=True)
  714. if download:
  715. if len(formats_to_download) > 1:
  716. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  717. for format in formats_to_download:
  718. new_info = dict(info_dict)
  719. new_info.update(format)
  720. self.process_info(new_info)
  721. # We update the info dict with the best quality format (backwards compatibility)
  722. info_dict.update(formats_to_download[-1])
  723. return info_dict
  724. def process_info(self, info_dict):
  725. """Process a single resolved IE result."""
  726. assert info_dict.get('_type', 'video') == 'video'
  727. max_downloads = self.params.get('max_downloads')
  728. if max_downloads is not None:
  729. if self._num_downloads >= int(max_downloads):
  730. raise MaxDownloadsReached()
  731. info_dict['fulltitle'] = info_dict['title']
  732. if len(info_dict['title']) > 200:
  733. info_dict['title'] = info_dict['title'][:197] + '...'
  734. # Keep for backwards compatibility
  735. info_dict['stitle'] = info_dict['title']
  736. if not 'format' in info_dict:
  737. info_dict['format'] = info_dict['ext']
  738. reason = self._match_entry(info_dict)
  739. if reason is not None:
  740. self.to_screen('[download] ' + reason)
  741. return
  742. self._num_downloads += 1
  743. filename = self.prepare_filename(info_dict)
  744. # Forced printings
  745. if self.params.get('forcetitle', False):
  746. self.to_stdout(info_dict['fulltitle'])
  747. if self.params.get('forceid', False):
  748. self.to_stdout(info_dict['id'])
  749. if self.params.get('forceurl', False):
  750. # For RTMP URLs, also include the playpath
  751. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  752. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  753. self.to_stdout(info_dict['thumbnail'])
  754. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  755. self.to_stdout(info_dict['description'])
  756. if self.params.get('forcefilename', False) and filename is not None:
  757. self.to_stdout(filename)
  758. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  759. self.to_stdout(formatSeconds(info_dict['duration']))
  760. if self.params.get('forceformat', False):
  761. self.to_stdout(info_dict['format'])
  762. if self.params.get('forcejson', False):
  763. info_dict['_filename'] = filename
  764. self.to_stdout(json.dumps(info_dict))
  765. # Do nothing else if in simulate mode
  766. if self.params.get('simulate', False):
  767. return
  768. if filename is None:
  769. return
  770. try:
  771. dn = os.path.dirname(encodeFilename(filename))
  772. if dn != '' and not os.path.exists(dn):
  773. os.makedirs(dn)
  774. except (OSError, IOError) as err:
  775. self.report_error('unable to create directory ' + compat_str(err))
  776. return
  777. if self.params.get('writedescription', False):
  778. descfn = filename + '.description'
  779. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  780. self.to_screen('[info] Video description is already present')
  781. else:
  782. try:
  783. self.to_screen('[info] Writing video description to: ' + descfn)
  784. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  785. descfile.write(info_dict['description'])
  786. except (KeyError, TypeError):
  787. self.report_warning('There\'s no description to write.')
  788. except (OSError, IOError):
  789. self.report_error('Cannot write description file ' + descfn)
  790. return
  791. if self.params.get('writeannotations', False):
  792. annofn = filename + '.annotations.xml'
  793. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  794. self.to_screen('[info] Video annotations are already present')
  795. else:
  796. try:
  797. self.to_screen('[info] Writing video annotations to: ' + annofn)
  798. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  799. annofile.write(info_dict['annotations'])
  800. except (KeyError, TypeError):
  801. self.report_warning('There are no annotations to write.')
  802. except (OSError, IOError):
  803. self.report_error('Cannot write annotations file: ' + annofn)
  804. return
  805. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  806. self.params.get('writeautomaticsub')])
  807. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  808. # subtitles download errors are already managed as troubles in relevant IE
  809. # that way it will silently go on when used with unsupporting IE
  810. subtitles = info_dict['subtitles']
  811. sub_format = self.params.get('subtitlesformat', 'srt')
  812. for sub_lang in subtitles.keys():
  813. sub = subtitles[sub_lang]
  814. if sub is None:
  815. continue
  816. try:
  817. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  818. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  819. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  820. else:
  821. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  822. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  823. subfile.write(sub)
  824. except (OSError, IOError):
  825. self.report_error('Cannot write subtitles file ' + descfn)
  826. return
  827. if self.params.get('writeinfojson', False):
  828. infofn = os.path.splitext(filename)[0] + '.info.json'
  829. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  830. self.to_screen('[info] Video description metadata is already present')
  831. else:
  832. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  833. try:
  834. write_json_file(info_dict, encodeFilename(infofn))
  835. except (OSError, IOError):
  836. self.report_error('Cannot write metadata to JSON file ' + infofn)
  837. return
  838. if self.params.get('writethumbnail', False):
  839. if info_dict.get('thumbnail') is not None:
  840. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  841. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  842. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  843. self.to_screen('[%s] %s: Thumbnail is already present' %
  844. (info_dict['extractor'], info_dict['id']))
  845. else:
  846. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  847. (info_dict['extractor'], info_dict['id']))
  848. try:
  849. uf = self.urlopen(info_dict['thumbnail'])
  850. with open(thumb_filename, 'wb') as thumbf:
  851. shutil.copyfileobj(uf, thumbf)
  852. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  853. (info_dict['extractor'], info_dict['id'], thumb_filename))
  854. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  855. self.report_warning('Unable to download thumbnail "%s": %s' %
  856. (info_dict['thumbnail'], compat_str(err)))
  857. if not self.params.get('skip_download', False):
  858. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  859. success = True
  860. else:
  861. try:
  862. def dl(name, info):
  863. fd = get_suitable_downloader(info)(self, self.params)
  864. for ph in self._progress_hooks:
  865. fd.add_progress_hook(ph)
  866. return fd.download(name, info)
  867. if info_dict.get('requested_formats') is not None:
  868. downloaded = []
  869. success = True
  870. merger = FFmpegMergerPP(self)
  871. if not merger._get_executable():
  872. postprocessors = []
  873. self.report_warning('You have requested multiple '
  874. 'formats but ffmpeg or avconv are not installed.'
  875. ' The formats won\'t be merged')
  876. else:
  877. postprocessors = [merger]
  878. for f in info_dict['requested_formats']:
  879. new_info = dict(info_dict)
  880. new_info.update(f)
  881. fname = self.prepare_filename(new_info)
  882. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  883. downloaded.append(fname)
  884. partial_success = dl(fname, new_info)
  885. success = success and partial_success
  886. info_dict['__postprocessors'] = postprocessors
  887. info_dict['__files_to_merge'] = downloaded
  888. else:
  889. # Just a single file
  890. success = dl(filename, info_dict)
  891. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  892. self.report_error('unable to download video data: %s' % str(err))
  893. return
  894. except (OSError, IOError) as err:
  895. raise UnavailableVideoError(err)
  896. except (ContentTooShortError, ) as err:
  897. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  898. return
  899. if success:
  900. try:
  901. self.post_process(filename, info_dict)
  902. except (PostProcessingError) as err:
  903. self.report_error('postprocessing: %s' % str(err))
  904. return
  905. self.record_download_archive(info_dict)
  906. def download(self, url_list):
  907. """Download a given list of URLs."""
  908. if (len(url_list) > 1 and
  909. '%' not in self.params['outtmpl']
  910. and self.params.get('max_downloads') != 1):
  911. raise SameFileError(self.params['outtmpl'])
  912. for url in url_list:
  913. try:
  914. #It also downloads the videos
  915. self.extract_info(url)
  916. except UnavailableVideoError:
  917. self.report_error('unable to download video')
  918. except MaxDownloadsReached:
  919. self.to_screen('[info] Maximum number of downloaded files reached.')
  920. raise
  921. return self._download_retcode
  922. def download_with_info_file(self, info_filename):
  923. with io.open(info_filename, 'r', encoding='utf-8') as f:
  924. info = json.load(f)
  925. try:
  926. self.process_ie_result(info, download=True)
  927. except DownloadError:
  928. webpage_url = info.get('webpage_url')
  929. if webpage_url is not None:
  930. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  931. return self.download([webpage_url])
  932. else:
  933. raise
  934. return self._download_retcode
  935. def post_process(self, filename, ie_info):
  936. """Run all the postprocessors on the given file."""
  937. info = dict(ie_info)
  938. info['filepath'] = filename
  939. keep_video = None
  940. pps_chain = []
  941. if ie_info.get('__postprocessors') is not None:
  942. pps_chain.extend(ie_info['__postprocessors'])
  943. pps_chain.extend(self._pps)
  944. for pp in pps_chain:
  945. try:
  946. keep_video_wish, new_info = pp.run(info)
  947. if keep_video_wish is not None:
  948. if keep_video_wish:
  949. keep_video = keep_video_wish
  950. elif keep_video is None:
  951. # No clear decision yet, let IE decide
  952. keep_video = keep_video_wish
  953. except PostProcessingError as e:
  954. self.report_error(e.msg)
  955. if keep_video is False and not self.params.get('keepvideo', False):
  956. try:
  957. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  958. os.remove(encodeFilename(filename))
  959. except (IOError, OSError):
  960. self.report_warning('Unable to remove downloaded video file')
  961. def _make_archive_id(self, info_dict):
  962. # Future-proof against any change in case
  963. # and backwards compatibility with prior versions
  964. extractor = info_dict.get('extractor_key')
  965. if extractor is None:
  966. if 'id' in info_dict:
  967. extractor = info_dict.get('ie_key') # key in a playlist
  968. if extractor is None:
  969. return None # Incomplete video information
  970. return extractor.lower() + ' ' + info_dict['id']
  971. def in_download_archive(self, info_dict):
  972. fn = self.params.get('download_archive')
  973. if fn is None:
  974. return False
  975. vid_id = self._make_archive_id(info_dict)
  976. if vid_id is None:
  977. return False # Incomplete video information
  978. try:
  979. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  980. for line in archive_file:
  981. if line.strip() == vid_id:
  982. return True
  983. except IOError as ioe:
  984. if ioe.errno != errno.ENOENT:
  985. raise
  986. return False
  987. def record_download_archive(self, info_dict):
  988. fn = self.params.get('download_archive')
  989. if fn is None:
  990. return
  991. vid_id = self._make_archive_id(info_dict)
  992. assert vid_id
  993. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  994. archive_file.write(vid_id + '\n')
  995. @staticmethod
  996. def format_resolution(format, default='unknown'):
  997. if format.get('vcodec') == 'none':
  998. return 'audio only'
  999. if format.get('resolution') is not None:
  1000. return format['resolution']
  1001. if format.get('height') is not None:
  1002. if format.get('width') is not None:
  1003. res = '%sx%s' % (format['width'], format['height'])
  1004. else:
  1005. res = '%sp' % format['height']
  1006. elif format.get('width') is not None:
  1007. res = '?x%d' % format['width']
  1008. else:
  1009. res = default
  1010. return res
  1011. def list_formats(self, info_dict):
  1012. def format_note(fdict):
  1013. res = ''
  1014. if fdict.get('ext') in ['f4f', 'f4m']:
  1015. res += '(unsupported) '
  1016. if fdict.get('format_note') is not None:
  1017. res += fdict['format_note'] + ' '
  1018. if fdict.get('tbr') is not None:
  1019. res += '%4dk ' % fdict['tbr']
  1020. if fdict.get('container') is not None:
  1021. if res:
  1022. res += ', '
  1023. res += '%s container' % fdict['container']
  1024. if (fdict.get('vcodec') is not None and
  1025. fdict.get('vcodec') != 'none'):
  1026. if res:
  1027. res += ', '
  1028. res += fdict['vcodec']
  1029. if fdict.get('vbr') is not None:
  1030. res += '@'
  1031. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1032. res += 'video@'
  1033. if fdict.get('vbr') is not None:
  1034. res += '%4dk' % fdict['vbr']
  1035. if fdict.get('acodec') is not None:
  1036. if res:
  1037. res += ', '
  1038. if fdict['acodec'] == 'none':
  1039. res += 'video only'
  1040. else:
  1041. res += '%-5s' % fdict['acodec']
  1042. elif fdict.get('abr') is not None:
  1043. if res:
  1044. res += ', '
  1045. res += 'audio'
  1046. if fdict.get('abr') is not None:
  1047. res += '@%3dk' % fdict['abr']
  1048. if fdict.get('asr') is not None:
  1049. res += ' (%5dHz)' % fdict['asr']
  1050. if fdict.get('filesize') is not None:
  1051. if res:
  1052. res += ', '
  1053. res += format_bytes(fdict['filesize'])
  1054. return res
  1055. def line(format, idlen=20):
  1056. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1057. format['format_id'],
  1058. format['ext'],
  1059. self.format_resolution(format),
  1060. format_note(format),
  1061. ))
  1062. formats = info_dict.get('formats', [info_dict])
  1063. idlen = max(len('format code'),
  1064. max(len(f['format_id']) for f in formats))
  1065. formats_s = [line(f, idlen) for f in formats]
  1066. if len(formats) > 1:
  1067. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1068. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1069. header_line = line({
  1070. 'format_id': 'format code', 'ext': 'extension',
  1071. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1072. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1073. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1074. def urlopen(self, req):
  1075. """ Start an HTTP download """
  1076. return self._opener.open(req, timeout=self._socket_timeout)
  1077. def print_debug_header(self):
  1078. if not self.params.get('verbose'):
  1079. return
  1080. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1081. try:
  1082. sp = subprocess.Popen(
  1083. ['git', 'rev-parse', '--short', 'HEAD'],
  1084. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1085. cwd=os.path.dirname(os.path.abspath(__file__)))
  1086. out, err = sp.communicate()
  1087. out = out.decode().strip()
  1088. if re.match('[0-9a-f]+', out):
  1089. write_string('[debug] Git HEAD: ' + out + '\n')
  1090. except:
  1091. try:
  1092. sys.exc_clear()
  1093. except:
  1094. pass
  1095. write_string('[debug] Python version %s - %s' %
  1096. (platform.python_version(), platform_name()) + '\n')
  1097. proxy_map = {}
  1098. for handler in self._opener.handlers:
  1099. if hasattr(handler, 'proxies'):
  1100. proxy_map.update(handler.proxies)
  1101. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1102. def _setup_opener(self):
  1103. timeout_val = self.params.get('socket_timeout')
  1104. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1105. opts_cookiefile = self.params.get('cookiefile')
  1106. opts_proxy = self.params.get('proxy')
  1107. if opts_cookiefile is None:
  1108. self.cookiejar = compat_cookiejar.CookieJar()
  1109. else:
  1110. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1111. opts_cookiefile)
  1112. if os.access(opts_cookiefile, os.R_OK):
  1113. self.cookiejar.load()
  1114. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1115. self.cookiejar)
  1116. if opts_proxy is not None:
  1117. if opts_proxy == '':
  1118. proxies = {}
  1119. else:
  1120. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1121. else:
  1122. proxies = compat_urllib_request.getproxies()
  1123. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1124. if 'http' in proxies and 'https' not in proxies:
  1125. proxies['https'] = proxies['http']
  1126. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1127. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1128. https_handler = make_HTTPS_handler(
  1129. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1130. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1131. opener = compat_urllib_request.build_opener(
  1132. https_handler, proxy_handler, cookie_processor, ydlh)
  1133. # Delete the default user-agent header, which would otherwise apply in
  1134. # cases where our custom HTTP handler doesn't come into play
  1135. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1136. opener.addheaders = []
  1137. self._opener = opener