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.

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