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
@@ -9,3 +9,5 @@ BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki
|
|||||||
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
||||||
# Required to access /admin and /api/admin/calculations.
|
# Required to access /admin and /api/admin/calculations.
|
||||||
BELKI_ADMIN_PASSWORD=change-me
|
BELKI_ADMIN_PASSWORD=change-me
|
||||||
|
# Optional image-hosting-web API origin, e.g. https://nyan.nyan404.ru.
|
||||||
|
BELKI_IMAGE_HOST_API_URL=
|
||||||
@@ -37,7 +37,7 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
||||||
|
|
||||||
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Админская панель показывает их миниатюры и исходные ссылки VK; зеркалирование на `image-hosting-web` и запись в Google Sheets пока не включены.
|
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот скачивает фото, загружает его через API `image-hosting-web` и сохраняет постоянный `mirror_url`; админская панель показывает зеркальную ссылку. Без настройки API сохраняется исходная ссылка VK. Google Sheets пока не подключён.
|
||||||
|
|
||||||
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
||||||
|
|
||||||
|
|||||||
@@ -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 .api import ApiError, calculate_payload
|
||||||
from .history import CalculationStore
|
from .history import CalculationStore
|
||||||
|
from .image_host import ImageHostClient
|
||||||
from .identity import Identity, IdentityDirectory
|
from .identity import Identity, IdentityDirectory
|
||||||
|
|
||||||
|
|
||||||
@@ -307,6 +308,7 @@ class BelkiBot:
|
|||||||
IdentityDirectory.from_environment(persistent=True),
|
IdentityDirectory.from_environment(persistent=True),
|
||||||
onboarding=True,
|
onboarding=True,
|
||||||
calculation_store=CalculationStore.from_environment(),
|
calculation_store=CalculationStore.from_environment(),
|
||||||
|
attachment_mirror=ImageHostClient().mirror,
|
||||||
)
|
)
|
||||||
|
|
||||||
def response_for_text(self, text: str) -> str:
|
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,
|
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._states: dict[int, dict[str, Any]] = {}
|
||||||
self._pending_attachments: dict[int, list[dict[str, Any]]] = {}
|
self._pending_attachments: dict[int, list[dict[str, Any]]] = {}
|
||||||
self.identity_directory = identity_directory or IdentityDirectory()
|
self.identity_directory = identity_directory or IdentityDirectory()
|
||||||
self.onboarding = onboarding
|
self.onboarding = onboarding
|
||||||
self.calculation_store = calculation_store
|
self.calculation_store = calculation_store
|
||||||
|
self.attachment_mirror = attachment_mirror
|
||||||
|
|
||||||
def _reset(self, peer_id: int) -> None:
|
def _reset(self, peer_id: int) -> None:
|
||||||
self._states.pop(peer_id, None)
|
self._states.pop(peer_id, None)
|
||||||
@@ -754,6 +757,14 @@ class BelkiDialog:
|
|||||||
self._attach_pending(actor_id)
|
self._attach_pending(actor_id)
|
||||||
if state and state.get("confirm"):
|
if state and state.get("confirm"):
|
||||||
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
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"}}
|
payload = {key: value for key, value in state.items() if key not in {"confirm", "escort", "kitten", "character", "independence", "_independence_provided"}}
|
||||||
response = calculate_payload(payload)
|
response = calculate_payload(payload)
|
||||||
if self.calculation_store:
|
if self.calculation_store:
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
- Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git.
|
- Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git.
|
||||||
- The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts.
|
- The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts.
|
||||||
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
|
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
|
||||||
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; `/admin` renders their thumbnails. The current phase keeps VK URLs/attachment references; image-host mirroring and Google Sheets export remain deferred.
|
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; `/admin` renders their thumbnails. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
|
||||||
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports sorting by kitten ID or name and does not persist the password in browser storage.
|
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports sorting by kitten ID or name and does not persist the password in browser storage.
|
||||||
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
|
||||||
- No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped.
|
- No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped.
|
||||||
|
|||||||
@@ -123,6 +123,21 @@ class VkConversationTests(unittest.TestCase):
|
|||||||
self.assertIn("подтверд", confirmation.lower())
|
self.assertIn("подтверд", confirmation.lower())
|
||||||
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
|
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
|
||||||
|
|
||||||
|
def test_photo_is_mirrored_before_history_save(self):
|
||||||
|
mirrored = []
|
||||||
|
|
||||||
|
def mirror(photo):
|
||||||
|
mirrored.append(photo["url"])
|
||||||
|
return "https://img.nyan404.ru/photo/abc.jpg"
|
||||||
|
|
||||||
|
dialog = BelkiDialog(attachment_mirror=mirror)
|
||||||
|
dialog.queue_attachments(108, [{"type": "photo", "url": "https://vk.example/photo.jpg"}])
|
||||||
|
dialog.handle(108, "/урок")
|
||||||
|
dialog.handle(108, "Белка [1]")
|
||||||
|
dialog.handle(108, "Котёнок [2]")
|
||||||
|
dialog.handle(108, "да")
|
||||||
|
self.assertEqual(mirrored, ["https://vk.example/photo.jpg"])
|
||||||
|
|
||||||
def test_natural_inspection_accepts_character_id_without_name(self):
|
def test_natural_inspection_accepts_character_id_without_name(self):
|
||||||
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
||||||
self.assertEqual(inspected["fields"]["character_id"], 1617140)
|
self.assertEqual(inspected["fields"]["character_id"], 1617140)
|
||||||
|
|||||||
+4
-3
@@ -55,9 +55,10 @@
|
|||||||
row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`));
|
row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`));
|
||||||
const photos = document.createElement('td');
|
const photos = document.createElement('td');
|
||||||
(item.input.attachments || []).forEach(photo => {
|
(item.input.attachments || []).forEach(photo => {
|
||||||
if (!photo.url) return;
|
const photoUrl = photo.mirror_url || photo.url;
|
||||||
const link = document.createElement('a'); link.href = photo.url; link.target = '_blank'; link.rel = 'noopener';
|
if (!photoUrl) return;
|
||||||
const image = document.createElement('img'); image.src = photo.url; image.alt = 'Фото'; image.loading = 'lazy';
|
const link = document.createElement('a'); link.href = photoUrl; link.target = '_blank'; link.rel = 'noopener';
|
||||||
|
const image = document.createElement('img'); image.src = photoUrl; image.alt = 'Фото'; image.loading = 'lazy';
|
||||||
link.append(image); photos.append(link);
|
link.append(image); photos.append(link);
|
||||||
});
|
});
|
||||||
if (!photos.childNodes.length) photos.textContent = '—';
|
if (!photos.childNodes.length) photos.textContent = '—';
|
||||||
|
|||||||
Reference in new issue
Block a user