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