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.

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