2 # -*- coding: utf-8 -*-
5 List expired entries of sima's internal http cache.
7 Use SIMA_VARDIR env. var to override default location.
9 SIMA_VARDIR="/var/lib/mpd-sima/http/LastFM/" ./list_expired_cache
11 Default location: $XDG_DATA_HOME/http/LastFM/
12 $XDG_DATA_HOME usually expands to $HOME/.local/share/
15 Run script with "-h" CLI option for info on defaults.
23 from hashlib import md5
24 from os import environ
25 from os.path import join as pjoin
29 def parse_cache_control(headers):
31 Parse the cache control headers returning a dictionary with values
32 for the different directives.
35 # requests provides a CaseInsensitiveDict as headers
36 cc_header = 'cache-control'
37 if cc_header in headers:
38 parts = headers[cc_header].split(',')
40 tuple([x.strip().lower() for x in part.split("=", 1)])
41 for part in parts if -1 != part.find("=")]
42 parts_wo_args = [(name.strip().lower(), 1)
43 for name in parts if -1 == name.find("=")]
44 retval = dict(parts_with_args + parts_wo_args)
48 """encode url to hash table key"""
49 return md5(val.encode('utf-8')).hexdigest()
52 homedir = environ.get('HOME')
53 xdh = environ.get('XDG_DATA_HOME', pjoin(homedir, '.local/share/'))
54 default_cache = pjoin(xdh, 'mpd_sima/http/LastFM')
55 cache = environ.get('SIMA_VARDIR', default_cache)
58 local_var = 'DEFAULTS\n\tXDG_DATA_HOME={0}\n\n\tWill use: {1}\n'.format(xdh, cache)
59 print(__doc__.split('HELP')[0]+local_var)
62 # use SIMA_VARDIR to override default XDG_DATA_HOME
63 cache_obj = sima.lib.cache.FileCache(environ.get('SIMA_VARDIR', cache))
65 for elem in cache_obj:
67 date = calendar.timegm(email.utils.parsedate_tz(elem.headers.get('Date')))
68 current_age = max(0, now - date)
69 cc = parse_cache_control(elem.headers)
71 freshness_lifetime = 0
72 if 'max-age' in cc and cc['max-age'].isdigit():
73 freshness_lifetime = int(cc['max-age'])
74 elif 'expires' in elem.headers:
75 expires = email.utils.parsedate_tz(elem.headers['expires'])
76 if expires is not None:
77 expire_time = calendar.timegm(expires) - date
78 freshness_lifetime = max(0, expire_time)
80 # see how fresh we actually are
81 fresh = (freshness_lifetime > current_age)
88 # we're not fresh. If we don't have an Etag, clear it out
89 if 'etag' not in elem.headers:
90 #print('no etag and expired')
91 print(pjoin(cache, encode(elem.url)))
95 # vim: ai ts=4 sw=4 sts=4 expandtab