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.

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