1 from __future__ import unicode_literals
11 from .compat import compat_expanduser
12 from .utils import write_json_file
16 def __init__(self, ydl):
19 def _get_root_dir(self):
20 res = self._ydl.params.get('cachedir')
22 cache_root = os.environ.get('XDG_CACHE_HOME', '~/.cache')
23 res = os.path.join(cache_root, 'youtube-dl')
24 return compat_expanduser(res)
26 def _get_cache_fn(self, section, key, dtype):
27 assert re.match(r'^[a-zA-Z0-9_.-]+$', section), \
28 'invalid section %r' % section
29 assert re.match(r'^[a-zA-Z0-9_.-]+$', key), 'invalid key %r' % key
31 self._get_root_dir(), section, '%s.%s' % (key, dtype))
35 return self._ydl.params.get('cachedir') is not False
37 def store(self, section, key, data, dtype='json'):
38 assert dtype in ('json',)
43 fn = self._get_cache_fn(section, key, dtype)
46 os.makedirs(os.path.dirname(fn))
47 except OSError as ose:
48 if ose.errno != errno.EEXIST:
50 write_json_file(data, fn)
52 tb = traceback.format_exc()
53 self._ydl.report_warning(
54 'Writing cache to %r failed: %s' % (fn, tb))
56 def load(self, section, key, dtype='json', default=None):
57 assert dtype in ('json',)
62 cache_fn = self._get_cache_fn(section, key, dtype)
65 with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
66 return json.load(cachef)
69 file_size = os.path.getsize(cache_fn)
70 except (OSError, IOError) as oe:
72 self._ydl.report_warning(
73 'Cache retrieval from %s failed (%s)' % (cache_fn, file_size))
75 pass # No cache available
81 self._ydl.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
84 cachedir = self._get_root_dir()
85 if not any((term in cachedir) for term in ('cache', 'tmp')):
86 raise Exception('Not removing directory %s - this does not look like a cache dir' % cachedir)
89 'Removing cache dir %s .' % cachedir, skip_eol=True)
90 if os.path.exists(cachedir):
91 self._ydl.to_screen('.', skip_eol=True)
92 shutil.rmtree(cachedir)
93 self._ydl.to_screen('.')