]>
jfr.im git - yt-dlp.git/blob - youtube_dl/cache.py
1 from __future__
import unicode_literals
17 def __init__(self
, ydl
):
20 def _get_root_dir(self
):
21 res
= self
._ydl
.params
.get('cachedir')
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
)
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
32 self
._get
_root
_dir
(), section
, '%s.%s' % (key
, dtype
))
36 return self
._ydl
.params
.get('cachedir') is not False
38 def store(self
, section
, key
, data
, dtype
='json'):
39 assert dtype
in ('json',)
44 fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
47 os
.makedirs(os
.path
.dirname(fn
))
48 except OSError as ose
:
49 if ose
.errno
!= errno
.EEXIST
:
51 write_json_file(data
, fn
)
53 tb
= traceback
.format_exc()
54 self
._ydl
.report_warning(
55 'Writing cache to %r failed: %s' % (fn
, tb
))
57 def load(self
, section
, key
, dtype
='json', default
=None):
58 assert dtype
in ('json',)
63 cache_fn
= self
._get
_cache
_fn
(section
, key
, dtype
)
66 with io
.open(cache_fn
, 'r', encoding
='utf-8') as cachef
:
67 return json
.load(cachef
)
70 file_size
= os
.path
.getsize(cache_fn
)
71 except (OSError, IOError) as oe
:
73 self
._ydl
.report_warning(
74 'Cache retrieval from %s failed (%s)' % (cache_fn
, file_size
))
76 pass # No cache available
82 self
._ydl
.to_screen('Cache is disabled (Did you combine --no-cache-dir and --rm-cache-dir?)')
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
)
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('.')