feat: mirror VK photos to image host
This commit is contained in:
1 parent
20b434dbcd
commit
f6c2275af3
7 files changed
+98
-6
No files matched your search
@@ -0,0 +1,63 @@
|
||||
"""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
|
||||
+12
-1
@@ -11,6 +11,7 @@ from urllib.request import Request, urlopen
|
||||
|
||||
from .api import ApiError, calculate_payload
|
||||
from .history import CalculationStore
|
||||
from .image_host import ImageHostClient
|
||||
from .identity import Identity, IdentityDirectory
|
||||
|
||||
|
||||
@@ -307,6 +308,7 @@ class BelkiBot:
|
||||
IdentityDirectory.from_environment(persistent=True),
|
||||
onboarding=True,
|
||||
calculation_store=CalculationStore.from_environment(),
|
||||
attachment_mirror=ImageHostClient().mirror,
|
||||
)
|
||||
|
||||
def response_for_text(self, text: str) -> str:
|
||||
@@ -402,12 +404,13 @@ class BelkiDialog:
|
||||
}
|
||||
|
||||
def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False,
|
||||
calculation_store: CalculationStore | None = None) -> None:
|
||||
calculation_store: CalculationStore | None = None, attachment_mirror=None) -> None:
|
||||
self._states: dict[int, dict[str, Any]] = {}
|
||||
self._pending_attachments: dict[int, list[dict[str, Any]]] = {}
|
||||
self.identity_directory = identity_directory or IdentityDirectory()
|
||||
self.onboarding = onboarding
|
||||
self.calculation_store = calculation_store
|
||||
self.attachment_mirror = attachment_mirror
|
||||
|
||||
def _reset(self, peer_id: int) -> None:
|
||||
self._states.pop(peer_id, None)
|
||||
@@ -754,6 +757,14 @@ class BelkiDialog:
|
||||
self._attach_pending(actor_id)
|
||||
if state and state.get("confirm"):
|
||||
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
||||
if self.attachment_mirror:
|
||||
for photo in state.get("attachments", []):
|
||||
try:
|
||||
mirror_url = self.attachment_mirror(photo)
|
||||
except Exception:
|
||||
mirror_url = None
|
||||
if mirror_url:
|
||||
photo["mirror_url"] = mirror_url
|
||||
payload = {key: value for key, value in state.items() if key not in {"confirm", "escort", "kitten", "character", "independence", "_independence_provided"}}
|
||||
response = calculate_payload(payload)
|
||||
if self.calculation_store:
|
||||
|
||||
Reference in new issue
Block a user