feat: serve Belki images through private MinIO

This commit is contained in:
nyan404 committed 2026-09-08 23:27:24 +03:00
1 parent b45e4925a6
commit ecc1f696da
14 files changed
+196 -121

No files matched your search

+68 -70
View File
@@ -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