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
11db = []
12last_updated = ""
13
14with suppress(FileExistsError):
15 os.makedirs(CACHE_PATH)
16
17def download_fanart(fanart_id: str):
18 cached_files = os.listdir(CACHE_PATH)
19 cached_ids = [ x.split(".")[0] for x in cached_files ]
20 try:
21 position = cached_ids.index(fanart_id)
22 print("Using cached file.")
23 fanart = cached_files[position]
24 except ValueError:
25 print("File is not cached. Downloading.")
26 fanart = get_file(fanart_id, CACHE_PATH)
27
28 return f"/static/res/{CACHE_DIRECTORY}/{fanart}"
29
30def clear_cache():
31 shutil.rmtree(CACHE_PATH)
32
33def handle_fanart(fanart):
34 fanart["content"] = download_fanart(fanart["id"])
35 return fanart
36
37def handle_row(row):
38 fanart_date = datetime.strptime(row[0], "%d/%m/%Y %H.%M.%S")
39 fanart_id = row[3][33:]
40 return {
41 'id': fanart_id,
42 'date': fanart_date.strftime("%Y-%m"),
43 'name': row[1],
44 'enabled': 1,
45 'watermark': { 'invert': '' }
46 }
47
48class DB():
49 def update_database(self):
50 self.db = [ handle_row(x) for x in get_rows() ]
51 if len(self.db) == 0:
52 print("No fanarts!")
53 exit(1)
54 self.last_updated = datetime.now()
55
56 def __init__(self):
57 self.db = []
58 self.update_database()
59
60 def get_fanarts(self, month):
61 return [ handle_fanart(x) for x in self.db if x["date"] == month ]
62
63 def get_last_updated(self):
64 return self.last_updated.strftime("%d/%m/%Y %H:%M")