140 lines
5.8 KiB
Python
140 lines
5.8 KiB
Python
"""
|
||
Клиент для зеркалирования фотографий из VK на external image-host.
|
||
|
||
Используется для хранения скриншотов-приложений к отчётам.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
from urllib.request import Request, urlopen
|
||
|
||
|
||
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 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
|
||
self.timeout = timeout
|
||
|
||
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 self.api_url or 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:
|
||
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
|
||
if not self.api_url or not body:
|
||
return 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
|
||
except ImageHostError:
|
||
raise
|
||
except Exception as exc:
|
||
raise ImageHostError(f"image host upload failed: {exc}") from exc
|
||
|
||
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)",
|
||
},
|
||
)
|
||
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
|