feat: serve Belki images through private MinIO
This commit is contained in:
1 parent
b45e4925a6
commit
ecc1f696da
14 files changed
+196
-121
No files matched your search
+68
-70
@@ -1,14 +1,14 @@
|
||||
"""
|
||||
Клиент для зеркалирования фотографий из VK на external image-host.
|
||||
|
||||
Используется для хранения скриншотов-приложений к отчётам.
|
||||
"""
|
||||
"""Private MinIO-backed storage for report screenshots and VK attachments."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Iterator
|
||||
from io import BytesIO
|
||||
import os
|
||||
from urllib.request import Request, urlopen
|
||||
import secrets
|
||||
from urllib.request import urlopen
|
||||
|
||||
from minio import Minio
|
||||
|
||||
|
||||
class ImageHostError(RuntimeError):
|
||||
@@ -29,23 +29,32 @@ def detect_raster_image_type(body: bytes) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
class ImageHostClient:
|
||||
"""
|
||||
Клиент для mirror VK-фото на external image-host.
|
||||
|
||||
Использует API image-hosting-web (initiate upload → PUT file → get URL).
|
||||
"""
|
||||
def __init__(self, api_url: str | None = None, retention: str = "forever", timeout: int = 30) -> None:
|
||||
"""
|
||||
Args:
|
||||
api_url: URL API image-host (из BELKI_IMAGE_HOST_API_URL)
|
||||
retention: Политика хранения (по умолчанию "forever")
|
||||
timeout: Таймаут HTTP-запросов в секундах
|
||||
"""
|
||||
self.api_url = (api_url or os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).rstrip("/")
|
||||
self.retention = retention
|
||||
class ImageStoreClient:
|
||||
"""Stores images in private MinIO and returns URLs served by Belki itself."""
|
||||
|
||||
def __init__(self, endpoints: str | None = None, access_key: str | None = None,
|
||||
secret_key: str | None = None, bucket: str | None = None,
|
||||
public_url: str | None = None, secure: bool | None = None, timeout: int = 30) -> None:
|
||||
raw_endpoints = endpoints if endpoints is not None else os.getenv("BELKI_S3_ENDPOINTS", "")
|
||||
self.endpoints = tuple(item.strip().removeprefix("http://").removeprefix("https://") for item in raw_endpoints.split(",") if item.strip())
|
||||
self.access_key = access_key if access_key is not None else os.getenv("BELKI_S3_ACCESS_KEY", "")
|
||||
self.secret_key = secret_key if secret_key is not None else os.getenv("BELKI_S3_SECRET_KEY", "")
|
||||
self.bucket = bucket if bucket is not None else os.getenv("BELKI_S3_BUCKET", "belki-images")
|
||||
self.public_url = (public_url if public_url is not None else os.getenv("BELKI_IMAGE_PUBLIC_URL", "")).rstrip("/")
|
||||
self.secure = secure if secure is not None else os.getenv("BELKI_S3_SECURE", "false").lower() == "true"
|
||||
self.timeout = timeout
|
||||
|
||||
def _clients(self) -> Iterator[Minio]:
|
||||
if not self.endpoints or not self.access_key or not self.secret_key:
|
||||
raise ImageHostError("image storage is not configured")
|
||||
for endpoint in self.endpoints:
|
||||
yield Minio(endpoint, access_key=self.access_key, secret_key=self.secret_key, secure=self.secure)
|
||||
|
||||
def _public_url(self, object_name: str) -> str:
|
||||
if not self.public_url:
|
||||
raise ImageHostError("image public URL is not configured")
|
||||
return f"{self.public_url}/api/images/{object_name}"
|
||||
|
||||
def mirror(self, photo: dict[str, object]) -> str | None:
|
||||
"""
|
||||
Зеркалирует одну VK-фотографию на image-host.
|
||||
@@ -62,7 +71,7 @@ class ImageHostClient:
|
||||
Returns:
|
||||
Прямая ссылка на загруженное фото или None
|
||||
"""
|
||||
if not self.api_url or not photo.get("url"):
|
||||
if not photo.get("url"):
|
||||
return None
|
||||
source_url = str(photo["url"])
|
||||
with urlopen(source_url, timeout=self.timeout) as response:
|
||||
@@ -84,56 +93,45 @@ class ImageHostClient:
|
||||
return self.upload_bytes(body, file_name, content_type)
|
||||
|
||||
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
|
||||
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
|
||||
if not self.api_url or not body:
|
||||
"""Stores bytes privately and returns the public Belki-proxy URL."""
|
||||
if not body:
|
||||
return None
|
||||
content_type = detect_raster_image_type(body)
|
||||
if content_type is None:
|
||||
raise ImageHostError("only PNG, JPEG, and WebP images are supported")
|
||||
suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}.get(content_type)
|
||||
if suffix is None:
|
||||
raise ImageHostError("only PNG, JPEG, and WebP images are supported")
|
||||
object_name = f"{secrets.token_hex(16)}.{suffix}"
|
||||
last_error: Exception | None = None
|
||||
try:
|
||||
initiate = self._request_json(
|
||||
"/api/uploads/initiate",
|
||||
{
|
||||
"retention": self.retention,
|
||||
"files": [{"name": file_name, "size": len(body), "type": content_type}],
|
||||
},
|
||||
)
|
||||
files = initiate.get("files") or []
|
||||
if not files or not files[0].get("uploadUrl"):
|
||||
raise ImageHostError("image host did not return an upload URL")
|
||||
upload = files[0]
|
||||
request = Request(
|
||||
str(upload["uploadUrl"]),
|
||||
data=body,
|
||||
method="PUT",
|
||||
headers={str(key): str(value) for key, value in (upload.get("uploadHeaders") or {}).items()},
|
||||
)
|
||||
with urlopen(request, timeout=self.timeout):
|
||||
pass
|
||||
return str(upload.get("directUrl") or upload.get("cdnUrl") or "") or None
|
||||
for client in self._clients():
|
||||
try:
|
||||
client.put_object(self.bucket, object_name, BytesIO(body), len(body), content_type=content_type)
|
||||
return self._public_url(object_name)
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
except ImageHostError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ImageHostError(f"image host upload failed: {exc}") from exc
|
||||
if last_error is not None:
|
||||
raise ImageHostError(f"image storage upload failed: {last_error}") from last_error
|
||||
raise ImageHostError("image storage has no reachable endpoints")
|
||||
|
||||
def _request_json(self, path: str, payload: dict[str, object]) -> dict[str, object]:
|
||||
"""
|
||||
Выполняет POST-запрос к API image-host и возвращает JSON-ответ.
|
||||
|
||||
В случае ошибки обёртывает исключение в ImageHostError.
|
||||
"""
|
||||
request = Request(
|
||||
f"{self.api_url}{path}",
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
method="POST",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "BelkiCalculator/1.0 (+https://cat.nyan404.ru/belki)",
|
||||
},
|
||||
)
|
||||
def get_object(self, object_name: str):
|
||||
"""Returns an object response from the first healthy MinIO endpoint."""
|
||||
last_error: Exception | None = None
|
||||
try:
|
||||
with urlopen(request, timeout=self.timeout) as response:
|
||||
result = json.load(response)
|
||||
except Exception as exc:
|
||||
raise ImageHostError(f"image host initiate failed: {exc}") from exc
|
||||
if not isinstance(result, dict):
|
||||
raise ImageHostError("image host returned an invalid response")
|
||||
return result
|
||||
for client in self._clients():
|
||||
try:
|
||||
return client.get_object(self.bucket, object_name)
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
except ImageHostError:
|
||||
raise
|
||||
if last_error is not None:
|
||||
raise ImageHostError(f"image storage read failed: {last_error}") from last_error
|
||||
raise ImageHostError("image storage has no reachable endpoints")
|
||||
|
||||
|
||||
# Kept as an import-compatible name for existing VK integration code.
|
||||
ImageHostClient = ImageStoreClient
|
||||
+30
-2
@@ -5,6 +5,7 @@ import base64
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
@@ -19,7 +20,7 @@ from .belki.applications import ApplicationError, ApplicationStore, validate_app
|
||||
from .belki.admin_filters import WEB_TIMEZONE, matches_period, period_bounds
|
||||
from .belki.google_sheets_export import GoogleSheetsExportService
|
||||
from .belki.identity import IdentityDirectory
|
||||
from .belki.image_host import ImageHostClient, ImageHostError
|
||||
from .belki.image_host import ImageHostError, ImageStoreClient
|
||||
from .belki.xlsx_export import build_xlsx
|
||||
from .sudoku import SudokuError, SudokuStore
|
||||
from .belki.vk_scheduler import VkConversationStore
|
||||
@@ -48,6 +49,7 @@ MAX_ADMIN_AUTH_ATTEMPTS = 5
|
||||
_ADMIN_UPDATE_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_ADMIN_UPDATES)
|
||||
WEB_UPLOAD_URL_TTL_SECONDS = 30 * 60
|
||||
MAX_ISSUED_WEB_UPLOAD_URLS = 1_000
|
||||
IMAGE_OBJECT_NAME = re.compile(r"^[a-f0-9]{32}\.(?:png|jpg|webp)$")
|
||||
ADMIN_SESSION_TTL_SECONDS = 12 * 60 * 60
|
||||
MAX_ADMIN_SESSIONS = 100
|
||||
|
||||
@@ -401,6 +403,32 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path == "/api/admin/updates":
|
||||
self._serve_admin_updates()
|
||||
return
|
||||
if path.startswith("/api/images/"):
|
||||
object_name = path.removeprefix("/api/images/")
|
||||
if not IMAGE_OBJECT_NAME.fullmatch(object_name):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
response = ImageStoreClient().get_object(object_name)
|
||||
except ImageHostError:
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", response.headers.get("Content-Type", mimetypes.guess_type(object_name)[0] or "application/octet-stream"))
|
||||
content_length = response.headers.get("Content-Length")
|
||||
if content_length:
|
||||
self.send_header("Content-Length", content_length)
|
||||
self.send_header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
self.end_headers()
|
||||
while chunk := response.read(64 * 1024):
|
||||
self.wfile.write(chunk)
|
||||
except (BrokenPipeError, ConnectionError, OSError):
|
||||
return
|
||||
finally:
|
||||
response.close()
|
||||
response.release_conn()
|
||||
return
|
||||
if path == "/api/admin/calculations":
|
||||
if not self._admin_authorized():
|
||||
return
|
||||
@@ -548,7 +576,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if declared_type and declared_type != content_type:
|
||||
raise ApiError("Тип файла не совпадает с содержимым изображения")
|
||||
try:
|
||||
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).upload_bytes(
|
||||
url = ImageStoreClient().upload_bytes(
|
||||
body, safe_upload_name(payload.get("name"), content_type), content_type
|
||||
)
|
||||
except ImageHostError as exc:
|
||||
|
||||
Reference in new issue
Block a user