all repos — artbound-python @ 46af02e02321e5eeae46e8af264d3098299ade87

A client-server reimplementation of the administration panel for ArtBound.

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	}
46    
47class DB():
48    def update_database(self):
49        self.db = [ handle_row(x) for x in get_rows() ]
50        if len(self.db) == 0:
51            print("No fanarts!")
52            exit(1)
53        self.last_updated = datetime.now()
54    
55    def __init__(self):
56        self.db = []
57        self.update_database()
58        
59    def get_fanarts(self, month):
60        return [ handle_fanart(x) for x in self.db if x["date"] == month ]
61    
62    def get_last_updated(self):
63        return self.last_updated.strftime("%d/%m/%Y %H:%M")