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.

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