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