artbound_python/cache.py (view raw)
1import os, shutil
2from datetime import datetime
3from contextlib import suppress
4
5import requests
6from artbound_python.api import get_file, get_rows
7
8CACHE_DIRECTORY = "cache"
9CACHE_PATH = os.path.join("artbound_python", "static", "res", CACHE_DIRECTORY)
10
11with suppress(FileExistsError):
12 os.makedirs(CACHE_PATH)
13
14def download_fanart(fanart_id: str):
15 cached_files = os.listdir(CACHE_PATH)
16 cached_ids = [ x.split(".")[0] for x in cached_files ]
17 try:
18 position = cached_ids.index(fanart_id)
19 fanart = cached_files[position]
20 except ValueError:
21 print("Downloading", fanart_id)
22 fanart = get_file(fanart_id, CACHE_PATH)
23
24 return f"/static/res/{CACHE_DIRECTORY}/{fanart}"
25
26def clear_cache():
27 shutil.rmtree(CACHE_PATH)
28
29def handle_fanart(fanart):
30 fanart["content"] = download_fanart(fanart["id"])
31 return fanart
32
33def handle_row(row):
34 fanart_date = datetime.strptime(row[0], "%d/%m/%Y %H.%M.%S")
35 return {
36 'id': row[3][33:],
37 'date': fanart_date.strftime("%Y-%m"),
38 'name': row[1],
39 }
40
41class DB():
42 def update_database(self):
43 prev_length = len(self.db)
44 self.db = [ handle_row(x) for x in get_rows() ]
45 new_length = len(self.db)
46 if new_length == 0:
47 print("No fanarts!")
48 exit(1)
49 self.last_updated = datetime.now()
50 return new_length - prev_length
51
52 def __init__(self):
53 self.db = []
54 self.update_database()
55
56 def get_fanarts(self, month):
57 return [ handle_fanart(x) for x in self.db if x["date"] == month ]
58
59 def get_last_updated(self):
60 return self.last_updated.strftime("%d/%m/%Y %H:%M")