138 lines
6.3 KiB
Python
138 lines
6.3 KiB
Python
"""Private MinIO-backed storage for report screenshots and VK attachments."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from collections.abc import Iterator
|
||
from io import BytesIO
|
||
import os
|
||
import secrets
|
||
from urllib.request import urlopen
|
||
|
||
from minio import Minio
|
||
|
||
|
||
class ImageHostError(RuntimeError):
|
||
"""Ошибка при работе с image-host."""
|
||
|
||
|
||
MAX_MIRRORED_IMAGE_BYTES = 15 * 1024 * 1024
|
||
|
||
|
||
def detect_raster_image_type(body: bytes) -> str | None:
|
||
"""Return the supported image MIME type from bytes, not an HTTP header."""
|
||
if body.startswith(b"\x89PNG\r\n\x1a\n"):
|
||
return "image/png"
|
||
if body.startswith(b"\xff\xd8\xff"):
|
||
return "image/jpeg"
|
||
if len(body) >= 12 and body.startswith(b"RIFF") and body[8:12] == b"WEBP":
|
||
return "image/webp"
|
||
return None
|
||
|
||
|
||
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.
|
||
|
||
Процесс:
|
||
1. Скачивает фото из VK по URL
|
||
2. Инициализирует загрузку через /api/uploads/initiate
|
||
3. Загружает файл PUT-запросом
|
||
4. Возвращает прямую ссылку
|
||
|
||
Args:
|
||
photo: Словарь с полями из extract_photo_attachments
|
||
|
||
Returns:
|
||
Прямая ссылка на загруженное фото или None
|
||
"""
|
||
if not photo.get("url"):
|
||
return None
|
||
source_url = str(photo["url"])
|
||
with urlopen(source_url, timeout=self.timeout) as response:
|
||
raw_length = response.headers.get("Content-Length")
|
||
try:
|
||
content_length = int(raw_length) if raw_length else None
|
||
except ValueError:
|
||
content_length = None
|
||
if content_length is not None and content_length > MAX_MIRRORED_IMAGE_BYTES:
|
||
raise ImageHostError("VK image is too large to mirror")
|
||
body = response.read(MAX_MIRRORED_IMAGE_BYTES + 1)
|
||
if len(body) > MAX_MIRRORED_IMAGE_BYTES:
|
||
raise ImageHostError("VK image is too large to mirror")
|
||
content_type = detect_raster_image_type(body)
|
||
if content_type is None:
|
||
raise ImageHostError("VK attachment is not a supported raster image")
|
||
suffix = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}[content_type]
|
||
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.{suffix}"
|
||
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:
|
||
"""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:
|
||
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
|
||
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 get_object(self, object_name: str):
|
||
"""Returns an object response from the first healthy MinIO endpoint."""
|
||
last_error: Exception | None = None
|
||
try:
|
||
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
|