all repos — artbound-python @ 76a90cd6e791a9580cccd1205dc7328bf80cf223

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        fanart = cached_files[position]
23    except ValueError:
24        print("Downloading", fanart_id)
25        fanart = get_file(fanart_id, CACHE_PATH)
26        
27    return f"/static/res/{CACHE_DIRECTORY}/{fanart}"
28
29def clear_cache():
30    shutil.rmtree(CACHE_PATH)
31
32def handle_fanart(fanart):
33    fanart["content"] = download_fanart(fanart["id"])
34    return fanart
35
36def handle_row(row):
37    fanart_date = datetime.strptime(row[0], "%d/%m/%Y %H.%M.%S")
38    fanart_id = row[3][33:]
39    return {
40        'id': fanart_id,
41        'date': fanart_date.strftime("%Y-%m"),
42        'name': row[1],
43        'enabled': 1,
44        'watermark': { 'invert': '' }
45	}
46    
47class DB():
48    def update_database(self):
49        prev_length = len(self.db)
50        self.db = [ handle_row(x) for x in get_rows() ]
51        new_length = len(self.db)
52        if new_length == 0:
53            print("No fanarts!")
54            exit(1)
55        self.last_updated = datetime.now()
56        return new_length - prev_length
57    
58    def __init__(self):
59        self.db = []
60        self.update_database()
61        
62    def get_fanarts(self, month):
63        return [ handle_fanart(x) for x in self.db if x["date"] == month ]
64    
65    def get_last_updated(self):
66        return self.last_updated.strftime("%d/%m/%Y %H:%M")