feat: show VK photos in calculation admin
This commit is contained in:
1 parent
6bbd8d4b0b
commit
20b434dbcd
6 files changed
+82
-3
No files matched your search
@@ -37,6 +37,8 @@ python3 -m app.belki.vk_bot
|
||||
|
||||
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
||||
|
||||
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Админская панель показывает их миниатюры и исходные ссылки VK; зеркалирование на `image-hosting-web` и запись в Google Sheets пока не включены.
|
||||
|
||||
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
|
||||
|
||||
## Структура
|
||||
|
||||
+48
-1
@@ -247,6 +247,33 @@ def build_message_request(peer_id: int, message: str, access_token: str, api_ver
|
||||
return request
|
||||
|
||||
|
||||
def extract_photo_attachments(message: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Normalize VK photo attachments for durable calculation history."""
|
||||
result: list[dict[str, Any]] = []
|
||||
for attachment in message.get("attachments", []) or []:
|
||||
if attachment.get("type") != "photo":
|
||||
continue
|
||||
photo = attachment.get("photo") or {}
|
||||
sizes = photo.get("sizes") or []
|
||||
largest = max(sizes, key=lambda item: item.get("width", 0) * item.get("height", 0), default={})
|
||||
owner_id = photo.get("owner_id")
|
||||
photo_id = photo.get("id")
|
||||
if owner_id is None or photo_id is None:
|
||||
continue
|
||||
result.append({
|
||||
"type": "photo",
|
||||
"owner_id": owner_id,
|
||||
"id": photo_id,
|
||||
"access_key": photo.get("access_key"),
|
||||
"url": largest.get("url"),
|
||||
"width": largest.get("width"),
|
||||
"height": largest.get("height"),
|
||||
"attachment": f"photo{owner_id}_{photo_id}"
|
||||
+ (f"_{photo['access_key']}" if photo.get("access_key") else ""),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
class VkApiClient:
|
||||
def __init__(self, access_token: str, api_version: str = "5.199") -> None:
|
||||
self.access_token = access_token
|
||||
@@ -298,8 +325,12 @@ class BelkiBot:
|
||||
peer_id = message.get("peer_id")
|
||||
sender_id = message.get("from_id", message.get("sender_id", peer_id))
|
||||
text = self._button_text(message) or message.get("text", "")
|
||||
if peer_id is not None and text:
|
||||
if peer_id is not None:
|
||||
sender = int(sender_id or peer_id)
|
||||
photos = extract_photo_attachments(message)
|
||||
if photos:
|
||||
self.dialog.queue_attachments(sender, photos)
|
||||
if text:
|
||||
response = self.dialog.handle(int(peer_id), text, user_id=sender)
|
||||
self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(sender))
|
||||
|
||||
@@ -373,12 +404,25 @@ class BelkiDialog:
|
||||
def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False,
|
||||
calculation_store: CalculationStore | None = 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
|
||||
|
||||
def _reset(self, peer_id: int) -> None:
|
||||
self._states.pop(peer_id, None)
|
||||
self._pending_attachments.pop(peer_id, None)
|
||||
|
||||
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
|
||||
if attachments:
|
||||
pending = self._pending_attachments.setdefault(actor_id, [])
|
||||
pending.extend(attachments)
|
||||
del pending[:-10]
|
||||
|
||||
def _attach_pending(self, actor_id: int) -> None:
|
||||
pending = self._pending_attachments.pop(actor_id, [])
|
||||
if pending and actor_id in self._states:
|
||||
self._states[actor_id].setdefault("attachments", []).extend(pending)
|
||||
|
||||
@staticmethod
|
||||
def _button(label: str, payload: str, color: str = "secondary") -> dict[str, Any]:
|
||||
@@ -706,6 +750,8 @@ class BelkiDialog:
|
||||
self._reset(actor_id)
|
||||
return "Текущий ввод отменён. Для нового отчёта используйте /лу, /зу или /help."
|
||||
state = self._states.get(actor_id)
|
||||
if state:
|
||||
self._attach_pending(actor_id)
|
||||
if state and state.get("confirm"):
|
||||
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
||||
payload = {key: value for key, value in state.items() if key not in {"confirm", "escort", "kitten", "character", "independence", "_independence_provided"}}
|
||||
@@ -723,6 +769,7 @@ class BelkiDialog:
|
||||
if not state:
|
||||
response = self._start_bulk(actor_id, text)
|
||||
if response is not None:
|
||||
self._attach_pending(actor_id)
|
||||
return response
|
||||
return "Начните с /лу или /зу. Для списка команд отправьте /help."
|
||||
try:
|
||||
|
||||
@@ -25,6 +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.
|
||||
- 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.
|
||||
- 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.
|
||||
- `/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.
|
||||
- No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped.
|
||||
|
||||
@@ -7,6 +7,7 @@ from app.belki.vk_bot import (
|
||||
build_message_request,
|
||||
parse_text_command,
|
||||
BelkiBot,
|
||||
extract_photo_attachments,
|
||||
)
|
||||
|
||||
|
||||
@@ -48,6 +49,15 @@ class VkBotTests(unittest.TestCase):
|
||||
self.assertIsInstance(payload, dict)
|
||||
self.assertIn("command", payload)
|
||||
|
||||
def test_extract_photo_attachment_keeps_largest_size_and_vk_reference(self):
|
||||
photos = extract_photo_attachments({"attachments": [{"type": "photo", "photo": {
|
||||
"owner_id": -10, "id": 42, "access_key": "secret",
|
||||
"sizes": [{"width": 100, "height": 100, "url": "small"},
|
||||
{"width": 1000, "height": 800, "url": "large"}],
|
||||
}}]})
|
||||
self.assertEqual(photos[0]["url"], "large")
|
||||
self.assertEqual(photos[0]["attachment"], "photo-10_42_secret")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -114,6 +114,15 @@ class VkConversationTests(unittest.TestCase):
|
||||
self.assertIn("вьюнок=-1", confirmation)
|
||||
self.assertIn("паук=3", confirmation)
|
||||
|
||||
def test_queued_photo_is_saved_in_confirmed_state(self):
|
||||
dialog = BelkiDialog()
|
||||
dialog.queue_attachments(107, [{"type": "photo", "url": "https://example.test/photo.jpg"}])
|
||||
dialog.handle(107, "/урок")
|
||||
dialog.handle(107, "Белка [1]")
|
||||
confirmation = dialog.handle(107, "Котёнок [2]")
|
||||
self.assertIn("подтверд", confirmation.lower())
|
||||
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
|
||||
|
||||
def test_natural_inspection_accepts_character_id_without_name(self):
|
||||
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
||||
self.assertEqual(inspected["fields"]["character_id"], 1617140)
|
||||
|
||||
+12
-2
@@ -14,10 +14,11 @@
|
||||
button { cursor: pointer; background: #d59b62; color: #211818; border-color: #d59b62; }
|
||||
.error { color: #ff9f9f; white-space: pre-wrap; }
|
||||
.table-wrap { overflow-x: auto; border: 1px solid #4a383d; border-radius: 10px; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 820px; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 980px; }
|
||||
th, td { text-align: left; vertical-align: top; padding: 10px; border-bottom: 1px solid #4a383d; }
|
||||
th { color: #d59b62; }
|
||||
td pre { white-space: pre-wrap; margin: 0; max-width: 560px; }
|
||||
td img { width: 96px; height: 72px; object-fit: cover; margin: 2px; border-radius: 5px; }
|
||||
.muted { color: #b9aaad; }
|
||||
</style>
|
||||
</head>
|
||||
@@ -32,7 +33,7 @@
|
||||
<button id="load">Загрузить</button>
|
||||
</div>
|
||||
<p class="error" id="error"></p>
|
||||
<div class="table-wrap"><table><thead><tr><th>ID записи</th><th>Автор</th><th>Режим</th><th>Котёнок</th><th>Дата</th><th>Сообщение</th></tr></thead><tbody id="rows"></tbody></table></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>ID записи</th><th>Автор</th><th>Режим</th><th>Котёнок</th><th>Фото</th><th>Дата</th><th>Сообщение</th></tr></thead><tbody id="rows"></tbody></table></div>
|
||||
</main>
|
||||
<script>
|
||||
const password = document.querySelector('#password');
|
||||
@@ -52,6 +53,15 @@
|
||||
const row = document.createElement('tr');
|
||||
row.append(cell(item.id)); row.append(cell(item.actor_id || '—')); row.append(cell(item.mode));
|
||||
row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`));
|
||||
const photos = document.createElement('td');
|
||||
(item.input.attachments || []).forEach(photo => {
|
||||
if (!photo.url) return;
|
||||
const link = document.createElement('a'); link.href = photo.url; link.target = '_blank'; link.rel = 'noopener';
|
||||
const image = document.createElement('img'); image.src = photo.url; image.alt = 'Фото'; image.loading = 'lazy';
|
||||
link.append(image); photos.append(link);
|
||||
});
|
||||
if (!photos.childNodes.length) photos.textContent = '—';
|
||||
row.append(photos);
|
||||
row.append(cell(item.created_at));
|
||||
const message = document.createElement('td'); const pre = document.createElement('pre'); pre.textContent = item.message; message.append(pre); row.append(message);
|
||||
rows.append(row);
|
||||
|
||||
Reference in new issue
Block a user