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.

95 lines
2.9 KiB

  1. from __future__ import unicode_literals
  2. import errno
  3. import io
  4. import json
  5. import os
  6. import re
  7. import shutil
  8. import traceback
  9. from .utils import (
  10. compat_expanduser,
  11. write_json_file,
  12. )
  13. class Cache(object):
  14. def __init__(self, ydl):
  15. self._ydl = ydl
  16. def _get_root_dir(self):
  17. res = self._ydl.params.get('cachedir')
  18. if res is None:
  19. cache_root = os.environ.get('XDG_CACHE_HOME', '~/.cache')
  20. res = os.path.join(cache_root, 'youtube-dl')
  21. return compat_expanduser(res)
  22. def _get_cache_fn(self, section, key, dtype):
  23. assert re.match(r'^[a-zA-Z0-9_.-]+$', section), \
  24. 'invalid section %r' % section
  25. assert re.match(r'^[a-zA-Z0-9_.-]+$', key), 'invalid key %r' % key
  26. return os.path.join(
  27. self._get_root_dir(), section, '%s.%s' % (key, dtype))
  28. @property
  29. def enabled(self):
  30. return self._ydl.params.get('cachedir') is not False
  31. def store(self, section, key, data, dtype='json'):
  32. assert dtype in ('json',)
  33. if not self.enabled:
  34. return
  35. fn = self._get_cache_fn(section, key, dtype)
  36. try:
  37. try:
  38. os.makedirs(os.path.dirname(fn))
  39. except OSError as ose:
  40. if ose.errno != errno.EEXIST:
  41. raise
  42. write_json_file(data, fn)
  43. except Exception:
  44. tb = traceback.format_exc()
  45. self._ydl.report_warning(
  46. 'Writing cache to %r failed: %s' % (fn, tb))
  47. def load(self, section, key, dtype='json', default=None):
  48. assert dtype in ('json',)
  49. if not self.enabled:
  50. return default
  51. cache_fn = self._get_cache_fn(section, key, dtype)
  52. try:
  53. try:
  54. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  55. return json.load(cachef)
  56. except ValueError:
  57. try:
  58. file_size = os.path.getsize(cache_fn)
  59. except (OSError, IOError) as oe:
  60. file_size = str(oe)
  61. self._ydl.report_warning(
  62. 'Cache retrieval from %s failed (%s)' % (cache_fn, file_size))
  63. except IOError:
  64. pass # No cache available
  65. return default
  66. def remove(self):
  67. if not self.enabled:
  68. self._ydl.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
  69. return
  70. cachedir = self._get_root_dir()
  71. if not any((term in cachedir) for term in ('cache', 'tmp')):
  72. raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir)
  73. self._ydl.to_screen(
  74. 'Removing cache dir %s .' % cachedir, skip_eol=True)
  75. if os.path.exists(cachedir):
  76. self._ydl.to_screen('.', skip_eol=True)
  77. shutil.rmtree(cachedir)
  78. self._ydl.to_screen('.')