all repos — artbound-python @ 0edae2b70652990a729ba21b58d5eb12a11f7496

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