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 SERVICE = ('EchoNest', 'LastFM')
31 def parse_cache_control(headers):
33 Parse the cache control headers returning a dictionary with values
34 for the different directives.
37 # requests provides a CaseInsensitiveDict as headers
38 cc_header = 'cache-control'
39 if cc_header in headers:
40 parts = headers[cc_header].split(',')
42 tuple([x.strip().lower() for x in part.split("=", 1)])
43 for part in parts if -1 != part.find("=")]
44 parts_wo_args = [(name.strip().lower(), 1)
45 for name in parts if -1 == name.find("=")]
46 retval = dict(parts_with_args + parts_wo_args)
50 """encode url to hash table key"""
51 return md5(val.encode('utf-8')).hexdigest()
54 homedir = environ.get('HOME')
55 xdh = environ.get('XDG_DATA_HOME', pjoin(homedir, '.local/share/'))
56 default_cache = pjoin(xdh, 'mpd_sima/http/', SERVICE[1])
57 cache = environ.get('SIMA_VARDIR', default_cache)
60 local_var = 'DEFAULTS\n\tXDG_DATA_HOME={0}\n\n\tWill use: {1}\n'.format(xdh, cache)
61 print(__doc__.split('HELP')[0]+local_var)
64 # use SIMA_VARDIR to override default XDG_DATA_HOME
65 cache_obj = sima.lib.cache.FileCache(environ.get('SIMA_VARDIR', cache))
67 for elem in cache_obj:
69 date = calendar.timegm(email.utils.parsedate_tz(elem.headers.get('Date')))
70 current_age = max(0, now - date)
71 cc = parse_cache_control(elem.headers)
73 freshness_lifetime = 0
74 if 'max-age' in cc and cc['max-age'].isdigit():
75 freshness_lifetime = int(cc['max-age'])
76 elif 'expires' in elem.headers:
77 expires = email.utils.parsedate_tz(elem.headers['expires'])
78 if expires is not None:
79 expire_time = calendar.timegm(expires) - date
80 freshness_lifetime = max(0, expire_time)
82 # see how fresh we actually are
83 fresh = (freshness_lifetime > current_age)
90 # we're not fresh. If we don't have an Etag, clear it out
91 if 'etag' not in elem.headers:
92 #print('no etag and expired')
93 print(pjoin(cache, encode(elem.url)))
97 # vim: ai ts=4 sw=4 sts=4 expandtab