64 lines
2.4 KiB
Python
64 lines
2.4 KiB
Python
"""Small client for mirroring VK photos to image-hosting-web."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from urllib.request import Request, urlopen
|
|
|
|
|
|
class ImageHostError(RuntimeError):
|
|
pass
|
|
|
|
|
|
class ImageHostClient:
|
|
def __init__(self, api_url: str | None = None, retention: str = "forever", timeout: int = 30) -> None:
|
|
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:
|
|
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]:
|
|
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
|