all repos — artbound-python @ 3072e0a7b9031c7de2553ca81f15e47e47b79f82

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 = None
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_id = fanart["id"]
35    fanart["content"] = download_fanart(fanart_id)
36    return fanart
37
38def handle_row(row):
39    fanart_date = datetime.strptime(row[0], "%d/%m/%Y %H.%M.%S")
40    fanart_id = row[3].strip("https://drive.google.com/open?id=")
41    return {
42        'id': fanart_id,
43        'date': fanart_date.strftime("%Y-%m"),
44        'name': row[1],
45        'enabled': 1
46	}
47
48def update_database():
49    global db
50    global last_updated
51    db = [ handle_row(x) for x in get_rows() ]
52    if len(db) == 0:
53        print("No fanarts!")
54        exit(1)
55    last_updated = datetime.now()
56
57def get_fanarts(month):
58    return [ handle_fanart(x) for x in db if x["date"] == month ]
59
60update_database()
61
62if __name__ == "__main__":
63    print(handle_fanart({ 'id': '1_DUo-dW40So3T24a91SyGrEcAGKfP0l_'}))
64    #clear_cache()