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