cache.py 2.9 KB

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