Initial port of core code to Python3.
[automanga.git] / manga / htcache.py
CommitLineData
3cc7937c 1import os, hashlib, urllib.request, time
f3ad0817
FT
2pj = os.path.join
3
4class cache(object):
5 def __init__(self, dir):
6 self.dir = dir
7
8 def mangle(self, url):
3cc7937c
FT
9 n = hashlib.md5()
10 n.update(url.encode("ascii"))
f3ad0817
FT
11 return n.hexdigest()
12
d6c0e189 13 def miss(self, url):
3cc7937c 14 with urllib.request.urlopen(url) as s:
75efe5be 15 if s.headers.get("content-encoding") == "gzip":
3cc7937c
FT
16 import gzip, io
17 return gzip.GzipFile(fileobj=io.BytesIO(s.read()), mode="r").read()
d6c0e189 18 return s.read()
d6c0e189 19
3cc7937c 20 def fetch(self, url, expire=3600):
f3ad0817
FT
21 path = pj(self.dir, self.mangle(url))
22 if os.path.exists(path):
23 if time.time() - os.stat(path).st_mtime < expire:
3cc7937c 24 with open(path, "rb") as f:
f3ad0817 25 return f.read()
d6c0e189 26 data = self.miss(url)
f3ad0817
FT
27 if not os.path.isdir(self.dir):
28 os.makedirs(self.dir)
3cc7937c 29 with open(path, "wb") as f:
f3ad0817
FT
30 f.write(data)
31 return data
32
33home = os.getenv("HOME")
34if home is None or not os.path.isdir(home):
35 raise Exception("Could not find home directory for HTTP caching")
36default = cache(pj(home, ".manga", "htcache"))
37
3cc7937c 38def fetch(url, expire=3600):
f3ad0817 39 return default.fetch(url, expire)