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.

1329 lines
57 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 isinstance(message, compat_str)
  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 isinstance(message, compat_str)
  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 'format' not 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. if self.params.get('verbose'):
  891. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  892. return fd.download(name, info)
  893. if info_dict.get('requested_formats') is not None:
  894. downloaded = []
  895. success = True
  896. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  897. if not merger._get_executable():
  898. postprocessors = []
  899. self.report_warning('You have requested multiple '
  900. 'formats but ffmpeg or avconv are not installed.'
  901. ' The formats won\'t be merged')
  902. else:
  903. postprocessors = [merger]
  904. for f in info_dict['requested_formats']:
  905. new_info = dict(info_dict)
  906. new_info.update(f)
  907. fname = self.prepare_filename(new_info)
  908. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  909. downloaded.append(fname)
  910. partial_success = dl(fname, new_info)
  911. success = success and partial_success
  912. info_dict['__postprocessors'] = postprocessors
  913. info_dict['__files_to_merge'] = downloaded
  914. else:
  915. # Just a single file
  916. success = dl(filename, info_dict)
  917. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  918. self.report_error('unable to download video data: %s' % str(err))
  919. return
  920. except (OSError, IOError) as err:
  921. raise UnavailableVideoError(err)
  922. except (ContentTooShortError, ) as err:
  923. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  924. return
  925. if success:
  926. try:
  927. self.post_process(filename, info_dict)
  928. except (PostProcessingError) as err:
  929. self.report_error('postprocessing: %s' % str(err))
  930. return
  931. self.record_download_archive(info_dict)
  932. def download(self, url_list):
  933. """Download a given list of URLs."""
  934. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  935. if (len(url_list) > 1 and
  936. '%' not in outtmpl
  937. and self.params.get('max_downloads') != 1):
  938. raise SameFileError(outtmpl)
  939. for url in url_list:
  940. try:
  941. #It also downloads the videos
  942. self.extract_info(url)
  943. except UnavailableVideoError:
  944. self.report_error('unable to download video')
  945. except MaxDownloadsReached:
  946. self.to_screen('[info] Maximum number of downloaded files reached.')
  947. raise
  948. return self._download_retcode
  949. def download_with_info_file(self, info_filename):
  950. with io.open(info_filename, 'r', encoding='utf-8') as f:
  951. info = json.load(f)
  952. try:
  953. self.process_ie_result(info, download=True)
  954. except DownloadError:
  955. webpage_url = info.get('webpage_url')
  956. if webpage_url is not None:
  957. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  958. return self.download([webpage_url])
  959. else:
  960. raise
  961. return self._download_retcode
  962. def post_process(self, filename, ie_info):
  963. """Run all the postprocessors on the given file."""
  964. info = dict(ie_info)
  965. info['filepath'] = filename
  966. keep_video = None
  967. pps_chain = []
  968. if ie_info.get('__postprocessors') is not None:
  969. pps_chain.extend(ie_info['__postprocessors'])
  970. pps_chain.extend(self._pps)
  971. for pp in pps_chain:
  972. try:
  973. keep_video_wish, new_info = pp.run(info)
  974. if keep_video_wish is not None:
  975. if keep_video_wish:
  976. keep_video = keep_video_wish
  977. elif keep_video is None:
  978. # No clear decision yet, let IE decide
  979. keep_video = keep_video_wish
  980. except PostProcessingError as e:
  981. self.report_error(e.msg)
  982. if keep_video is False and not self.params.get('keepvideo', False):
  983. try:
  984. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  985. os.remove(encodeFilename(filename))
  986. except (IOError, OSError):
  987. self.report_warning('Unable to remove downloaded video file')
  988. def _make_archive_id(self, info_dict):
  989. # Future-proof against any change in case
  990. # and backwards compatibility with prior versions
  991. extractor = info_dict.get('extractor_key')
  992. if extractor is None:
  993. if 'id' in info_dict:
  994. extractor = info_dict.get('ie_key') # key in a playlist
  995. if extractor is None:
  996. return None # Incomplete video information
  997. return extractor.lower() + ' ' + info_dict['id']
  998. def in_download_archive(self, info_dict):
  999. fn = self.params.get('download_archive')
  1000. if fn is None:
  1001. return False
  1002. vid_id = self._make_archive_id(info_dict)
  1003. if vid_id is None:
  1004. return False # Incomplete video information
  1005. try:
  1006. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1007. for line in archive_file:
  1008. if line.strip() == vid_id:
  1009. return True
  1010. except IOError as ioe:
  1011. if ioe.errno != errno.ENOENT:
  1012. raise
  1013. return False
  1014. def record_download_archive(self, info_dict):
  1015. fn = self.params.get('download_archive')
  1016. if fn is None:
  1017. return
  1018. vid_id = self._make_archive_id(info_dict)
  1019. assert vid_id
  1020. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1021. archive_file.write(vid_id + '\n')
  1022. @staticmethod
  1023. def format_resolution(format, default='unknown'):
  1024. if format.get('vcodec') == 'none':
  1025. return 'audio only'
  1026. if format.get('resolution') is not None:
  1027. return format['resolution']
  1028. if format.get('height') is not None:
  1029. if format.get('width') is not None:
  1030. res = '%sx%s' % (format['width'], format['height'])
  1031. else:
  1032. res = '%sp' % format['height']
  1033. elif format.get('width') is not None:
  1034. res = '?x%d' % format['width']
  1035. else:
  1036. res = default
  1037. return res
  1038. def _format_note(self, fdict):
  1039. res = ''
  1040. if fdict.get('ext') in ['f4f', 'f4m']:
  1041. res += '(unsupported) '
  1042. if fdict.get('format_note') is not None:
  1043. res += fdict['format_note'] + ' '
  1044. if fdict.get('tbr') is not None:
  1045. res += '%4dk ' % fdict['tbr']
  1046. if fdict.get('container') is not None:
  1047. if res:
  1048. res += ', '
  1049. res += '%s container' % fdict['container']
  1050. if (fdict.get('vcodec') is not None and
  1051. fdict.get('vcodec') != 'none'):
  1052. if res:
  1053. res += ', '
  1054. res += fdict['vcodec']
  1055. if fdict.get('vbr') is not None:
  1056. res += '@'
  1057. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1058. res += 'video@'
  1059. if fdict.get('vbr') is not None:
  1060. res += '%4dk' % fdict['vbr']
  1061. if fdict.get('acodec') is not None:
  1062. if res:
  1063. res += ', '
  1064. if fdict['acodec'] == 'none':
  1065. res += 'video only'
  1066. else:
  1067. res += '%-5s' % fdict['acodec']
  1068. elif fdict.get('abr') is not None:
  1069. if res:
  1070. res += ', '
  1071. res += 'audio'
  1072. if fdict.get('abr') is not None:
  1073. res += '@%3dk' % fdict['abr']
  1074. if fdict.get('asr') is not None:
  1075. res += ' (%5dHz)' % fdict['asr']
  1076. if fdict.get('filesize') is not None:
  1077. if res:
  1078. res += ', '
  1079. res += format_bytes(fdict['filesize'])
  1080. elif fdict.get('filesize_approx') is not None:
  1081. if res:
  1082. res += ', '
  1083. res += '~' + format_bytes(fdict['filesize_approx'])
  1084. return res
  1085. def list_formats(self, info_dict):
  1086. def line(format, idlen=20):
  1087. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1088. format['format_id'],
  1089. format['ext'],
  1090. self.format_resolution(format),
  1091. self._format_note(format),
  1092. ))
  1093. formats = info_dict.get('formats', [info_dict])
  1094. idlen = max(len('format code'),
  1095. max(len(f['format_id']) for f in formats))
  1096. formats_s = [line(f, idlen) for f in formats]
  1097. if len(formats) > 1:
  1098. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1099. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1100. header_line = line({
  1101. 'format_id': 'format code', 'ext': 'extension',
  1102. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1103. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1104. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1105. def urlopen(self, req):
  1106. """ Start an HTTP download """
  1107. return self._opener.open(req, timeout=self._socket_timeout)
  1108. def print_debug_header(self):
  1109. if not self.params.get('verbose'):
  1110. return
  1111. if type('') is not compat_str:
  1112. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1113. self.report_warning(
  1114. 'Your Python is broken! Update to a newer and supported version')
  1115. encoding_str = (
  1116. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1117. locale.getpreferredencoding(),
  1118. sys.getfilesystemencoding(),
  1119. sys.stdout.encoding,
  1120. self.get_encoding()))
  1121. write_string(encoding_str, encoding=None)
  1122. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1123. try:
  1124. sp = subprocess.Popen(
  1125. ['git', 'rev-parse', '--short', 'HEAD'],
  1126. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1127. cwd=os.path.dirname(os.path.abspath(__file__)))
  1128. out, err = sp.communicate()
  1129. out = out.decode().strip()
  1130. if re.match('[0-9a-f]+', out):
  1131. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1132. except:
  1133. try:
  1134. sys.exc_clear()
  1135. except:
  1136. pass
  1137. self._write_string('[debug] Python version %s - %s' %
  1138. (platform.python_version(), platform_name()) + '\n')
  1139. proxy_map = {}
  1140. for handler in self._opener.handlers:
  1141. if hasattr(handler, 'proxies'):
  1142. proxy_map.update(handler.proxies)
  1143. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1144. def _setup_opener(self):
  1145. timeout_val = self.params.get('socket_timeout')
  1146. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1147. opts_cookiefile = self.params.get('cookiefile')
  1148. opts_proxy = self.params.get('proxy')
  1149. if opts_cookiefile is None:
  1150. self.cookiejar = compat_cookiejar.CookieJar()
  1151. else:
  1152. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1153. opts_cookiefile)
  1154. if os.access(opts_cookiefile, os.R_OK):
  1155. self.cookiejar.load()
  1156. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1157. self.cookiejar)
  1158. if opts_proxy is not None:
  1159. if opts_proxy == '':
  1160. proxies = {}
  1161. else:
  1162. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1163. else:
  1164. proxies = compat_urllib_request.getproxies()
  1165. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1166. if 'http' in proxies and 'https' not in proxies:
  1167. proxies['https'] = proxies['http']
  1168. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1169. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1170. https_handler = make_HTTPS_handler(
  1171. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1172. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1173. opener = compat_urllib_request.build_opener(
  1174. https_handler, proxy_handler, cookie_processor, ydlh)
  1175. # Delete the default user-agent header, which would otherwise apply in
  1176. # cases where our custom HTTP handler doesn't come into play
  1177. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1178. opener.addheaders = []
  1179. self._opener = opener
  1180. def encode(self, s):
  1181. if isinstance(s, bytes):
  1182. return s # Already encoded
  1183. try:
  1184. return s.encode(self.get_encoding())
  1185. except UnicodeEncodeError as err:
  1186. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1187. raise
  1188. def get_encoding(self):
  1189. encoding = self.params.get('encoding')
  1190. if encoding is None:
  1191. encoding = preferredencoding()
  1192. return encoding