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

99 lines
3.9 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."""
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", "")).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:
body = response.read()
content_type = response.headers.get_content_type() or "image/jpeg"
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
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
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"},
)
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