Files
port-ui/app/utils/cache_manager.py

46 lines
1.5 KiB
Python
Raw Normal View History

2025-01-09 14:27:07 +01:00
import os
import hashlib
import requests
2025-07-07 12:40:25 +02:00
import mimetypes
2025-01-09 14:27:07 +01:00
class CacheManager:
def __init__(self, cache_dir="static/cache"):
self.cache_dir = cache_dir
self._ensure_cache_dir_exists()
def _ensure_cache_dir_exists(self):
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
def clear_cache(self):
if os.path.exists(self.cache_dir):
for filename in os.listdir(self.cache_dir):
2025-07-07 13:19:49 +02:00
path = os.path.join(self.cache_dir, filename)
if os.path.isfile(path):
os.remove(path)
2025-01-09 14:27:07 +01:00
def cache_file(self, file_url):
2025-07-07 13:19:49 +02:00
# generate a short hash for filename
hash_suffix = hashlib.blake2s(file_url.encode('utf-8'), digest_size=8).hexdigest()
parts = file_url.rstrip("/").split("/")
base = parts[-2] if parts[-1] == "download" else parts[-1]
2025-07-07 12:40:25 +02:00
try:
2025-07-07 13:19:49 +02:00
resp = requests.get(file_url, stream=True, timeout=5)
resp.raise_for_status()
2025-07-07 12:40:25 +02:00
except requests.RequestException:
2025-07-07 13:19:49 +02:00
return None
2025-07-07 12:40:25 +02:00
2025-07-07 13:19:49 +02:00
content_type = resp.headers.get('Content-Type', '')
ext = mimetypes.guess_extension(content_type.split(";")[0].strip()) or ".png"
filename = f"{base}_{hash_suffix}{ext}"
2025-01-09 14:27:07 +01:00
full_path = os.path.join(self.cache_dir, filename)
2025-07-07 12:40:25 +02:00
if not os.path.exists(full_path):
2025-07-07 13:19:49 +02:00
with open(full_path, "wb") as f:
for chunk in resp.iter_content(1024):
f.write(chunk)
2025-01-09 14:27:07 +01:00
2025-07-07 13:19:49 +02:00
# return path relative to /static/
return f"cache/{filename}"