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.

1335 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. if age_limit < info_dict.get('age_limit', 0):
  435. return 'Skipping "' + title + '" because it is age restricted'
  436. if self.in_download_archive(info_dict):
  437. return '%s has already been recorded in archive' % video_title
  438. return None
  439. @staticmethod
  440. def add_extra_info(info_dict, extra_info):
  441. '''Set the keys from extra_info in info dict if they are missing'''
  442. for key, value in extra_info.items():
  443. info_dict.setdefault(key, value)
  444. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  445. process=True):
  446. '''
  447. Returns a list with a dictionary for each video we find.
  448. If 'download', also downloads the videos.
  449. extra_info is a dict containing the extra values to add to each result
  450. '''
  451. if ie_key:
  452. ies = [self.get_info_extractor(ie_key)]
  453. else:
  454. ies = self._ies
  455. for ie in ies:
  456. if not ie.suitable(url):
  457. continue
  458. if not ie.working():
  459. self.report_warning('The program functionality for this site has been marked as broken, '
  460. 'and will probably not work.')
  461. try:
  462. ie_result = ie.extract(url)
  463. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  464. break
  465. if isinstance(ie_result, list):
  466. # Backwards compatibility: old IE result format
  467. ie_result = {
  468. '_type': 'compat_list',
  469. 'entries': ie_result,
  470. }
  471. self.add_default_extra_info(ie_result, ie, url)
  472. if process:
  473. return self.process_ie_result(ie_result, download, extra_info)
  474. else:
  475. return ie_result
  476. except ExtractorError as de: # An error we somewhat expected
  477. self.report_error(compat_str(de), de.format_traceback())
  478. break
  479. except MaxDownloadsReached:
  480. raise
  481. except Exception as e:
  482. if self.params.get('ignoreerrors', False):
  483. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  484. break
  485. else:
  486. raise
  487. else:
  488. self.report_error('no suitable InfoExtractor for URL %s' % url)
  489. def add_default_extra_info(self, ie_result, ie, url):
  490. self.add_extra_info(ie_result, {
  491. 'extractor': ie.IE_NAME,
  492. 'webpage_url': url,
  493. 'webpage_url_basename': url_basename(url),
  494. 'extractor_key': ie.ie_key(),
  495. })
  496. def process_ie_result(self, ie_result, download=True, extra_info={}):
  497. """
  498. Take the result of the ie(may be modified) and resolve all unresolved
  499. references (URLs, playlist items).
  500. It will also download the videos if 'download'.
  501. Returns the resolved ie_result.
  502. """
  503. result_type = ie_result.get('_type', 'video')
  504. if self.params.get('extract_flat', False):
  505. if result_type in ('url', 'url_transparent'):
  506. return ie_result
  507. if result_type == 'video':
  508. self.add_extra_info(ie_result, extra_info)
  509. return self.process_video_result(ie_result, download=download)
  510. elif result_type == 'url':
  511. # We have to add extra_info to the results because it may be
  512. # contained in a playlist
  513. return self.extract_info(ie_result['url'],
  514. download,
  515. ie_key=ie_result.get('ie_key'),
  516. extra_info=extra_info)
  517. elif result_type == 'url_transparent':
  518. # Use the information from the embedding page
  519. info = self.extract_info(
  520. ie_result['url'], ie_key=ie_result.get('ie_key'),
  521. extra_info=extra_info, download=False, process=False)
  522. def make_result(embedded_info):
  523. new_result = ie_result.copy()
  524. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  525. 'entries', 'ie_key', 'duration',
  526. 'subtitles', 'annotations', 'format',
  527. 'thumbnail', 'thumbnails'):
  528. if f in new_result:
  529. del new_result[f]
  530. if f in embedded_info:
  531. new_result[f] = embedded_info[f]
  532. return new_result
  533. new_result = make_result(info)
  534. assert new_result.get('_type') != 'url_transparent'
  535. if new_result.get('_type') == 'compat_list':
  536. new_result['entries'] = [
  537. make_result(e) for e in new_result['entries']]
  538. return self.process_ie_result(
  539. new_result, download=download, extra_info=extra_info)
  540. elif result_type == 'playlist':
  541. # We process each entry in the playlist
  542. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  543. self.to_screen('[download] Downloading playlist: %s' % playlist)
  544. playlist_results = []
  545. playliststart = self.params.get('playliststart', 1) - 1
  546. playlistend = self.params.get('playlistend', None)
  547. # For backwards compatibility, interpret -1 as whole list
  548. if playlistend == -1:
  549. playlistend = None
  550. if isinstance(ie_result['entries'], list):
  551. n_all_entries = len(ie_result['entries'])
  552. entries = ie_result['entries'][playliststart:playlistend]
  553. n_entries = len(entries)
  554. self.to_screen(
  555. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  556. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  557. else:
  558. assert isinstance(ie_result['entries'], PagedList)
  559. entries = ie_result['entries'].getslice(
  560. playliststart, playlistend)
  561. n_entries = len(entries)
  562. self.to_screen(
  563. "[%s] playlist %s: Downloading %d videos" %
  564. (ie_result['extractor'], playlist, n_entries))
  565. for i, entry in enumerate(entries, 1):
  566. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  567. extra = {
  568. 'playlist': playlist,
  569. 'playlist_index': i + playliststart,
  570. 'extractor': ie_result['extractor'],
  571. 'webpage_url': ie_result['webpage_url'],
  572. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  573. 'extractor_key': ie_result['extractor_key'],
  574. }
  575. reason = self._match_entry(entry)
  576. if reason is not None:
  577. self.to_screen('[download] ' + reason)
  578. continue
  579. entry_result = self.process_ie_result(entry,
  580. download=download,
  581. extra_info=extra)
  582. playlist_results.append(entry_result)
  583. ie_result['entries'] = playlist_results
  584. return ie_result
  585. elif result_type == 'compat_list':
  586. def _fixup(r):
  587. self.add_extra_info(r,
  588. {
  589. 'extractor': ie_result['extractor'],
  590. 'webpage_url': ie_result['webpage_url'],
  591. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  592. 'extractor_key': ie_result['extractor_key'],
  593. })
  594. return r
  595. ie_result['entries'] = [
  596. self.process_ie_result(_fixup(r), download, extra_info)
  597. for r in ie_result['entries']
  598. ]
  599. return ie_result
  600. else:
  601. raise Exception('Invalid result type: %s' % result_type)
  602. def select_format(self, format_spec, available_formats):
  603. if format_spec == 'best' or format_spec is None:
  604. return available_formats[-1]
  605. elif format_spec == 'worst':
  606. return available_formats[0]
  607. elif format_spec == 'bestaudio':
  608. audio_formats = [
  609. f for f in available_formats
  610. if f.get('vcodec') == 'none']
  611. if audio_formats:
  612. return audio_formats[-1]
  613. elif format_spec == 'worstaudio':
  614. audio_formats = [
  615. f for f in available_formats
  616. if f.get('vcodec') == 'none']
  617. if audio_formats:
  618. return audio_formats[0]
  619. elif format_spec == 'bestvideo':
  620. video_formats = [
  621. f for f in available_formats
  622. if f.get('acodec') == 'none']
  623. if video_formats:
  624. return video_formats[-1]
  625. elif format_spec == 'worstvideo':
  626. video_formats = [
  627. f for f in available_formats
  628. if f.get('acodec') == 'none']
  629. if video_formats:
  630. return video_formats[0]
  631. else:
  632. extensions = ['mp4', 'flv', 'webm', '3gp']
  633. if format_spec in extensions:
  634. filter_f = lambda f: f['ext'] == format_spec
  635. else:
  636. filter_f = lambda f: f['format_id'] == format_spec
  637. matches = list(filter(filter_f, available_formats))
  638. if matches:
  639. return matches[-1]
  640. return None
  641. def process_video_result(self, info_dict, download=True):
  642. assert info_dict.get('_type', 'video') == 'video'
  643. if 'id' not in info_dict:
  644. raise ExtractorError('Missing "id" field in extractor result')
  645. if 'title' not in info_dict:
  646. raise ExtractorError('Missing "title" field in extractor result')
  647. if 'playlist' not in info_dict:
  648. # It isn't part of a playlist
  649. info_dict['playlist'] = None
  650. info_dict['playlist_index'] = None
  651. thumbnails = info_dict.get('thumbnails')
  652. if thumbnails:
  653. thumbnails.sort(key=lambda t: (
  654. t.get('width'), t.get('height'), t.get('url')))
  655. for t in thumbnails:
  656. if 'width' in t and 'height' in t:
  657. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  658. if thumbnails and 'thumbnail' not in info_dict:
  659. info_dict['thumbnail'] = thumbnails[-1]['url']
  660. if 'display_id' not in info_dict and 'id' in info_dict:
  661. info_dict['display_id'] = info_dict['id']
  662. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  663. upload_date = datetime.datetime.utcfromtimestamp(
  664. info_dict['timestamp'])
  665. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  666. # This extractors handle format selection themselves
  667. if info_dict['extractor'] in ['Youku']:
  668. if download:
  669. self.process_info(info_dict)
  670. return info_dict
  671. # We now pick which formats have to be downloaded
  672. if info_dict.get('formats') is None:
  673. # There's only one format available
  674. formats = [info_dict]
  675. else:
  676. formats = info_dict['formats']
  677. if not formats:
  678. raise ExtractorError('No video formats found!')
  679. # We check that all the formats have the format and format_id fields
  680. for i, format in enumerate(formats):
  681. if 'url' not in format:
  682. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  683. if format.get('format_id') is None:
  684. format['format_id'] = compat_str(i)
  685. if format.get('format') is None:
  686. format['format'] = '{id} - {res}{note}'.format(
  687. id=format['format_id'],
  688. res=self.format_resolution(format),
  689. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  690. )
  691. # Automatically determine file extension if missing
  692. if 'ext' not in format:
  693. format['ext'] = determine_ext(format['url']).lower()
  694. format_limit = self.params.get('format_limit', None)
  695. if format_limit:
  696. formats = list(takewhile_inclusive(
  697. lambda f: f['format_id'] != format_limit, formats
  698. ))
  699. # TODO Central sorting goes here
  700. if formats[0] is not info_dict:
  701. # only set the 'formats' fields if the original info_dict list them
  702. # otherwise we end up with a circular reference, the first (and unique)
  703. # element in the 'formats' field in info_dict is info_dict itself,
  704. # wich can't be exported to json
  705. info_dict['formats'] = formats
  706. if self.params.get('listformats', None):
  707. self.list_formats(info_dict)
  708. return
  709. req_format = self.params.get('format')
  710. if req_format is None:
  711. req_format = 'best'
  712. formats_to_download = []
  713. # The -1 is for supporting YoutubeIE
  714. if req_format in ('-1', 'all'):
  715. formats_to_download = formats
  716. else:
  717. # We can accept formats requested in the format: 34/5/best, we pick
  718. # the first that is available, starting from left
  719. req_formats = req_format.split('/')
  720. for rf in req_formats:
  721. if re.match(r'.+?\+.+?', rf) is not None:
  722. # Two formats have been requested like '137+139'
  723. format_1, format_2 = rf.split('+')
  724. formats_info = (self.select_format(format_1, formats),
  725. self.select_format(format_2, formats))
  726. if all(formats_info):
  727. selected_format = {
  728. 'requested_formats': formats_info,
  729. 'format': rf,
  730. 'ext': formats_info[0]['ext'],
  731. }
  732. else:
  733. selected_format = None
  734. else:
  735. selected_format = self.select_format(rf, formats)
  736. if selected_format is not None:
  737. formats_to_download = [selected_format]
  738. break
  739. if not formats_to_download:
  740. raise ExtractorError('requested format not available',
  741. expected=True)
  742. if download:
  743. if len(formats_to_download) > 1:
  744. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  745. for format in formats_to_download:
  746. new_info = dict(info_dict)
  747. new_info.update(format)
  748. self.process_info(new_info)
  749. # We update the info dict with the best quality format (backwards compatibility)
  750. info_dict.update(formats_to_download[-1])
  751. return info_dict
  752. def process_info(self, info_dict):
  753. """Process a single resolved IE result."""
  754. assert info_dict.get('_type', 'video') == 'video'
  755. max_downloads = self.params.get('max_downloads')
  756. if max_downloads is not None:
  757. if self._num_downloads >= int(max_downloads):
  758. raise MaxDownloadsReached()
  759. info_dict['fulltitle'] = info_dict['title']
  760. if len(info_dict['title']) > 200:
  761. info_dict['title'] = info_dict['title'][:197] + '...'
  762. # Keep for backwards compatibility
  763. info_dict['stitle'] = info_dict['title']
  764. if 'format' not in info_dict:
  765. info_dict['format'] = info_dict['ext']
  766. reason = self._match_entry(info_dict)
  767. if reason is not None:
  768. self.to_screen('[download] ' + reason)
  769. return
  770. self._num_downloads += 1
  771. filename = self.prepare_filename(info_dict)
  772. # Forced printings
  773. if self.params.get('forcetitle', False):
  774. self.to_stdout(info_dict['fulltitle'])
  775. if self.params.get('forceid', False):
  776. self.to_stdout(info_dict['id'])
  777. if self.params.get('forceurl', False):
  778. # For RTMP URLs, also include the playpath
  779. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  780. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  781. self.to_stdout(info_dict['thumbnail'])
  782. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  783. self.to_stdout(info_dict['description'])
  784. if self.params.get('forcefilename', False) and filename is not None:
  785. self.to_stdout(filename)
  786. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  787. self.to_stdout(formatSeconds(info_dict['duration']))
  788. if self.params.get('forceformat', False):
  789. self.to_stdout(info_dict['format'])
  790. if self.params.get('forcejson', False):
  791. info_dict['_filename'] = filename
  792. self.to_stdout(json.dumps(info_dict))
  793. # Do nothing else if in simulate mode
  794. if self.params.get('simulate', False):
  795. return
  796. if filename is None:
  797. return
  798. try:
  799. dn = os.path.dirname(encodeFilename(filename))
  800. if dn and not os.path.exists(dn):
  801. os.makedirs(dn)
  802. except (OSError, IOError) as err:
  803. self.report_error('unable to create directory ' + compat_str(err))
  804. return
  805. if self.params.get('writedescription', False):
  806. descfn = filename + '.description'
  807. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  808. self.to_screen('[info] Video description is already present')
  809. else:
  810. try:
  811. self.to_screen('[info] Writing video description to: ' + descfn)
  812. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  813. descfile.write(info_dict['description'])
  814. except (KeyError, TypeError):
  815. self.report_warning('There\'s no description to write.')
  816. except (OSError, IOError):
  817. self.report_error('Cannot write description file ' + descfn)
  818. return
  819. if self.params.get('writeannotations', False):
  820. annofn = filename + '.annotations.xml'
  821. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  822. self.to_screen('[info] Video annotations are already present')
  823. else:
  824. try:
  825. self.to_screen('[info] Writing video annotations to: ' + annofn)
  826. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  827. annofile.write(info_dict['annotations'])
  828. except (KeyError, TypeError):
  829. self.report_warning('There are no annotations to write.')
  830. except (OSError, IOError):
  831. self.report_error('Cannot write annotations file: ' + annofn)
  832. return
  833. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  834. self.params.get('writeautomaticsub')])
  835. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  836. # subtitles download errors are already managed as troubles in relevant IE
  837. # that way it will silently go on when used with unsupporting IE
  838. subtitles = info_dict['subtitles']
  839. sub_format = self.params.get('subtitlesformat', 'srt')
  840. for sub_lang in subtitles.keys():
  841. sub = subtitles[sub_lang]
  842. if sub is None:
  843. continue
  844. try:
  845. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  846. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  847. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  848. else:
  849. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  850. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  851. subfile.write(sub)
  852. except (OSError, IOError):
  853. self.report_error('Cannot write subtitles file ' + sub_filename)
  854. return
  855. if self.params.get('writeinfojson', False):
  856. infofn = os.path.splitext(filename)[0] + '.info.json'
  857. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  858. self.to_screen('[info] Video description metadata is already present')
  859. else:
  860. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  861. try:
  862. write_json_file(info_dict, encodeFilename(infofn))
  863. except (OSError, IOError):
  864. self.report_error('Cannot write metadata to JSON file ' + infofn)
  865. return
  866. if self.params.get('writethumbnail', False):
  867. if info_dict.get('thumbnail') is not None:
  868. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  869. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  870. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  871. self.to_screen('[%s] %s: Thumbnail is already present' %
  872. (info_dict['extractor'], info_dict['id']))
  873. else:
  874. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  875. (info_dict['extractor'], info_dict['id']))
  876. try:
  877. uf = self.urlopen(info_dict['thumbnail'])
  878. with open(thumb_filename, 'wb') as thumbf:
  879. shutil.copyfileobj(uf, thumbf)
  880. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  881. (info_dict['extractor'], info_dict['id'], thumb_filename))
  882. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  883. self.report_warning('Unable to download thumbnail "%s": %s' %
  884. (info_dict['thumbnail'], compat_str(err)))
  885. if not self.params.get('skip_download', False):
  886. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  887. success = True
  888. else:
  889. try:
  890. def dl(name, info):
  891. fd = get_suitable_downloader(info)(self, self.params)
  892. for ph in self._progress_hooks:
  893. fd.add_progress_hook(ph)
  894. if self.params.get('verbose'):
  895. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  896. return fd.download(name, info)
  897. if info_dict.get('requested_formats') is not None:
  898. downloaded = []
  899. success = True
  900. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  901. if not merger._get_executable():
  902. postprocessors = []
  903. self.report_warning('You have requested multiple '
  904. 'formats but ffmpeg or avconv are not installed.'
  905. ' The formats won\'t be merged')
  906. else:
  907. postprocessors = [merger]
  908. for f in info_dict['requested_formats']:
  909. new_info = dict(info_dict)
  910. new_info.update(f)
  911. fname = self.prepare_filename(new_info)
  912. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  913. downloaded.append(fname)
  914. partial_success = dl(fname, new_info)
  915. success = success and partial_success
  916. info_dict['__postprocessors'] = postprocessors
  917. info_dict['__files_to_merge'] = downloaded
  918. else:
  919. # Just a single file
  920. success = dl(filename, info_dict)
  921. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  922. self.report_error('unable to download video data: %s' % str(err))
  923. return
  924. except (OSError, IOError) as err:
  925. raise UnavailableVideoError(err)
  926. except (ContentTooShortError, ) as err:
  927. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  928. return
  929. if success:
  930. try:
  931. self.post_process(filename, info_dict)
  932. except (PostProcessingError) as err:
  933. self.report_error('postprocessing: %s' % str(err))
  934. return
  935. self.record_download_archive(info_dict)
  936. def download(self, url_list):
  937. """Download a given list of URLs."""
  938. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  939. if (len(url_list) > 1 and
  940. '%' not in outtmpl
  941. and self.params.get('max_downloads') != 1):
  942. raise SameFileError(outtmpl)
  943. for url in url_list:
  944. try:
  945. #It also downloads the videos
  946. self.extract_info(url)
  947. except UnavailableVideoError:
  948. self.report_error('unable to download video')
  949. except MaxDownloadsReached:
  950. self.to_screen('[info] Maximum number of downloaded files reached.')
  951. raise
  952. return self._download_retcode
  953. def download_with_info_file(self, info_filename):
  954. with io.open(info_filename, 'r', encoding='utf-8') as f:
  955. info = json.load(f)
  956. try:
  957. self.process_ie_result(info, download=True)
  958. except DownloadError:
  959. webpage_url = info.get('webpage_url')
  960. if webpage_url is not None:
  961. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  962. return self.download([webpage_url])
  963. else:
  964. raise
  965. return self._download_retcode
  966. def post_process(self, filename, ie_info):
  967. """Run all the postprocessors on the given file."""
  968. info = dict(ie_info)
  969. info['filepath'] = filename
  970. keep_video = None
  971. pps_chain = []
  972. if ie_info.get('__postprocessors') is not None:
  973. pps_chain.extend(ie_info['__postprocessors'])
  974. pps_chain.extend(self._pps)
  975. for pp in pps_chain:
  976. try:
  977. keep_video_wish, new_info = pp.run(info)
  978. if keep_video_wish is not None:
  979. if keep_video_wish:
  980. keep_video = keep_video_wish
  981. elif keep_video is None:
  982. # No clear decision yet, let IE decide
  983. keep_video = keep_video_wish
  984. except PostProcessingError as e:
  985. self.report_error(e.msg)
  986. if keep_video is False and not self.params.get('keepvideo', False):
  987. try:
  988. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  989. os.remove(encodeFilename(filename))
  990. except (IOError, OSError):
  991. self.report_warning('Unable to remove downloaded video file')
  992. def _make_archive_id(self, info_dict):
  993. # Future-proof against any change in case
  994. # and backwards compatibility with prior versions
  995. extractor = info_dict.get('extractor_key')
  996. if extractor is None:
  997. if 'id' in info_dict:
  998. extractor = info_dict.get('ie_key') # key in a playlist
  999. if extractor is None:
  1000. return None # Incomplete video information
  1001. return extractor.lower() + ' ' + info_dict['id']
  1002. def in_download_archive(self, info_dict):
  1003. fn = self.params.get('download_archive')
  1004. if fn is None:
  1005. return False
  1006. vid_id = self._make_archive_id(info_dict)
  1007. if vid_id is None:
  1008. return False # Incomplete video information
  1009. try:
  1010. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1011. for line in archive_file:
  1012. if line.strip() == vid_id:
  1013. return True
  1014. except IOError as ioe:
  1015. if ioe.errno != errno.ENOENT:
  1016. raise
  1017. return False
  1018. def record_download_archive(self, info_dict):
  1019. fn = self.params.get('download_archive')
  1020. if fn is None:
  1021. return
  1022. vid_id = self._make_archive_id(info_dict)
  1023. assert vid_id
  1024. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1025. archive_file.write(vid_id + '\n')
  1026. @staticmethod
  1027. def format_resolution(format, default='unknown'):
  1028. if format.get('vcodec') == 'none':
  1029. return 'audio only'
  1030. if format.get('resolution') is not None:
  1031. return format['resolution']
  1032. if format.get('height') is not None:
  1033. if format.get('width') is not None:
  1034. res = '%sx%s' % (format['width'], format['height'])
  1035. else:
  1036. res = '%sp' % format['height']
  1037. elif format.get('width') is not None:
  1038. res = '?x%d' % format['width']
  1039. else:
  1040. res = default
  1041. return res
  1042. def _format_note(self, fdict):
  1043. res = ''
  1044. if fdict.get('ext') in ['f4f', 'f4m']:
  1045. res += '(unsupported) '
  1046. if fdict.get('format_note') is not None:
  1047. res += fdict['format_note'] + ' '
  1048. if fdict.get('tbr') is not None:
  1049. res += '%4dk ' % fdict['tbr']
  1050. if fdict.get('container') is not None:
  1051. if res:
  1052. res += ', '
  1053. res += '%s container' % fdict['container']
  1054. if (fdict.get('vcodec') is not None and
  1055. fdict.get('vcodec') != 'none'):
  1056. if res:
  1057. res += ', '
  1058. res += fdict['vcodec']
  1059. if fdict.get('vbr') is not None:
  1060. res += '@'
  1061. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1062. res += 'video@'
  1063. if fdict.get('vbr') is not None:
  1064. res += '%4dk' % fdict['vbr']
  1065. if fdict.get('acodec') is not None:
  1066. if res:
  1067. res += ', '
  1068. if fdict['acodec'] == 'none':
  1069. res += 'video only'
  1070. else:
  1071. res += '%-5s' % fdict['acodec']
  1072. elif fdict.get('abr') is not None:
  1073. if res:
  1074. res += ', '
  1075. res += 'audio'
  1076. if fdict.get('abr') is not None:
  1077. res += '@%3dk' % fdict['abr']
  1078. if fdict.get('asr') is not None:
  1079. res += ' (%5dHz)' % fdict['asr']
  1080. if fdict.get('filesize') is not None:
  1081. if res:
  1082. res += ', '
  1083. res += format_bytes(fdict['filesize'])
  1084. elif fdict.get('filesize_approx') is not None:
  1085. if res:
  1086. res += ', '
  1087. res += '~' + format_bytes(fdict['filesize_approx'])
  1088. return res
  1089. def list_formats(self, info_dict):
  1090. def line(format, idlen=20):
  1091. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1092. format['format_id'],
  1093. format['ext'],
  1094. self.format_resolution(format),
  1095. self._format_note(format),
  1096. ))
  1097. formats = info_dict.get('formats', [info_dict])
  1098. idlen = max(len('format code'),
  1099. max(len(f['format_id']) for f in formats))
  1100. formats_s = [line(f, idlen) for f in formats]
  1101. if len(formats) > 1:
  1102. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1103. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1104. header_line = line({
  1105. 'format_id': 'format code', 'ext': 'extension',
  1106. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1107. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1108. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1109. def urlopen(self, req):
  1110. """ Start an HTTP download """
  1111. return self._opener.open(req, timeout=self._socket_timeout)
  1112. def print_debug_header(self):
  1113. if not self.params.get('verbose'):
  1114. return
  1115. if type('') is not compat_str:
  1116. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1117. self.report_warning(
  1118. 'Your Python is broken! Update to a newer and supported version')
  1119. encoding_str = (
  1120. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1121. locale.getpreferredencoding(),
  1122. sys.getfilesystemencoding(),
  1123. sys.stdout.encoding,
  1124. self.get_encoding()))
  1125. write_string(encoding_str, encoding=None)
  1126. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1127. try:
  1128. sp = subprocess.Popen(
  1129. ['git', 'rev-parse', '--short', 'HEAD'],
  1130. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1131. cwd=os.path.dirname(os.path.abspath(__file__)))
  1132. out, err = sp.communicate()
  1133. out = out.decode().strip()
  1134. if re.match('[0-9a-f]+', out):
  1135. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1136. except:
  1137. try:
  1138. sys.exc_clear()
  1139. except:
  1140. pass
  1141. self._write_string('[debug] Python version %s - %s' %
  1142. (platform.python_version(), platform_name()) + '\n')
  1143. proxy_map = {}
  1144. for handler in self._opener.handlers:
  1145. if hasattr(handler, 'proxies'):
  1146. proxy_map.update(handler.proxies)
  1147. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1148. def _setup_opener(self):
  1149. timeout_val = self.params.get('socket_timeout')
  1150. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1151. opts_cookiefile = self.params.get('cookiefile')
  1152. opts_proxy = self.params.get('proxy')
  1153. if opts_cookiefile is None:
  1154. self.cookiejar = compat_cookiejar.CookieJar()
  1155. else:
  1156. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1157. opts_cookiefile)
  1158. if os.access(opts_cookiefile, os.R_OK):
  1159. self.cookiejar.load()
  1160. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1161. self.cookiejar)
  1162. if opts_proxy is not None:
  1163. if opts_proxy == '':
  1164. proxies = {}
  1165. else:
  1166. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1167. else:
  1168. proxies = compat_urllib_request.getproxies()
  1169. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1170. if 'http' in proxies and 'https' not in proxies:
  1171. proxies['https'] = proxies['http']
  1172. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1173. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1174. https_handler = make_HTTPS_handler(
  1175. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1176. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1177. opener = compat_urllib_request.build_opener(
  1178. https_handler, proxy_handler, cookie_processor, ydlh)
  1179. # Delete the default user-agent header, which would otherwise apply in
  1180. # cases where our custom HTTP handler doesn't come into play
  1181. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1182. opener.addheaders = []
  1183. self._opener = opener
  1184. def encode(self, s):
  1185. if isinstance(s, bytes):
  1186. return s # Already encoded
  1187. try:
  1188. return s.encode(self.get_encoding())
  1189. except UnicodeEncodeError as err:
  1190. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1191. raise
  1192. def get_encoding(self):
  1193. encoding = self.params.get('encoding')
  1194. if encoding is None:
  1195. encoding = preferredencoding()
  1196. return encoding