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.

1295 lines
56 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 'id' not in info_dict:
  636. raise ExtractorError('Missing "id" field in extractor result')
  637. if 'title' not in info_dict:
  638. raise ExtractorError('Missing "title" field in extractor result')
  639. if 'playlist' not in info_dict:
  640. # It isn't part of a playlist
  641. info_dict['playlist'] = None
  642. info_dict['playlist_index'] = None
  643. if 'display_id' not in info_dict and 'id' in info_dict:
  644. info_dict['display_id'] = info_dict['id']
  645. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  646. upload_date = datetime.datetime.utcfromtimestamp(
  647. info_dict['timestamp'])
  648. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  649. # This extractors handle format selection themselves
  650. if info_dict['extractor'] in ['Youku']:
  651. if download:
  652. self.process_info(info_dict)
  653. return info_dict
  654. # We now pick which formats have to be downloaded
  655. if info_dict.get('formats') is None:
  656. # There's only one format available
  657. formats = [info_dict]
  658. else:
  659. formats = info_dict['formats']
  660. if not formats:
  661. raise ExtractorError('No video formats found!')
  662. # We check that all the formats have the format and format_id fields
  663. for i, format in enumerate(formats):
  664. if 'url' not in format:
  665. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  666. if format.get('format_id') is None:
  667. format['format_id'] = compat_str(i)
  668. if format.get('format') is None:
  669. format['format'] = '{id} - {res}{note}'.format(
  670. id=format['format_id'],
  671. res=self.format_resolution(format),
  672. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  673. )
  674. # Automatically determine file extension if missing
  675. if 'ext' not in format:
  676. format['ext'] = determine_ext(format['url']).lower()
  677. format_limit = self.params.get('format_limit', None)
  678. if format_limit:
  679. formats = list(takewhile_inclusive(
  680. lambda f: f['format_id'] != format_limit, formats
  681. ))
  682. # TODO Central sorting goes here
  683. if formats[0] is not info_dict:
  684. # only set the 'formats' fields if the original info_dict list them
  685. # otherwise we end up with a circular reference, the first (and unique)
  686. # element in the 'formats' field in info_dict is info_dict itself,
  687. # wich can't be exported to json
  688. info_dict['formats'] = formats
  689. if self.params.get('listformats', None):
  690. self.list_formats(info_dict)
  691. return
  692. req_format = self.params.get('format')
  693. if req_format is None:
  694. req_format = 'best'
  695. formats_to_download = []
  696. # The -1 is for supporting YoutubeIE
  697. if req_format in ('-1', 'all'):
  698. formats_to_download = formats
  699. else:
  700. # We can accept formats requested in the format: 34/5/best, we pick
  701. # the first that is available, starting from left
  702. req_formats = req_format.split('/')
  703. for rf in req_formats:
  704. if re.match(r'.+?\+.+?', rf) is not None:
  705. # Two formats have been requested like '137+139'
  706. format_1, format_2 = rf.split('+')
  707. formats_info = (self.select_format(format_1, formats),
  708. self.select_format(format_2, formats))
  709. if all(formats_info):
  710. selected_format = {
  711. 'requested_formats': formats_info,
  712. 'format': rf,
  713. 'ext': formats_info[0]['ext'],
  714. }
  715. else:
  716. selected_format = None
  717. else:
  718. selected_format = self.select_format(rf, formats)
  719. if selected_format is not None:
  720. formats_to_download = [selected_format]
  721. break
  722. if not formats_to_download:
  723. raise ExtractorError('requested format not available',
  724. expected=True)
  725. if download:
  726. if len(formats_to_download) > 1:
  727. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  728. for format in formats_to_download:
  729. new_info = dict(info_dict)
  730. new_info.update(format)
  731. self.process_info(new_info)
  732. # We update the info dict with the best quality format (backwards compatibility)
  733. info_dict.update(formats_to_download[-1])
  734. return info_dict
  735. def process_info(self, info_dict):
  736. """Process a single resolved IE result."""
  737. assert info_dict.get('_type', 'video') == 'video'
  738. max_downloads = self.params.get('max_downloads')
  739. if max_downloads is not None:
  740. if self._num_downloads >= int(max_downloads):
  741. raise MaxDownloadsReached()
  742. info_dict['fulltitle'] = info_dict['title']
  743. if len(info_dict['title']) > 200:
  744. info_dict['title'] = info_dict['title'][:197] + '...'
  745. # Keep for backwards compatibility
  746. info_dict['stitle'] = info_dict['title']
  747. if not 'format' in info_dict:
  748. info_dict['format'] = info_dict['ext']
  749. reason = self._match_entry(info_dict)
  750. if reason is not None:
  751. self.to_screen('[download] ' + reason)
  752. return
  753. self._num_downloads += 1
  754. filename = self.prepare_filename(info_dict)
  755. # Forced printings
  756. if self.params.get('forcetitle', False):
  757. self.to_stdout(info_dict['fulltitle'])
  758. if self.params.get('forceid', False):
  759. self.to_stdout(info_dict['id'])
  760. if self.params.get('forceurl', False):
  761. # For RTMP URLs, also include the playpath
  762. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  763. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  764. self.to_stdout(info_dict['thumbnail'])
  765. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  766. self.to_stdout(info_dict['description'])
  767. if self.params.get('forcefilename', False) and filename is not None:
  768. self.to_stdout(filename)
  769. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  770. self.to_stdout(formatSeconds(info_dict['duration']))
  771. if self.params.get('forceformat', False):
  772. self.to_stdout(info_dict['format'])
  773. if self.params.get('forcejson', False):
  774. info_dict['_filename'] = filename
  775. self.to_stdout(json.dumps(info_dict))
  776. # Do nothing else if in simulate mode
  777. if self.params.get('simulate', False):
  778. return
  779. if filename is None:
  780. return
  781. try:
  782. dn = os.path.dirname(encodeFilename(filename))
  783. if dn and not os.path.exists(dn):
  784. os.makedirs(dn)
  785. except (OSError, IOError) as err:
  786. self.report_error('unable to create directory ' + compat_str(err))
  787. return
  788. if self.params.get('writedescription', False):
  789. descfn = filename + '.description'
  790. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  791. self.to_screen('[info] Video description is already present')
  792. else:
  793. try:
  794. self.to_screen('[info] Writing video description to: ' + descfn)
  795. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  796. descfile.write(info_dict['description'])
  797. except (KeyError, TypeError):
  798. self.report_warning('There\'s no description to write.')
  799. except (OSError, IOError):
  800. self.report_error('Cannot write description file ' + descfn)
  801. return
  802. if self.params.get('writeannotations', False):
  803. annofn = filename + '.annotations.xml'
  804. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  805. self.to_screen('[info] Video annotations are already present')
  806. else:
  807. try:
  808. self.to_screen('[info] Writing video annotations to: ' + annofn)
  809. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  810. annofile.write(info_dict['annotations'])
  811. except (KeyError, TypeError):
  812. self.report_warning('There are no annotations to write.')
  813. except (OSError, IOError):
  814. self.report_error('Cannot write annotations file: ' + annofn)
  815. return
  816. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  817. self.params.get('writeautomaticsub')])
  818. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  819. # subtitles download errors are already managed as troubles in relevant IE
  820. # that way it will silently go on when used with unsupporting IE
  821. subtitles = info_dict['subtitles']
  822. sub_format = self.params.get('subtitlesformat', 'srt')
  823. for sub_lang in subtitles.keys():
  824. sub = subtitles[sub_lang]
  825. if sub is None:
  826. continue
  827. try:
  828. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  829. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  830. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  831. else:
  832. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  833. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  834. subfile.write(sub)
  835. except (OSError, IOError):
  836. self.report_error('Cannot write subtitles file ' + descfn)
  837. return
  838. if self.params.get('writeinfojson', False):
  839. infofn = os.path.splitext(filename)[0] + '.info.json'
  840. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  841. self.to_screen('[info] Video description metadata is already present')
  842. else:
  843. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  844. try:
  845. write_json_file(info_dict, encodeFilename(infofn))
  846. except (OSError, IOError):
  847. self.report_error('Cannot write metadata to JSON file ' + infofn)
  848. return
  849. if self.params.get('writethumbnail', False):
  850. if info_dict.get('thumbnail') is not None:
  851. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  852. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  853. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  854. self.to_screen('[%s] %s: Thumbnail is already present' %
  855. (info_dict['extractor'], info_dict['id']))
  856. else:
  857. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  858. (info_dict['extractor'], info_dict['id']))
  859. try:
  860. uf = self.urlopen(info_dict['thumbnail'])
  861. with open(thumb_filename, 'wb') as thumbf:
  862. shutil.copyfileobj(uf, thumbf)
  863. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  864. (info_dict['extractor'], info_dict['id'], thumb_filename))
  865. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  866. self.report_warning('Unable to download thumbnail "%s": %s' %
  867. (info_dict['thumbnail'], compat_str(err)))
  868. if not self.params.get('skip_download', False):
  869. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  870. success = True
  871. else:
  872. try:
  873. def dl(name, info):
  874. fd = get_suitable_downloader(info)(self, self.params)
  875. for ph in self._progress_hooks:
  876. fd.add_progress_hook(ph)
  877. return fd.download(name, info)
  878. if info_dict.get('requested_formats') is not None:
  879. downloaded = []
  880. success = True
  881. merger = FFmpegMergerPP(self)
  882. if not merger._get_executable():
  883. postprocessors = []
  884. self.report_warning('You have requested multiple '
  885. 'formats but ffmpeg or avconv are not installed.'
  886. ' The formats won\'t be merged')
  887. else:
  888. postprocessors = [merger]
  889. for f in info_dict['requested_formats']:
  890. new_info = dict(info_dict)
  891. new_info.update(f)
  892. fname = self.prepare_filename(new_info)
  893. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  894. downloaded.append(fname)
  895. partial_success = dl(fname, new_info)
  896. success = success and partial_success
  897. info_dict['__postprocessors'] = postprocessors
  898. info_dict['__files_to_merge'] = downloaded
  899. else:
  900. # Just a single file
  901. success = dl(filename, info_dict)
  902. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  903. self.report_error('unable to download video data: %s' % str(err))
  904. return
  905. except (OSError, IOError) as err:
  906. raise UnavailableVideoError(err)
  907. except (ContentTooShortError, ) as err:
  908. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  909. return
  910. if success:
  911. try:
  912. self.post_process(filename, info_dict)
  913. except (PostProcessingError) as err:
  914. self.report_error('postprocessing: %s' % str(err))
  915. return
  916. self.record_download_archive(info_dict)
  917. def download(self, url_list):
  918. """Download a given list of URLs."""
  919. if (len(url_list) > 1 and
  920. '%' not in self.params['outtmpl']
  921. and self.params.get('max_downloads') != 1):
  922. raise SameFileError(self.params['outtmpl'])
  923. for url in url_list:
  924. try:
  925. #It also downloads the videos
  926. self.extract_info(url)
  927. except UnavailableVideoError:
  928. self.report_error('unable to download video')
  929. except MaxDownloadsReached:
  930. self.to_screen('[info] Maximum number of downloaded files reached.')
  931. raise
  932. return self._download_retcode
  933. def download_with_info_file(self, info_filename):
  934. with io.open(info_filename, 'r', encoding='utf-8') as f:
  935. info = json.load(f)
  936. try:
  937. self.process_ie_result(info, download=True)
  938. except DownloadError:
  939. webpage_url = info.get('webpage_url')
  940. if webpage_url is not None:
  941. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  942. return self.download([webpage_url])
  943. else:
  944. raise
  945. return self._download_retcode
  946. def post_process(self, filename, ie_info):
  947. """Run all the postprocessors on the given file."""
  948. info = dict(ie_info)
  949. info['filepath'] = filename
  950. keep_video = None
  951. pps_chain = []
  952. if ie_info.get('__postprocessors') is not None:
  953. pps_chain.extend(ie_info['__postprocessors'])
  954. pps_chain.extend(self._pps)
  955. for pp in pps_chain:
  956. try:
  957. keep_video_wish, new_info = pp.run(info)
  958. if keep_video_wish is not None:
  959. if keep_video_wish:
  960. keep_video = keep_video_wish
  961. elif keep_video is None:
  962. # No clear decision yet, let IE decide
  963. keep_video = keep_video_wish
  964. except PostProcessingError as e:
  965. self.report_error(e.msg)
  966. if keep_video is False and not self.params.get('keepvideo', False):
  967. try:
  968. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  969. os.remove(encodeFilename(filename))
  970. except (IOError, OSError):
  971. self.report_warning('Unable to remove downloaded video file')
  972. def _make_archive_id(self, info_dict):
  973. # Future-proof against any change in case
  974. # and backwards compatibility with prior versions
  975. extractor = info_dict.get('extractor_key')
  976. if extractor is None:
  977. if 'id' in info_dict:
  978. extractor = info_dict.get('ie_key') # key in a playlist
  979. if extractor is None:
  980. return None # Incomplete video information
  981. return extractor.lower() + ' ' + info_dict['id']
  982. def in_download_archive(self, info_dict):
  983. fn = self.params.get('download_archive')
  984. if fn is None:
  985. return False
  986. vid_id = self._make_archive_id(info_dict)
  987. if vid_id is None:
  988. return False # Incomplete video information
  989. try:
  990. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  991. for line in archive_file:
  992. if line.strip() == vid_id:
  993. return True
  994. except IOError as ioe:
  995. if ioe.errno != errno.ENOENT:
  996. raise
  997. return False
  998. def record_download_archive(self, info_dict):
  999. fn = self.params.get('download_archive')
  1000. if fn is None:
  1001. return
  1002. vid_id = self._make_archive_id(info_dict)
  1003. assert vid_id
  1004. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1005. archive_file.write(vid_id + '\n')
  1006. @staticmethod
  1007. def format_resolution(format, default='unknown'):
  1008. if format.get('vcodec') == 'none':
  1009. return 'audio only'
  1010. if format.get('resolution') is not None:
  1011. return format['resolution']
  1012. if format.get('height') is not None:
  1013. if format.get('width') is not None:
  1014. res = '%sx%s' % (format['width'], format['height'])
  1015. else:
  1016. res = '%sp' % format['height']
  1017. elif format.get('width') is not None:
  1018. res = '?x%d' % format['width']
  1019. else:
  1020. res = default
  1021. return res
  1022. def list_formats(self, info_dict):
  1023. def format_note(fdict):
  1024. res = ''
  1025. if fdict.get('ext') in ['f4f', 'f4m']:
  1026. res += '(unsupported) '
  1027. if fdict.get('format_note') is not None:
  1028. res += fdict['format_note'] + ' '
  1029. if fdict.get('tbr') is not None:
  1030. res += '%4dk ' % fdict['tbr']
  1031. if fdict.get('container') is not None:
  1032. if res:
  1033. res += ', '
  1034. res += '%s container' % fdict['container']
  1035. if (fdict.get('vcodec') is not None and
  1036. fdict.get('vcodec') != 'none'):
  1037. if res:
  1038. res += ', '
  1039. res += fdict['vcodec']
  1040. if fdict.get('vbr') is not None:
  1041. res += '@'
  1042. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1043. res += 'video@'
  1044. if fdict.get('vbr') is not None:
  1045. res += '%4dk' % fdict['vbr']
  1046. if fdict.get('acodec') is not None:
  1047. if res:
  1048. res += ', '
  1049. if fdict['acodec'] == 'none':
  1050. res += 'video only'
  1051. else:
  1052. res += '%-5s' % fdict['acodec']
  1053. elif fdict.get('abr') is not None:
  1054. if res:
  1055. res += ', '
  1056. res += 'audio'
  1057. if fdict.get('abr') is not None:
  1058. res += '@%3dk' % fdict['abr']
  1059. if fdict.get('asr') is not None:
  1060. res += ' (%5dHz)' % fdict['asr']
  1061. if fdict.get('filesize') is not None:
  1062. if res:
  1063. res += ', '
  1064. res += format_bytes(fdict['filesize'])
  1065. return res
  1066. def line(format, idlen=20):
  1067. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1068. format['format_id'],
  1069. format['ext'],
  1070. self.format_resolution(format),
  1071. format_note(format),
  1072. ))
  1073. formats = info_dict.get('formats', [info_dict])
  1074. idlen = max(len('format code'),
  1075. max(len(f['format_id']) for f in formats))
  1076. formats_s = [line(f, idlen) for f in formats]
  1077. if len(formats) > 1:
  1078. formats_s[0] += (' ' if format_note(formats[0]) else '') + '(worst)'
  1079. formats_s[-1] += (' ' if format_note(formats[-1]) else '') + '(best)'
  1080. header_line = line({
  1081. 'format_id': 'format code', 'ext': 'extension',
  1082. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1083. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1084. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1085. def urlopen(self, req):
  1086. """ Start an HTTP download """
  1087. return self._opener.open(req, timeout=self._socket_timeout)
  1088. def print_debug_header(self):
  1089. if not self.params.get('verbose'):
  1090. return
  1091. write_string('[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' %
  1092. (locale.getpreferredencoding(), sys.getfilesystemencoding(), sys.stdout.encoding, self.get_encoding()))
  1093. write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1094. try:
  1095. sp = subprocess.Popen(
  1096. ['git', 'rev-parse', '--short', 'HEAD'],
  1097. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1098. cwd=os.path.dirname(os.path.abspath(__file__)))
  1099. out, err = sp.communicate()
  1100. out = out.decode().strip()
  1101. if re.match('[0-9a-f]+', out):
  1102. write_string('[debug] Git HEAD: ' + out + '\n')
  1103. except:
  1104. try:
  1105. sys.exc_clear()
  1106. except:
  1107. pass
  1108. write_string('[debug] Python version %s - %s' %
  1109. (platform.python_version(), platform_name()) + '\n')
  1110. proxy_map = {}
  1111. for handler in self._opener.handlers:
  1112. if hasattr(handler, 'proxies'):
  1113. proxy_map.update(handler.proxies)
  1114. write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1115. def _setup_opener(self):
  1116. timeout_val = self.params.get('socket_timeout')
  1117. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1118. opts_cookiefile = self.params.get('cookiefile')
  1119. opts_proxy = self.params.get('proxy')
  1120. if opts_cookiefile is None:
  1121. self.cookiejar = compat_cookiejar.CookieJar()
  1122. else:
  1123. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1124. opts_cookiefile)
  1125. if os.access(opts_cookiefile, os.R_OK):
  1126. self.cookiejar.load()
  1127. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1128. self.cookiejar)
  1129. if opts_proxy is not None:
  1130. if opts_proxy == '':
  1131. proxies = {}
  1132. else:
  1133. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1134. else:
  1135. proxies = compat_urllib_request.getproxies()
  1136. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1137. if 'http' in proxies and 'https' not in proxies:
  1138. proxies['https'] = proxies['http']
  1139. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1140. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1141. https_handler = make_HTTPS_handler(
  1142. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1143. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1144. opener = compat_urllib_request.build_opener(
  1145. https_handler, proxy_handler, cookie_processor, ydlh)
  1146. # Delete the default user-agent header, which would otherwise apply in
  1147. # cases where our custom HTTP handler doesn't come into play
  1148. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1149. opener.addheaders = []
  1150. self._opener = opener
  1151. def encode(self, s):
  1152. if isinstance(s, bytes):
  1153. return s # Already encoded
  1154. try:
  1155. return s.encode(self.get_encoding())
  1156. except UnicodeEncodeError as err:
  1157. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1158. raise
  1159. def get_encoding(self):
  1160. encoding = self.params.get('encoding')
  1161. if encoding is None:
  1162. encoding = preferredencoding()
  1163. return encoding