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.

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