Files
cwshed-clone/app/belki/image_host.py
T

126 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Клиент для зеркалирования фотографий из 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
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 = response.headers.get_content_type() or "image/jpeg"
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
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