fix(upload): target image host API

This commit is contained in:
nyan404 committed 2026-08-21 14:26:16 +03:00
1 parent 12e9de9ba4
commit c3358f3f66
7 files changed
+33 -7

No files matched your search

+1
View File
@@ -28,6 +28,7 @@
- 2026-08-21: project-local frontend instructions include `frontend-craft`, `frontend-design`, and `ui-ux-pro-max`; use them together for UI work.
- 2026-08-21: `/belki` is the single public Belki workspace: both reports and its “Заявки” tab are open without a password. The old `/applications` route remains only as a direct legacy entry point. `/admin` is the only password-protected surface.
- 2026-08-21: `/admin` now keeps a server-memory `HttpOnly` cookie session across page refreshes instead of retaining an admin password in the browser. Its authenticated WebSocket sends a refresh signal every 25 seconds; this needs the cwshed Nginx `/api/` Upgrade proxy settings.
- 2026-08-21: `img.nyan404.ru` is only the image-host viewer/frontend; Belki uploads must use the image-host API `https://nyan.nyan404.ru`. Upload failures are converted to actionable API errors rather than a generic calculator 500.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+1 -1
View File
@@ -37,7 +37,7 @@ python3 -m app.belki.vk_bot
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их на image host (в production — `https://img.nyan404.ru`) и сохраняет ссылки вместе с отчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же image host. Google Sheets пока не подключён.
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их через API `https://nyan.nyan404.ru` и сохраняет ссылки вместе с отчётом. Пользовательский интерфейс image-host доступен на `https://img.nyan404.ru`. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же API. Google Sheets пока не подключён.
## Заявки
+5
View File
@@ -61,6 +61,7 @@ class ImageHostClient:
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
if not self.api_url or not body:
return None
try:
initiate = self._request_json(
"/api/uploads/initiate",
{
@@ -81,6 +82,10 @@ class ImageHostClient:
with urlopen(request, timeout=self.timeout):
pass
return str(upload.get("directUrl") or upload.get("cdnUrl") or "") or None
except ImageHostError:
raise
except Exception as exc:
raise ImageHostError(f"image host upload failed: {exc}") from exc
def _request_json(self, path: str, payload: dict[str, object]) -> dict[str, object]:
"""
+5 -2
View File
@@ -16,7 +16,7 @@ from .belki.history import CalculationStore
from .belki.applications import ApplicationError, ApplicationStore, validate_application
from .belki.google_sheets_export import GoogleSheetsExportService
from .belki.identity import IdentityDirectory
from .belki.image_host import ImageHostClient
from .belki.image_host import ImageHostClient, ImageHostError
ROOT = Path(__file__).resolve().parents[1]
@@ -229,9 +229,12 @@ class Handler(BaseHTTPRequestHandler):
raise ApiError("Не удалось прочитать изображение") from exc
if len(body) > 15 * 1024 * 1024:
raise ApiError("Файл слишком большой (максимум 15 МБ)")
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://img.nyan404.ru")).upload_bytes(
try:
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://nyan.nyan404.ru")).upload_bytes(
body, str(payload.get("name", "screenshot.jpg")), str(payload.get("type", "image/jpeg"))
)
except ImageHostError as exc:
raise ApiError(f"Не удалось загрузить изображение: {exc}") from exc
if not url:
raise ApiError("Хранилище изображений не настроено")
self._json(200, {"url": url, "name": payload.get("name", "screenshot.jpg")})
+2 -2
View File
@@ -120,7 +120,7 @@ spec:
name: belki-runtime
key: BELKI_ADMIN_PASSWORD
- name: BELKI_IMAGE_HOST_API_URL
value: https://img.nyan404.ru
value: https://nyan.nyan404.ru
readinessProbe:
httpGet:
path: /health
@@ -199,4 +199,4 @@ spec:
name: belki-runtime
key: BELKI_DATABASE_URL
- name: BELKI_IMAGE_HOST_API_URL
value: https://img.nyan404.ru
value: https://nyan.nyan404.ru
+2 -2
View File
@@ -32,7 +32,7 @@
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. 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 table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- `/admin` exchanges `BELKI_ADMIN_PASSWORD` for a server-memory `HttpOnly`, `SameSite=Lax` session cookie. The page restores that session after a refresh; it does not persist the password in browser storage. Authenticated browsers connect to `/api/admin/updates` over WebSocket and receive a `refresh` event every 25 seconds, which reloads report and application data. The cwshed Nginx `/api/` proxy upgrades WebSocket connections.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. The “Заявки” tab within `/belki` reuses the existing password-gated web session and upload endpoint; `/applications` remains a legacy direct page. `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. The “Заявки” tab within `/belki` and `/applications` are public and use the upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one.
- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`; its context keyboard drives every selectable application branch, while users type only free-form values. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient.
- Google Sheets export is pre-wired but disabled by `BELKI_GOOGLE_EXPORT_ENABLED=0`. `ApplicationStore` records `application_created` and `application_accepted` snapshots in the PostgreSQL `belki_application_export_events` or SQLite `application_export_events` outbox. `GoogleSheetsExportService` sends FIFO JSON events only to an explicitly configured Google Apps Script Web App URL, retains failed events for retry, and is polled by the bot every 15 seconds when enabled.
- The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API.
@@ -54,7 +54,7 @@
- 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case.
- 2026-08-16: adopted `2026-08-16-krylany-calculator-rules.md`: Krylan is the Belka/escort role, kittens always receive 1 point per 5 minutes, non-self-sufficient ЛУ multiplies escort points by 1.5, and ZU forces self-sufficient calculation.
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
- 2026-08-17: web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments.
- 2026-08-17: web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production API `https://nyan.nyan404.ru`, viewer `https://img.nyan404.ru`) and persisted as report attachments.
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
# Обновление 2026-08-16: несколько котят
+17
View File
@@ -0,0 +1,17 @@
import unittest
from unittest.mock import patch
from app.belki.image_host import ImageHostClient, ImageHostError
class ImageHostClientTests(unittest.TestCase):
def test_upload_wraps_presigned_put_failure(self) -> None:
client = ImageHostClient(api_url="https://api.example.test")
with patch.object(client, "_request_json", return_value={"files": [{"uploadUrl": "https://storage.example.test/upload"}]}):
with patch("app.belki.image_host.urlopen", side_effect=OSError("network unavailable")):
with self.assertRaisesRegex(ImageHostError, "image host upload failed"):
client.upload_bytes(b"image", "screenshot.jpg")
if __name__ == "__main__":
unittest.main()