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.

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