too many changes
This commit is contained in:
@@ -68,3 +68,8 @@ coverage/
|
||||
|
||||
## Publish output
|
||||
publish/
|
||||
|
||||
## Frontend (miniapp)
|
||||
miniapp/node_modules/
|
||||
miniapp/dist/
|
||||
miniapp/.svelte-kit/
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
# CLAUDE.md — MemeVault
|
||||
|
||||
Этот файл — инструкция для Claude Code. Читать перед любой работой с проектом.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Обязательные правила
|
||||
|
||||
### 1. Копировать изменения на компьютер пользователя
|
||||
**Любой изменённый или созданный файл** нужно скопировать в шаренную папку `TelegramFavVaultBot` на Mac пользователя — сразу, не дожидаясь просьбы. Путь монтирования: `$HOME/mnt/TelegramFavVaultBot/`.
|
||||
|
||||
Алгоритм:
|
||||
1. Сначала правим файл в облачном контейнере (`/home/claude/project/...`).
|
||||
2. Затем применяем то же изменение на Mac через `device_bash` — `sed -i` для точечных правок, `cp` для новых файлов.
|
||||
3. Сверяем результат `grep` / `cat` чтобы убедиться, что всё совпадает.
|
||||
|
||||
Если папка не смонтирована — сообщить пользователю, но не пропускать шаг.
|
||||
|
||||
### 2. Не переименовывать поля DTO без явного запроса
|
||||
Имена свойств DTO — часть публичного контракта API. Их переименование ломает фронтенд и тесты.
|
||||
|
||||
**Запрещено:**
|
||||
- Переименовывать существующее поле DTO «для красоты» или чтобы имя совпало с именем JSON-ключа.
|
||||
- Менять регистр / стиль (`Type` → `MediaType`, `FileId` → `FileReference` и т.п.) по своей инициативе.
|
||||
|
||||
**Разрешено** только если пользователь явно попросил переименовать конкретное поле.
|
||||
|
||||
Если название поля кажется неудачным — предложить переименование отдельным сообщением, но не делать это молча в рамках другой задачи.
|
||||
|
||||
### 3. Миграции EF Core — только вручную
|
||||
**Никогда не генерировать миграции самостоятельно.** Попросить пользователя выполнить:
|
||||
```bash
|
||||
dotnet ef migrations add <Название> \
|
||||
--project src/MemeVault.Infrastructure \
|
||||
--startup-project src/MemeVault.Migrator
|
||||
```
|
||||
Причина: пользователь самостоятельно управляет снапшотом модели и временно́й меткой миграции.
|
||||
|
||||
---
|
||||
|
||||
## Проект: MemeVault
|
||||
|
||||
Telegram-бот + REST API для сохранения медиа (фото, видео, стикеры, GIF, текст) с управлением через Telegram Mini App (Svelte).
|
||||
|
||||
**Стек:** .NET 10, ASP.NET Core, EF Core 10, PostgreSQL 17, Redis 7, Telegram.Bot 22, MediatR 12, prometheus-net, Svelte 5 + Vite 6, nginx.
|
||||
|
||||
---
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
MemeVault.Domain — агрегаты, value objects, интерфейсы репозиториев
|
||||
MemeVault.Application — CQRS команды и запросы (MediatR), интерфейсы сервисов
|
||||
MemeVault.Infrastructure — EF Core, PostgreSQL, Redis, реализации репозиториев
|
||||
MemeVault.Api — REST API + JWT-авторизация через Telegram initData (порт 8080)
|
||||
MemeVault.Bot — Telegram-бот, polling/webhook (порт 8081)
|
||||
MemeVault.Migrator — одноразовый runner миграций EF Core
|
||||
MemeVault.Tests.Unit — xUnit-тесты (Domain + Handlers)
|
||||
miniapp/ — Svelte 5 + Vite 6 Mini App → собирается в nginx-контейнер (порт 3000)
|
||||
```
|
||||
|
||||
Зависимости слоёв: Domain ← Application ← Infrastructure / Api / Bot. Application не зависит от инфраструктуры напрямую.
|
||||
|
||||
---
|
||||
|
||||
## Domain
|
||||
|
||||
### Агрегаты
|
||||
|
||||
| Агрегат | Файл | Назначение |
|
||||
|---------|------|-----------|
|
||||
| `BotUser` | `Aggregates/BotUser/BotUser.cs` | Telegram-пользователь; TelegramId, Username, FirstName, timestamps |
|
||||
| `Collection` | `Aggregates/Collection/Collection.cs` | Именованная коллекция медиа; ACL через `CollectionMember`; флаг Inbox, видимость |
|
||||
| `CollectionMember` | `Aggregates/Collection/CollectionMember.cs` | Owned entity: TelegramId → `CollectionRole` (Viewer/Manager/Owner) |
|
||||
| `CollectionInvite` | `Aggregates/CollectionInvite/CollectionInvite.cs` | Invite-ссылка; URL-safe токен для deep link `t.me/Bot?start=inv_TOKEN`; поддерживает Revoke |
|
||||
| `MediaItem` | `Aggregates/MediaItem/MediaItem.cs` | Медиа-элемент: Source (Telegram/S3), MediaType, Caption, теги |
|
||||
|
||||
### Enums
|
||||
|
||||
- `CollectionRole`: `Viewer(0)`, `Manager(1)`, `Owner(2)`
|
||||
- `CollectionVisibility`: `Private(0)`, `LinkOnly(1)`, `Public(2)`
|
||||
- `MediaType`: `Photo`, `Video`, `Sticker`, `Animation`, `Text`
|
||||
|
||||
### Value Objects
|
||||
|
||||
- `Tag` — строка ≤ 50 символов, нормализация: trim + lowercase
|
||||
- `MediaSource` — Telegram file_id или S3-ключ + discriminator `MediaOrigin`
|
||||
- `TagSearchQuery` — парсит `#тег -#исключён слово` в три списка
|
||||
- `TelegramFileId` — тонкая обёртка над file_id
|
||||
|
||||
---
|
||||
|
||||
## Application (CQRS)
|
||||
|
||||
### Команды
|
||||
|
||||
| Команда | Описание |
|
||||
|---------|---------|
|
||||
| `SaveMedia` | Сохраняет MediaItem в Inbox (или указанную коллекцию) |
|
||||
| `UpdateMedia` | Обновляет Caption, теги, переносит в другую коллекцию |
|
||||
| `DeleteMedia` | Удаляет MediaItem (проверка владельца) |
|
||||
| `CopyMediaToCollection` | Копирует медиа в другую коллекцию |
|
||||
| `CreateCollection` | Создаёт коллекцию; создатель получает роль Owner |
|
||||
| `UpdateCollection` | Переименовывает / меняет описание (не Inbox, только Owner) |
|
||||
| `DeleteCollection` | Удаляет коллекцию и все медиа (не Inbox, только Owner) |
|
||||
| `ShareCollection` | Генерирует / обновляет share-токен коллекции |
|
||||
| `ManageCollectionItem` | Добавляет / удаляет MediaItem из коллекции |
|
||||
| `ManageCollectionMember` | Добавляет / изменяет / удаляет участника коллекции |
|
||||
| `EnsureUser` | Upsert BotUser; вызывается при каждом входящем сообщении |
|
||||
| `CreateCollectionInvite` | Создаёт invite-ссылку для роли Viewer или Manager |
|
||||
| `RevokeCollectionInvite` | Отзывает invite-ссылку |
|
||||
| `AcceptCollectionInvite` | Принимает токен; добавляет пользователя в коллекцию |
|
||||
|
||||
### Запросы
|
||||
|
||||
| Запрос | Описание |
|
||||
|--------|---------|
|
||||
| `GetUserMedia` | Все MediaItem пользователя, упорядочены по дате |
|
||||
| `SearchMedia` | Поиск по тегам и тексту (#тег-синтаксис) |
|
||||
| `GetUserCollections` | Список коллекций, в которых пользователь — участник |
|
||||
| `GetCollectionItems` | MediaItem конкретной коллекции (проверка участия) |
|
||||
| `GetCollectionInvites` | Активные (не отозванные) invite-ссылки коллекции |
|
||||
|
||||
### Интерфейсы-заглушки (не реализованы)
|
||||
|
||||
- `IFileStorage` — S3/MinIO: `UploadAsync`, `GetDownloadUrlAsync`, `DeleteAsync`. Реализации нет, прямые загрузки из Mini App не работают.
|
||||
|
||||
---
|
||||
|
||||
## Infrastructure
|
||||
|
||||
- **EF Core 10 + PostgreSQL 17.** Теги хранятся как `text[]`; поиск через `@>` (containment) и `&&` (exclusion) в `FromSqlRaw`.
|
||||
- **Redis.** Буферизация медиа-альбомов в боте: 2-секундный TTL-окно по `media_group_id`.
|
||||
- **Миграции (две):**
|
||||
1. `Initial` — `bot_users`, `collections`, `collection_members`, `media_items`
|
||||
2. `AddCollectionInvites` — `collection_invites`; убирает `owner_telegram_id` из `collections`; добавляет `is_inbox`
|
||||
|
||||
---
|
||||
|
||||
## API (`MemeVault.Api`, порт 8080)
|
||||
|
||||
**Авторизация:** `POST /api/auth/telegram` (initData → JWT). Все остальные эндпоинты требуют `Authorization: Bearer <jwt>`.
|
||||
|
||||
JWT: HS256, `sub` = Telegram userId, 24 часа. `ValidateIssuer = false`, `ValidateAudience = false` (внутренний сервис, `aud`/`iss` не проверяются).
|
||||
|
||||
**Ключевые файлы:**
|
||||
|
||||
- `Auth/TelegramInitDataValidator.cs` — HMAC-SHA256 валидация initData, окно 60 сек
|
||||
- `Auth/JwtTokenService.cs` — выдача JWT
|
||||
- `Auth/CurrentUser.cs` — scoped: TelegramId + Username из JWT-клеймов
|
||||
- `Middleware/DomainExceptionHandler.cs` — `DomainException` → HTTP 400 Problem Details
|
||||
|
||||
**Отладка без Telegram** (dev-режим): открыть Mini App с хешем `#token=eyJ...`. В `App.svelte` при `import.meta.env.DEV` токен читается из `window.location.hash`. В продакшн-сборке этот код вырезается Vite. Токен генерировать на jwt.io: `{"alg":"HS256"}`, `{"sub":"<telegram_id>"}`, подписать `JWT_SECRET_KEY`.
|
||||
|
||||
---
|
||||
|
||||
## Bot (`MemeVault.Bot`, порт 8081)
|
||||
|
||||
- **Режим:** `TELEGRAM_MODE=Polling` (по умолчанию) или `Webhook`
|
||||
- **MessageHandler** — обрабатывает медиа, команды `/start`, `/help`; deep link `/start inv_TOKEN` передаётся в `AcceptCollectionInviteCommand`
|
||||
- **InlineQueryHandler** — `@bot #тег -#исключён текст`; возвращает до 50 результатов
|
||||
- **Альбомы:** буферизуются в Redis 2 сек по `media_group_id`
|
||||
- **Метрики Prometheus:** `memevault_bot_updates_received_total`, `_processed_total`, `_errors_total`, `_duration_seconds` — по label `update_type`
|
||||
|
||||
---
|
||||
|
||||
## Mini App (`miniapp/`)
|
||||
|
||||
Svelte 5 + Vite 6, CSR-only (без SSR). Собирается в Docker-образ на основе nginx:1.27.
|
||||
|
||||
- `src/lib/telegram.js` — обёртка над `window.Telegram.WebApp`; `initData`, `applyTheme()`
|
||||
- `src/lib/api.js` — fetch-обёртка; читает JWT из store; все методы REST API
|
||||
- `src/stores/auth.js` — `jwt` (writable), `isAuthed` (derived)
|
||||
- `nginx.conf` — `/api/` проксируется на `api:8080`; SPA fallback `try_files`
|
||||
|
||||
---
|
||||
|
||||
## Docker Compose
|
||||
|
||||
| Сервис | Образ / Build | Порт | Роль |
|
||||
|--------|--------------|------|------|
|
||||
| `postgres` | postgres:17-alpine | — | БД |
|
||||
| `redis` | redis:7-alpine | — | Кэш |
|
||||
| `migrator` | ./Dockerfile | — | Одноразовый runner миграций |
|
||||
| `api` | ./Dockerfile | 8080 | REST API |
|
||||
| `bot` | ./Dockerfile | — | Telegram-бот |
|
||||
| `miniapp` | ./miniapp/Dockerfile | 3000 | Svelte SPA + nginx |
|
||||
| `prometheus` | prom/prometheus:v3.3.1 | 9090 | Метрики |
|
||||
|
||||
**Обязательные переменные:** `POSTGRES_PASSWORD`, `TELEGRAM_BOT_TOKEN`, `JWT_SECRET_KEY` (≥ 32 символа).
|
||||
|
||||
---
|
||||
|
||||
## Тесты (`MemeVault.Tests.Unit`)
|
||||
|
||||
xUnit. Покрывают: `CollectionInvite`, `MediaItem`, `Tag`, `BotUser` (домен); все command/query handlers через моки репозиториев.
|
||||
|
||||
Запуск:
|
||||
```bash
|
||||
dotnet test src/MemeVault.Tests.Unit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Что не реализовано (backlog)
|
||||
|
||||
- `IFileStorage` (S3/MinIO) — загрузка файлов из Mini App
|
||||
- Bot username через `GetMe()` — для динамического формирования invite-ссылок в UI
|
||||
- UI: редактирование подписи/тегов в MediaPage
|
||||
- UI: управление приглашениями в CollectionsPage
|
||||
- UI: просмотр элементов коллекции (переход внутрь коллекции)
|
||||
@@ -19,6 +19,40 @@ services:
|
||||
interval: 5s
|
||||
retries: 5
|
||||
|
||||
minio:
|
||||
image: pgsty/silo:latest
|
||||
command: server /data --console-address ":9001"
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ACCESS_KEY:-memevault}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_SECRET_KEY:?err}
|
||||
# Rewrite presigned URLs to this public base URL so browsers can reach them.
|
||||
MINIO_SERVER_URL: ${MINIO_PUBLIC_URL:-http://localhost:9000}
|
||||
volumes:
|
||||
- minio-data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
retries: 10
|
||||
|
||||
minio-init:
|
||||
image: pgsty/silo:latest
|
||||
depends_on:
|
||||
minio:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY:-memevault}
|
||||
MINIO_SECRET_KEY: ${MINIO_SECRET_KEY:?err}
|
||||
entrypoint: >
|
||||
/bin/sh -c "
|
||||
mc alias set local http://minio:9000 $$MINIO_ACCESS_KEY $$MINIO_SECRET_KEY &&
|
||||
mc mb --ignore-existing local/memevault &&
|
||||
echo 'Bucket ready.'
|
||||
"
|
||||
restart: "no"
|
||||
|
||||
migrator:
|
||||
build: .
|
||||
command: ["dotnet", "/app/migrator/MemeVault.Migrator.dll"]
|
||||
@@ -38,6 +72,10 @@ services:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
minio:
|
||||
condition: service_healthy
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
migrator:
|
||||
condition: service_completed_successfully
|
||||
environment:
|
||||
@@ -45,8 +83,13 @@ services:
|
||||
ConnectionStrings__Postgres: Host=postgres;Database=memevault;Username=memevault;Password=${POSTGRES_PASSWORD}
|
||||
ConnectionStrings__Redis: redis:6379
|
||||
Telegram__BotToken: ${TELEGRAM_BOT_TOKEN:?err}
|
||||
Telegram__ApiBaseUrl: ${TELEGRAM_API_BASE_URL:-https://api.telegram.org}
|
||||
Jwt__SecretKey: ${JWT_SECRET_KEY:?err}
|
||||
Jwt__ExpiryHours: 24
|
||||
S3__ServiceUrl: ${MINIO_PUBLIC_URL:-http://localhost:9000}
|
||||
S3__AccessKey: ${MINIO_ACCESS_KEY:-memevault}
|
||||
S3__SecretKey: ${MINIO_SECRET_KEY:?err}
|
||||
S3__BucketName: memevault
|
||||
|
||||
bot:
|
||||
build: .
|
||||
@@ -62,6 +105,8 @@ services:
|
||||
ASPNETCORE_URLS: http://+:8081
|
||||
ConnectionStrings__Postgres: Host=postgres;Database=memevault;Username=memevault;Password=${POSTGRES_PASSWORD}
|
||||
ConnectionStrings__Redis: redis:6379
|
||||
Telegram__BotToken: ${TELEGRAM_BOT_TOKEN:?err}
|
||||
Telegram__ApiBaseUrl: ${TELEGRAM_API_BASE_URL:-https://api.telegram.org}
|
||||
Bot__Token: ${TELEGRAM_BOT_TOKEN:?err}
|
||||
Bot__Mode: ${TELEGRAM_MODE:-Polling}
|
||||
# Bot__WebhookHost: https://your-domain.com # только для Webhook-режима
|
||||
@@ -77,6 +122,14 @@ services:
|
||||
- "--config.file=/etc/prometheus/prometheus.yml"
|
||||
- "--storage.tsdb.retention.time=7d"
|
||||
|
||||
miniapp:
|
||||
build: ./miniapp
|
||||
ports:
|
||||
- "3000:80"
|
||||
depends_on:
|
||||
- api
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
minio-data:
|
||||
prometheus-data:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
@@ -0,0 +1,18 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
# ── Build ─────────────────────────────────────────────────────────────────────
|
||||
FROM node:22-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN --mount=type=cache,target=/root/.npm \
|
||||
npm ci
|
||||
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# ── Runtime ───────────────────────────────────────────────────────────────────
|
||||
FROM nginx:1.27-alpine AS runtime
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>MemeVault</title>
|
||||
<!-- Telegram Mini App SDK -->
|
||||
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,25 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Проксируем /api/ на бэкенд — Mini App не делает cross-origin запросы
|
||||
location /api/ {
|
||||
proxy_pass http://api:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA: любой неизвестный путь отдаём index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
|
||||
gzip_min_length 1024;
|
||||
}
|
||||
Generated
+1419
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "memevault-miniapp",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-svelte": "^1.0.1",
|
||||
"svelte": "^5.57.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"vite": "^6.3.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { jwt, isAuthed } from './stores/auth.js'
|
||||
import { api } from './lib/api.js'
|
||||
import { initData, applyTheme } from './lib/telegram.js'
|
||||
import MediaPage from './pages/MediaPage.svelte'
|
||||
import CollectionsPage from './pages/CollectionsPage.svelte'
|
||||
|
||||
let tab = 'media' // 'media' | 'collections'
|
||||
let authError = null
|
||||
let authing = true
|
||||
|
||||
function devTokenFromHash() {
|
||||
if (!import.meta.env.DEV) return null
|
||||
const params = new URLSearchParams(window.location.hash.slice(1))
|
||||
return params.get('token') ?? null
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
applyTheme()
|
||||
|
||||
// Dev-режим: #token=<jwt> в URL — пропускаем обмен initData
|
||||
const devToken = devTokenFromHash()
|
||||
if (devToken) {
|
||||
jwt.set(devToken)
|
||||
authing = false
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const { token } = await api.auth(initData)
|
||||
jwt.set(token)
|
||||
} catch (e) {
|
||||
authError = e.message
|
||||
} finally {
|
||||
authing = false
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<main>
|
||||
{#if authing}
|
||||
<div class="splash">Загрузка…</div>
|
||||
{:else if authError}
|
||||
<div class="splash error">Ошибка авторизации:<br/>{authError}</div>
|
||||
{:else if $isAuthed}
|
||||
<nav>
|
||||
<button class:active={tab === 'media'} on:click={() => (tab = 'media')}>Медиа</button>
|
||||
<button class:active={tab === 'collections'} on:click={() => (tab = 'collections')}>Коллекции</button>
|
||||
</nav>
|
||||
|
||||
{#if tab === 'media'}
|
||||
<MediaPage />
|
||||
{:else}
|
||||
<CollectionsPage />
|
||||
{/if}
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
:global(*) { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
:global(body) {
|
||||
background: var(--tg-bg, #fff);
|
||||
color: var(--tg-text, #000);
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
main { display: flex; flex-direction: column; height: 100vh; }
|
||||
|
||||
.splash {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
height: 100vh; color: var(--tg-hint, #888); font-size: 16px; text-align: center; padding: 24px;
|
||||
}
|
||||
.error { color: #e53935; }
|
||||
|
||||
nav {
|
||||
display: flex; border-bottom: 1px solid var(--tg-hint, #ccc);
|
||||
background: var(--tg-bg, #fff); position: sticky; top: 0; z-index: 10;
|
||||
}
|
||||
nav button {
|
||||
flex: 1; padding: 12px; border: none; background: none;
|
||||
color: var(--tg-hint, #888); font-size: 15px; cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
nav button.active {
|
||||
color: var(--tg-button, #2196f3);
|
||||
border-bottom-color: var(--tg-button, #2196f3);
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,49 @@
|
||||
import { get } from 'svelte/store'
|
||||
import { jwt } from '../stores/auth.js'
|
||||
|
||||
const BASE = '/api'
|
||||
|
||||
async function request(method, path, body) {
|
||||
const token = get(jwt)
|
||||
const headers = { 'Content-Type': 'application/json' }
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`
|
||||
|
||||
const res = await fetch(BASE + path, {
|
||||
method,
|
||||
headers,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
throw new Error(`${res.status}: ${text}`)
|
||||
}
|
||||
|
||||
const ct = res.headers.get('content-type') ?? ''
|
||||
return ct.includes('application/json') ? res.json() : null
|
||||
}
|
||||
|
||||
export const api = {
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
|
||||
// ── Media ─────────────────────────────────────────────────────────────────
|
||||
getMedia: (q) => request('GET', `/media${q ? `?q=${encodeURIComponent(q)}` : ''}`),
|
||||
getDownloadUrl: (id) => request('GET', `/media/${id}/download-url`).then((r) => r?.url),
|
||||
sendToChat: (id, queryId) => request('POST', `/media/${id}/send`, { queryId }),
|
||||
updateMedia: (id, patch) => request('PATCH', `/media/${id}`, patch),
|
||||
deleteMedia: (id) => request('DELETE', `/media/${id}`),
|
||||
|
||||
// ── Collections ───────────────────────────────────────────────────────────
|
||||
getCollections: () => request('GET', '/collections'),
|
||||
createCollection: (name, description) => request('POST', '/collections', { name, description }),
|
||||
updateCollection: (id, name, description) => request('PATCH', `/collections/${id}`, { name, description }),
|
||||
deleteCollection: (id) => request('DELETE', `/collections/${id}`),
|
||||
setCollectionInbox: (id) => request('PUT', `/collections/${id}/inbox`),
|
||||
getCollectionItems: (id) => request('GET', `/collections/${id}/items`),
|
||||
|
||||
// ── Invites ───────────────────────────────────────────────────────────────
|
||||
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
||||
createInvite: (collectionId, role) => request('POST', `/collections/${collectionId}/invites`, { role }),
|
||||
revokeInvite: (collectionId, inviteId) => request('DELETE', `/collections/${collectionId}/invites/${inviteId}`),
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** Обёртка над Telegram WebApp SDK */
|
||||
const tg = window.Telegram?.WebApp
|
||||
|
||||
export const webApp = tg
|
||||
|
||||
/** initData для обмена на JWT */
|
||||
export const initData = tg?.initData ?? ''
|
||||
|
||||
/** Закрыть Mini App */
|
||||
export const close = () => tg?.close()
|
||||
|
||||
/**
|
||||
* query_id присутствует когда Mini App открыта из меню «Приложить».
|
||||
* Используется для answerWebAppQuery: позволяет отправить контент в чат одним тапом.
|
||||
*/
|
||||
export const getQueryId = () => tg?.initDataUnsafe?.query_id ?? null
|
||||
export const isAttachmentMode = () => !!getQueryId()
|
||||
|
||||
/** Показать нативный алерт Telegram, или fallback на browser alert вне TG-контекста */
|
||||
export const showAlert = (msg) => {
|
||||
if (tg?.showAlert) tg.showAlert(msg)
|
||||
else alert(msg)
|
||||
}
|
||||
|
||||
/** Применить тему Telegram к CSS-переменным */
|
||||
export function applyTheme() {
|
||||
if (!tg) return
|
||||
tg.expand()
|
||||
tg.ready()
|
||||
const colors = tg.themeParams
|
||||
const root = document.documentElement.style
|
||||
if (colors.bg_color) root.setProperty('--tg-bg', colors.bg_color)
|
||||
if (colors.text_color) root.setProperty('--tg-text', colors.text_color)
|
||||
if (colors.hint_color) root.setProperty('--tg-hint', colors.hint_color)
|
||||
if (colors.link_color) root.setProperty('--tg-link', colors.link_color)
|
||||
if (colors.button_color) root.setProperty('--tg-button', colors.button_color)
|
||||
if (colors.button_text_color) root.setProperty('--tg-btn-text', colors.button_text_color)
|
||||
if (colors.secondary_bg_color) root.setProperty('--tg-secondary-bg', colors.secondary_bg_color)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { mount } from 'svelte'
|
||||
import App from './App.svelte'
|
||||
|
||||
mount(App, { target: document.getElementById('app') })
|
||||
@@ -0,0 +1,280 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { Pencil, Trash2, Star, Check, X } from 'lucide-svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { showAlert } from '../lib/telegram.js'
|
||||
|
||||
let collections = $state([])
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
let creating = $state(false)
|
||||
let newName = $state('')
|
||||
|
||||
// Inline-редактирование: { id, value }
|
||||
let editing = $state(null)
|
||||
|
||||
// Подтверждение удаления: id коллекции, которую хотим удалить
|
||||
let confirmDelete = $state(null)
|
||||
|
||||
// Подтверждение смены Inbox: id целевой коллекции
|
||||
let confirmInbox = $state(null)
|
||||
|
||||
$derived: var deleteTarget = collections.find(c => c.id === confirmDelete)
|
||||
$derived: var inboxTarget = collections.find(c => c.id === confirmInbox)
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null
|
||||
try { collections = await api.getCollections() }
|
||||
catch (e) { error = e.message }
|
||||
finally { loading = false }
|
||||
}
|
||||
|
||||
async function createCollection() {
|
||||
if (!newName.trim()) return
|
||||
creating = true
|
||||
try {
|
||||
await api.createCollection(newName.trim(), null)
|
||||
newName = ''
|
||||
await load()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally { creating = false }
|
||||
}
|
||||
|
||||
// ── Редактирование ─────────────────────────────────────────────────────────
|
||||
function startEdit(col) {
|
||||
editing = { id: col.id, value: col.name }
|
||||
}
|
||||
|
||||
async function commitEdit() {
|
||||
if (!editing || !editing.value.trim()) { editing = null; return }
|
||||
try {
|
||||
await api.updateCollection(editing.id, editing.value.trim(), null)
|
||||
const idx = collections.findIndex(c => c.id === editing.id)
|
||||
if (idx !== -1) collections[idx] = { ...collections[idx], name: editing.value.trim() }
|
||||
editing = null
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function cancelEdit() { editing = null }
|
||||
|
||||
// ── Удаление ───────────────────────────────────────────────────────────────
|
||||
async function commitDelete() {
|
||||
if (!confirmDelete) return
|
||||
try {
|
||||
await api.deleteCollection(confirmDelete)
|
||||
collections = collections.filter(c => c.id !== confirmDelete)
|
||||
confirmDelete = null
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
confirmDelete = null
|
||||
}
|
||||
}
|
||||
|
||||
// ── Смена Inbox ────────────────────────────────────────────────────────────
|
||||
async function commitSetInbox() {
|
||||
if (!confirmInbox) return
|
||||
try {
|
||||
await api.setCollectionInbox(confirmInbox)
|
||||
collections = collections.map(c => ({
|
||||
...c,
|
||||
isInbox: c.id === confirmInbox,
|
||||
}))
|
||||
confirmInbox = null
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
confirmInbox = null
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
<!-- Форма создания -->
|
||||
<div class="new-row">
|
||||
<input
|
||||
class="new-input"
|
||||
placeholder="Новая коллекция…"
|
||||
bind:value={newName}
|
||||
onkeydown={(e) => e.key === 'Enter' && createCollection()}
|
||||
disabled={creating}
|
||||
/>
|
||||
<button class="btn-create" onclick={createCollection} disabled={creating || !newName.trim()}>+</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
{:else if error}
|
||||
<div class="hint error">{error}</div>
|
||||
{:else if collections.length === 0}
|
||||
<div class="hint">Нет коллекций</div>
|
||||
{:else}
|
||||
<ul class="list">
|
||||
{#each collections as col (col.id)}
|
||||
<li class="item">
|
||||
<!-- Имя / inline-редактор -->
|
||||
<div class="col-info">
|
||||
{#if editing?.id === col.id}
|
||||
<input
|
||||
class="edit-input"
|
||||
bind:value={editing.value}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Enter') commitEdit()
|
||||
if (e.key === 'Escape') cancelEdit()
|
||||
}}
|
||||
autofocus
|
||||
/>
|
||||
{:else}
|
||||
<div class="col-name">
|
||||
{col.name}
|
||||
{#if col.isInbox}
|
||||
<span class="badge-inbox">основная</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if col.itemCount > 0}
|
||||
<div class="col-meta">{col.itemCount} эл.</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Кнопки действий -->
|
||||
<div class="actions">
|
||||
{#if editing?.id === col.id}
|
||||
<button class="icon-btn ok" onclick={commitEdit} title="Сохранить"><Check size={16}/></button>
|
||||
<button class="icon-btn cancel" onclick={cancelEdit} title="Отмена"> <X size={16}/></button>
|
||||
{:else}
|
||||
{#if !col.isInbox}
|
||||
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
||||
<Pencil size={16}/>
|
||||
</button>
|
||||
<button class="icon-btn star" onclick={() => confirmInbox = col.id} title="Сделать основной">
|
||||
<Star size={16}/>
|
||||
</button>
|
||||
<button class="icon-btn del" onclick={() => confirmDelete = col.id} title="Удалить">
|
||||
<Trash2 size={16}/>
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<!-- Подтверждение удаления -->
|
||||
{#if confirmDelete === col.id && deleteTarget}
|
||||
<li class="confirm-panel">
|
||||
<div class="confirm-text">
|
||||
{#if deleteTarget.itemCount > 0}
|
||||
⚠️ Коллекция содержит <strong>{deleteTarget.itemCount} эл.</strong> — они будут удалены безвозвратно.
|
||||
{:else}
|
||||
Удалить «{deleteTarget.name}»?
|
||||
{/if}
|
||||
</div>
|
||||
<div class="confirm-actions">
|
||||
<button class="btn-danger" onclick={commitDelete}>Удалить</button>
|
||||
<button class="btn-ghost" onclick={() => confirmDelete = null}>Отмена</button>
|
||||
</div>
|
||||
</li>
|
||||
{/if}
|
||||
|
||||
<!-- Подтверждение смены Inbox -->
|
||||
{#if confirmInbox === col.id && inboxTarget}
|
||||
<li class="confirm-panel">
|
||||
<div class="confirm-text">
|
||||
Сделать «{inboxTarget.name}» основной коллекцией? Новые медиа будут сохраняться в неё.
|
||||
</div>
|
||||
<div class="confirm-actions">
|
||||
<button class="btn-primary" onclick={commitSetInbox}>Подтвердить</button>
|
||||
<button class="btn-ghost" onclick={() => confirmInbox = null}>Отмена</button>
|
||||
</div>
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.page { padding: 8px; }
|
||||
|
||||
/* Создание */
|
||||
.new-row { display: flex; gap: 6px; margin-bottom: 8px; }
|
||||
.new-input {
|
||||
flex: 1; padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 14px;
|
||||
}
|
||||
.btn-create {
|
||||
width: 36px; border-radius: 8px; border: none;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
font-size: 20px; cursor: pointer;
|
||||
}
|
||||
.btn-create:disabled { opacity: .4; cursor: default; }
|
||||
|
||||
/* Список */
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
.list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
|
||||
.item {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 10px 10px 12px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.col-info { flex: 1; min-width: 0; }
|
||||
.col-name {
|
||||
font-size: 15px; font-weight: 500;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
}
|
||||
.col-meta { font-size: 12px; color: var(--tg-hint, #888); margin-top: 2px; }
|
||||
|
||||
.badge-inbox {
|
||||
font-size: 11px; font-weight: 600; letter-spacing: .02em;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
border-radius: 4px; padding: 1px 5px;
|
||||
}
|
||||
|
||||
/* Inline-редактор */
|
||||
.edit-input {
|
||||
width: 100%; padding: 4px 8px; border-radius: 6px; border: none;
|
||||
background: var(--tg-bg, #fff); color: var(--tg-text, #000);
|
||||
font-size: 15px; font-weight: 500;
|
||||
outline: 2px solid var(--tg-button, #2196f3);
|
||||
}
|
||||
|
||||
/* Кнопки-иконки */
|
||||
.actions { display: flex; gap: 2px; flex-shrink: 0; }
|
||||
.icon-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none;
|
||||
background: none; color: var(--tg-hint, #999); cursor: pointer;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.icon-btn:hover { background: var(--tg-secondary-bg, #e8e8e8); color: var(--tg-text, #000); }
|
||||
.icon-btn.star:hover { color: #f5a623; }
|
||||
.icon-btn.del:hover { color: #e53935; }
|
||||
.icon-btn.ok { color: #43a047; }
|
||||
.icon-btn.cancel { color: var(--tg-hint, #999); }
|
||||
|
||||
/* Подтверждение */
|
||||
.confirm-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid var(--tg-button, #2196f3);
|
||||
}
|
||||
.confirm-text { font-size: 13px; color: var(--tg-text, #000); margin-bottom: 8px; line-height: 1.4; }
|
||||
.confirm-actions { display: flex; gap: 6px; }
|
||||
|
||||
.btn-danger, .btn-primary, .btn-ghost {
|
||||
padding: 6px 14px; border-radius: 8px; border: none;
|
||||
font-size: 13px; font-weight: 500; cursor: pointer;
|
||||
}
|
||||
.btn-danger { background: #e53935; color: #fff; }
|
||||
.btn-primary { background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff); }
|
||||
.btn-ghost { background: none; color: var(--tg-hint, #888); }
|
||||
.btn-ghost:hover { background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { isAttachmentMode, getQueryId, close as tgClose, showAlert } from '../lib/telegram.js'
|
||||
|
||||
const attachMode = isAttachmentMode()
|
||||
const queryId = getQueryId()
|
||||
|
||||
// Types that have a downloadable file preview
|
||||
const PREVIEWABLE = new Set(['Photo', 'Video', 'Animation', 'Sticker'])
|
||||
|
||||
let items = []
|
||||
let query = ''
|
||||
let loading = true
|
||||
let error = null
|
||||
|
||||
// Map of itemId → { url: string|null, loading: boolean, error: boolean }
|
||||
let previews = {}
|
||||
|
||||
async function load() {
|
||||
loading = true
|
||||
error = null
|
||||
previews = {}
|
||||
try {
|
||||
items = await api.getMedia(query)
|
||||
// Kick off preview loading for each previewable item (fire & forget)
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType)) {
|
||||
loadPreview(item.id)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
error = e.message
|
||||
} finally {
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPreview(id) {
|
||||
previews[id] = { url: null, loading: true, error: false }
|
||||
try {
|
||||
const url = await api.getDownloadUrl(id)
|
||||
previews[id] = { url, loading: false, error: false }
|
||||
} catch {
|
||||
previews[id] = { url: null, loading: false, error: true }
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendToChat(id) {
|
||||
try {
|
||||
await api.sendToChat(id, queryId)
|
||||
tgClose()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id) {
|
||||
try {
|
||||
await api.deleteMedia(id)
|
||||
items = items.filter((i) => i.id !== id)
|
||||
const { [id]: _, ...rest } = previews
|
||||
previews = rest
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
let searchTimer
|
||||
function onSearch() {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(load, 400)
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
{#if attachMode}
|
||||
<div class="attach-banner">Выберите медиа для отправки в чат</div>
|
||||
{/if}
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
on:input={onSearch}
|
||||
/>
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
{:else if error}
|
||||
<div class="hint error">{error}</div>
|
||||
{:else if items.length === 0}
|
||||
<div class="hint">Нет медиа</div>
|
||||
{:else}
|
||||
<ul class="list">
|
||||
{#each items as item (item.id)}
|
||||
{@const preview = previews[item.id]}
|
||||
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->
|
||||
<li
|
||||
class="item"
|
||||
class:item--attach={attachMode}
|
||||
on:click={attachMode ? () => handleSendToChat(item.id) : undefined}
|
||||
role={attachMode ? 'button' : undefined}
|
||||
>
|
||||
{#if PREVIEWABLE.has(item.mediaType)}
|
||||
<div class="thumb-wrap">
|
||||
{#if preview?.loading || !preview}
|
||||
<div class="thumb-skeleton" aria-hidden="true"></div>
|
||||
{:else if preview.url}
|
||||
{#if item.mediaType === 'Video'}
|
||||
<video class="thumb" src={preview.url} muted preload="metadata" />
|
||||
{:else}
|
||||
<img class="thumb" src={preview.url} alt={item.caption ?? item.mediaType} loading="lazy" />
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="thumb-error" title="Не удалось загрузить">🖼</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="item-info">
|
||||
<span class="item-type">{item.mediaType}</span>
|
||||
{#if item.caption}
|
||||
<span class="item-caption">{item.caption}</span>
|
||||
{/if}
|
||||
{#if item.tags?.length}
|
||||
<div class="tags">
|
||||
{#each item.tags as tag}
|
||||
<span class="tag">#{tag}</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if attachMode}
|
||||
<span class="attach-hint">Отправить</span>
|
||||
{:else}
|
||||
<button class="del" on:click={() => handleDelete(item.id)} title="Удалить">✕</button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.page { padding: 8px; }
|
||||
.attach-banner {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: var(--tg-hint, #888);
|
||||
padding: 6px 0 4px;
|
||||
}
|
||||
.search {
|
||||
width: 100%; box-sizing: border-box;
|
||||
padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000);
|
||||
font-size: 14px; margin-bottom: 8px;
|
||||
}
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
.list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
.item {
|
||||
display: flex; align-items: flex-start; gap: 10px;
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
}
|
||||
|
||||
/* ── Thumbnail ──────────────────────────────────────────────────────────── */
|
||||
.thumb-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 64px; height: 64px;
|
||||
border-radius: 6px; overflow: hidden;
|
||||
}
|
||||
.thumb {
|
||||
width: 100%; height: 100%; object-fit: cover; display: block;
|
||||
}
|
||||
.thumb-skeleton {
|
||||
width: 100%; height: 100%;
|
||||
background: linear-gradient(90deg,
|
||||
var(--tg-secondary-bg, #e0e0e0) 25%,
|
||||
var(--tg-bg, #f5f5f5) 50%,
|
||||
var(--tg-secondary-bg, #e0e0e0) 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.4s infinite;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.thumb-error {
|
||||
width: 100%; height: 100%;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 24px;
|
||||
background: var(--tg-secondary-bg, #eee);
|
||||
}
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
/* ── Text info ──────────────────────────────────────────────────────────── */
|
||||
.item-info { flex: 1; min-width: 0; }
|
||||
.item-type { font-size: 11px; color: var(--tg-hint, #888); text-transform: uppercase; }
|
||||
.item-caption { display: block; font-size: 14px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
|
||||
.tag {
|
||||
font-size: 12px; background: var(--tg-button, #2196f3);
|
||||
color: var(--tg-btn-text, #fff); border-radius: 4px; padding: 1px 6px;
|
||||
}
|
||||
.item--attach {
|
||||
cursor: pointer;
|
||||
}
|
||||
.item--attach:active {
|
||||
opacity: 0.7;
|
||||
}
|
||||
.attach-hint {
|
||||
font-size: 12px;
|
||||
color: var(--tg-button, #2196f3);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
align-self: center;
|
||||
}
|
||||
.del {
|
||||
background: none; border: none; color: var(--tg-hint, #888);
|
||||
font-size: 16px; cursor: pointer; padding: 0; flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,7 @@
|
||||
import { writable, derived } from 'svelte/store'
|
||||
|
||||
/** JWT-токен. null — не авторизован. */
|
||||
export const jwt = writable(null)
|
||||
|
||||
/** true, если пользователь авторизован */
|
||||
export const isAuthed = derived(jwt, ($jwt) => $jwt !== null)
|
||||
@@ -0,0 +1,5 @@
|
||||
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
|
||||
|
||||
export default {
|
||||
preprocess: vitePreprocess(),
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { svelte } from '@sveltejs/vite-plugin-svelte'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [svelte()],
|
||||
// В dev-режиме проксируем /api на локальный API,
|
||||
// в продакшене nginx берёт это на себя
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -4,6 +4,8 @@ using MemeVault.Application.Commands.CreateCollection;
|
||||
using MemeVault.Application.Commands.CreateCollectionInvite;
|
||||
using MemeVault.Application.Commands.DeleteCollection;
|
||||
using MemeVault.Application.Commands.RevokeCollectionInvite;
|
||||
using MemeVault.Application.Commands.SetCollectionInbox;
|
||||
using MemeVault.Application.Commands.SetCollectionNsfw;
|
||||
using MemeVault.Application.Commands.ShareCollection;
|
||||
using MemeVault.Application.Commands.UpdateCollection;
|
||||
using MemeVault.Application.Queries.GetCollectionInvites;
|
||||
@@ -96,7 +98,7 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
CancellationToken ct)
|
||||
{
|
||||
var token = await mediator.Send(
|
||||
new CreateCollectionInviteCommand(id, currentUser.TelegramId, request.Role), ct);
|
||||
new CreateCollectionInviteCommand(id, currentUser.TelegramId, request.Role, request.ExpiresAt), ct);
|
||||
return token is null ? NotFound() : Ok(new { token });
|
||||
}
|
||||
|
||||
@@ -109,6 +111,28 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/inbox
|
||||
[HttpPut("{id:guid}/inbox")]
|
||||
public async Task<IActionResult> SetInbox(Guid id, CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(new SetCollectionInboxCommand(id, currentUser.TelegramId), ct);
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/nsfw
|
||||
[HttpPut("{id:guid}/nsfw")]
|
||||
public async Task<IActionResult> SetNsfw(
|
||||
Guid id,
|
||||
[FromBody] SetNsfwRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SetCollectionNsfwCommand(id, currentUser.TelegramId, request.IsNsfw),
|
||||
ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/visibility
|
||||
[HttpPut("{id:guid}/visibility")]
|
||||
public async Task<IActionResult> SetVisibility(
|
||||
@@ -126,5 +150,6 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
|
||||
public sealed record CreateCollectionRequest(string Name, string? Description);
|
||||
public sealed record UpdateCollectionRequest(string Name, string? Description);
|
||||
public sealed record SetNsfwRequest(bool IsNsfw);
|
||||
public sealed record SetVisibilityRequest(CollectionVisibility Visibility);
|
||||
public sealed record CreateInviteRequest(CollectionRole Role);
|
||||
public sealed record CreateInviteRequest(CollectionRole Role, DateTimeOffset? ExpiresAt = null);
|
||||
|
||||
@@ -3,6 +3,8 @@ using MemeVault.Api.Auth;
|
||||
using MemeVault.Application.Commands.CopyMediaToCollection;
|
||||
using MemeVault.Application.Commands.DeleteMedia;
|
||||
using MemeVault.Application.Commands.UpdateMedia;
|
||||
using MemeVault.Application.Commands.SendMediaToChat;
|
||||
using MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
using MemeVault.Application.Queries.GetUserMedia;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -15,17 +17,45 @@ namespace MemeVault.Api.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public sealed class MediaController(IMediator mediator, CurrentUser currentUser) : ControllerBase
|
||||
{
|
||||
// GET /api/media?q=...
|
||||
// GET /api/media?q=...&includeNsfw=true
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll([FromQuery] string? q, CancellationToken ct)
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] string? q,
|
||||
[FromQuery] bool includeNsfw = true,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var items = string.IsNullOrWhiteSpace(q)
|
||||
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId), ct)
|
||||
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q), ct);
|
||||
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q, IncludeNsfw: includeNsfw), ct);
|
||||
|
||||
return Ok(items);
|
||||
}
|
||||
|
||||
// GET /api/media/{id}/download-url
|
||||
// Returns a short-lived pre-signed URL for displaying the media file.
|
||||
[HttpGet("{id:guid}/download-url")]
|
||||
public async Task<IActionResult> GetDownloadUrl(Guid id, CancellationToken ct)
|
||||
{
|
||||
var url = await mediator.Send(
|
||||
new GetMediaDownloadUrlQuery(id, currentUser.TelegramId), ct);
|
||||
|
||||
return Ok(new { url });
|
||||
}
|
||||
|
||||
// POST /api/media/{id}/send
|
||||
// Отправляет элемент в Telegram-чат через answerWebAppQuery (режим аттачмента).
|
||||
[HttpPost("{id:guid}/send")]
|
||||
public async Task<IActionResult> SendToChat(
|
||||
Guid id,
|
||||
[FromBody] SendToChatRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SendMediaToChatCommand(id, currentUser.TelegramId, request.QueryId), ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PATCH /api/media/{id}
|
||||
// Обновляет caption, теги и/или перемещает в другую коллекцию
|
||||
[HttpPatch("{id:guid}")]
|
||||
@@ -67,6 +97,8 @@ public sealed class MediaController(IMediator mediator, CurrentUser currentUser)
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record SendToChatRequest(string QueryId);
|
||||
|
||||
public sealed record UpdateMediaRequest(
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
|
||||
@@ -38,8 +38,8 @@ builder.Services
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateIssuer = false,
|
||||
ValidateAudience = false,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtOpts.Issuer,
|
||||
@@ -53,7 +53,10 @@ builder.Services
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<DomainExceptionHandler>();
|
||||
builder.Services.AddAuthorization();
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddControllers()
|
||||
.AddJsonOptions(o =>
|
||||
o.JsonSerializerOptions.Converters.Add(
|
||||
new System.Text.Json.Serialization.JsonStringEnumConverter()));
|
||||
|
||||
// ── OpenAPI ───────────────────────────────────────────────────────────────────
|
||||
builder.Services.AddHealthChecks()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"Telegram": {
|
||||
"BotToken": ""
|
||||
"BotToken": "",
|
||||
"ApiBaseUrl": "https://api.telegram.org"
|
||||
},
|
||||
"Jwt": {
|
||||
"SecretKey": "",
|
||||
@@ -8,6 +9,13 @@
|
||||
"Audience": "memevault-miniapp",
|
||||
"ExpiryHours": 24
|
||||
},
|
||||
"S3": {
|
||||
"ServiceUrl": "http://minio:9000",
|
||||
"AccessKey": "memevault",
|
||||
"SecretKey": "changeme123",
|
||||
"BucketName": "memevault",
|
||||
"PublicUrl": "http://localhost:9000"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"Postgres": "Host=localhost;Database=memevault;Username=memevault;Password=changeme",
|
||||
"Redis": "localhost:6379"
|
||||
|
||||
+8
-15
@@ -1,6 +1,5 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
@@ -27,25 +26,19 @@ public sealed class AcceptCollectionInviteCommandHandler
|
||||
AcceptCollectionInviteCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var invite = await _invites.GetByTokenAsync(request.Token, cancellationToken);
|
||||
if (invite is null || invite.IsRevoked)
|
||||
if (invite is null || invite.IsRevoked || invite.IsExpired)
|
||||
return null;
|
||||
|
||||
var collection = await _collections.GetByIdAsync(invite.CollectionId, cancellationToken)
|
||||
?? throw new DomainException("Collection no longer exists.");
|
||||
|
||||
// Владелец не может принять инвайт в собственную коллекцию
|
||||
if (collection.OwnerTelegramId == request.AcceptingTelegramId)
|
||||
return collection.Id;
|
||||
|
||||
// Если уже участник — просто возвращаем коллекцию (идемпотентность)
|
||||
if (collection.GetRole(request.AcceptingTelegramId) is not null)
|
||||
return collection.Id;
|
||||
|
||||
// Owner создаёт инвайт с правами requestingTelegramId, добавляем участника
|
||||
collection.AddMember(request.AcceptingTelegramId, invite.Role, collection.OwnerTelegramId);
|
||||
|
||||
await _collections.UpdateAsync(collection, cancellationToken);
|
||||
await _uow.SaveChangesAsync(cancellationToken);
|
||||
// Инвариант "уже участник/владелец → идемпотентно" живёт на агрегате.
|
||||
var added = collection.TryAcceptInvite(request.AcceptingTelegramId, invite.Role);
|
||||
if (added)
|
||||
{
|
||||
await _collections.UpdateAsync(collection, cancellationToken);
|
||||
await _uow.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return collection.Id;
|
||||
}
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ public sealed class CopyMediaToCollectionCommandHandler(
|
||||
return null;
|
||||
|
||||
var target = await collections.GetByIdAsync(request.TargetCollectionId, ct);
|
||||
if (target is null || target.OwnerTelegramId != request.RequestingTelegramId)
|
||||
if (target is null || !target.CanWrite(request.RequestingTelegramId))
|
||||
throw new DomainException("Target collection not found.");
|
||||
|
||||
var copy = MediaItem.Create(
|
||||
|
||||
+3
-1
@@ -6,9 +6,11 @@ namespace MemeVault.Application.Commands.CreateCollectionInvite;
|
||||
/// <param name="CollectionId">Коллекция, для которой создаётся инвайт.</param>
|
||||
/// <param name="RequestingTelegramId">Telegram ID запрашивающего (должен быть Owner).</param>
|
||||
/// <param name="Role">Роль, которую получит принявший (Viewer или Manager).</param>
|
||||
/// <param name="ExpiresAt">Срок действия инвайта. null — инвайт бессрочный.</param>
|
||||
/// <returns>Токен инвайта, или null если коллекция не найдена / нет прав.</returns>
|
||||
public sealed record CreateCollectionInviteCommand(
|
||||
Guid CollectionId,
|
||||
long RequestingTelegramId,
|
||||
CollectionRole Role
|
||||
CollectionRole Role,
|
||||
DateTimeOffset? ExpiresAt = null
|
||||
) : IRequest<string?>;
|
||||
|
||||
+2
-1
@@ -37,7 +37,8 @@ public sealed class CreateCollectionInviteCommandHandler
|
||||
var invite = CollectionInvite.Create(
|
||||
collection.Id,
|
||||
request.RequestingTelegramId,
|
||||
request.Role);
|
||||
request.Role,
|
||||
request.ExpiresAt);
|
||||
|
||||
await _invites.AddAsync(invite, cancellationToken);
|
||||
await _uow.SaveChangesAsync(cancellationToken);
|
||||
|
||||
+3
-5
@@ -1,6 +1,6 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Commands.DeleteCollection;
|
||||
@@ -13,12 +13,10 @@ public sealed class DeleteCollectionCommandHandler(
|
||||
public async Task<bool> Handle(DeleteCollectionCommand request, CancellationToken ct)
|
||||
{
|
||||
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
|
||||
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
|
||||
if (collection is null || collection.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
|
||||
return false;
|
||||
|
||||
if (collection.IsInbox)
|
||||
throw new DomainException("Cannot delete the Inbox collection.");
|
||||
|
||||
collection.Delete(request.RequestingTelegramId); // бросает DomainException если IsInbox
|
||||
await collections.RemoveAsync(collection, ct);
|
||||
await unitOfWork.SaveChangesAsync(ct);
|
||||
return true;
|
||||
|
||||
@@ -32,7 +32,7 @@ public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand,
|
||||
if (request.CollectionId.HasValue)
|
||||
{
|
||||
var col = await _collections.GetByIdAsync(request.CollectionId.Value, cancellationToken);
|
||||
if (col is null || col.OwnerTelegramId != request.OwnerTelegramId)
|
||||
if (col is null || !col.CanWrite(request.OwnerTelegramId))
|
||||
throw new DomainException("Target collection not found.");
|
||||
collectionId = col.Id;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Commands.SendMediaToChat;
|
||||
|
||||
/// <summary>
|
||||
/// Отправляет сохранённый MediaItem в чат через Telegram answerWebAppQuery.
|
||||
/// Вызывается когда Mini App открыта из меню «Приложить» и пользователь тапает по элементу.
|
||||
/// </summary>
|
||||
/// <param name="MediaItemId">Элемент для отправки.</param>
|
||||
/// <param name="RequestingUserTelegramId">Telegram ID пользователя (для проверки владения).</param>
|
||||
/// <param name="QueryId">query_id из Telegram WebApp initData.</param>
|
||||
public record SendMediaToChatCommand(
|
||||
Guid MediaItemId,
|
||||
long RequestingUserTelegramId,
|
||||
string QueryId) : IRequest<bool>;
|
||||
@@ -0,0 +1,22 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Commands.SendMediaToChat;
|
||||
|
||||
public sealed class SendMediaToChatCommandHandler(
|
||||
IMediaItemRepository mediaItems,
|
||||
ITelegramQueryAnswerer queryAnswerer)
|
||||
: IRequestHandler<SendMediaToChatCommand, bool>
|
||||
{
|
||||
public async Task<bool> Handle(SendMediaToChatCommand request, CancellationToken ct)
|
||||
{
|
||||
var item = await mediaItems.GetByIdAsync(request.MediaItemId, ct);
|
||||
|
||||
if (item is null || item.OwnerTelegramId != request.RequestingUserTelegramId)
|
||||
return false;
|
||||
|
||||
await queryAnswerer.AnswerAsync(request.QueryId, item, ct);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Commands.SetCollectionInbox;
|
||||
|
||||
/// <summary>
|
||||
/// Делает указанную коллекцию основной (Inbox) для пользователя.
|
||||
/// Возвращает false, если коллекция не найдена или пользователь не владелец.
|
||||
/// </summary>
|
||||
public sealed record SetCollectionInboxCommand(
|
||||
Guid CollectionId,
|
||||
long RequestingTelegramId
|
||||
) : IRequest<bool>;
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Commands.SetCollectionInbox;
|
||||
|
||||
public sealed class SetCollectionInboxCommandHandler(
|
||||
ICollectionRepository collections,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<SetCollectionInboxCommand, bool>
|
||||
{
|
||||
public async Task<bool> Handle(SetCollectionInboxCommand request, CancellationToken ct)
|
||||
{
|
||||
var target = await collections.GetByIdAsync(request.CollectionId, ct);
|
||||
if (target is null || target.GetRole(request.RequestingTelegramId) != CollectionRole.Owner)
|
||||
return false;
|
||||
|
||||
if (target.IsInbox)
|
||||
throw new DomainException("Collection is already the Inbox.");
|
||||
|
||||
// Снимаем флаг с текущего Inbox
|
||||
var currentInbox = await collections.GetInboxAsync(request.RequestingTelegramId, ct);
|
||||
currentInbox?.DemoteFromInbox();
|
||||
|
||||
// Промоция целевой коллекции
|
||||
target.PromoteToInbox(request.RequestingTelegramId);
|
||||
|
||||
await unitOfWork.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Commands.SetCollectionNsfw;
|
||||
|
||||
public sealed record SetCollectionNsfwCommand(
|
||||
Guid CollectionId,
|
||||
long RequestingTelegramId,
|
||||
bool IsNsfw
|
||||
) : IRequest<bool>;
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Commands.SetCollectionNsfw;
|
||||
|
||||
public sealed class SetCollectionNsfwCommandHandler(
|
||||
ICollectionRepository collections,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<SetCollectionNsfwCommand, bool>
|
||||
{
|
||||
public async Task<bool> Handle(SetCollectionNsfwCommand request, CancellationToken ct)
|
||||
{
|
||||
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
|
||||
|
||||
// Коллекция не найдена или пользователь — не участник
|
||||
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
|
||||
return false;
|
||||
|
||||
// Проверка роли Owner делегирована домену (бросит DomainException при нарушении)
|
||||
collection.SetNsfw(request.IsNsfw, request.RequestingTelegramId);
|
||||
|
||||
await unitOfWork.SaveChangesAsync(ct);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -12,7 +12,9 @@ public sealed class UpdateCollectionCommandHandler(
|
||||
public async Task<bool> Handle(UpdateCollectionCommand request, CancellationToken ct)
|
||||
{
|
||||
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
|
||||
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
|
||||
// Если коллекции нет или пользователь — не участник, возвращаем 404.
|
||||
// Если роль ниже Manager — domain.Rename() бросит DomainException.
|
||||
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
|
||||
return false;
|
||||
|
||||
collection.Rename(request.Name, request.RequestingTelegramId);
|
||||
|
||||
@@ -20,19 +20,13 @@ public sealed class UpdateMediaCommandHandler(
|
||||
return false;
|
||||
|
||||
item.UpdateCaption(request.Caption);
|
||||
|
||||
// Полная замена тегов
|
||||
foreach (var tag in item.Tags.ToList())
|
||||
item.RemoveTag(tag);
|
||||
|
||||
foreach (var raw in request.Tags)
|
||||
item.AddTag(new Tag(raw));
|
||||
item.ReplaceTags(request.Tags.Select(r => new Tag(r)));
|
||||
|
||||
// Перемещение в другую коллекцию
|
||||
if (request.CollectionId.HasValue && request.CollectionId.Value != item.CollectionId)
|
||||
{
|
||||
var target = await collections.GetByIdAsync(request.CollectionId.Value, ct);
|
||||
if (target is null || target.OwnerTelegramId != request.RequestingTelegramId)
|
||||
if (target is null || !target.CanWrite(request.RequestingTelegramId))
|
||||
throw new DomainException("Target collection not found.");
|
||||
|
||||
item.MoveToCollection(target.Id);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace MemeVault.Application.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a Telegram file, caches it in S3, and returns a pre-signed download URL.
|
||||
/// </summary>
|
||||
public interface ITelegramFileCacheService
|
||||
{
|
||||
/// <param name="telegramFileId">Telegram file_id to fetch and cache.</param>
|
||||
/// <param name="urlExpiry">How long the returned pre-signed URL should remain valid.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A temporary pre-signed URL pointing to the cached file in S3.</returns>
|
||||
Task<string> GetCachedUrlAsync(string telegramFileId, TimeSpan urlExpiry, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
|
||||
namespace MemeVault.Application.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Отправляет медиа-элемент в Telegram-чат через answerWebAppQuery.
|
||||
/// Используется когда Mini App открыта из меню «Приложить».
|
||||
/// </summary>
|
||||
public interface ITelegramQueryAnswerer
|
||||
{
|
||||
Task AnswerAsync(string queryId, MediaItem item, CancellationToken ct = default);
|
||||
}
|
||||
@@ -15,5 +15,6 @@ public sealed record CollectionInviteDto(
|
||||
CollectionRole Role,
|
||||
bool IsRevoked,
|
||||
DateTimeOffset CreatedAt,
|
||||
DateTimeOffset? RevokedAt
|
||||
DateTimeOffset? RevokedAt,
|
||||
DateTimeOffset? ExpiresAt
|
||||
);
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ public sealed class GetCollectionInvitesQueryHandler
|
||||
|
||||
return invites
|
||||
.Select(i => new CollectionInviteDto(
|
||||
i.Id, i.Token, i.Role, i.IsRevoked, i.CreatedAt, i.RevokedAt))
|
||||
i.Id, i.Token, i.Role, i.IsRevoked, i.CreatedAt, i.RevokedAt, i.ExpiresAt))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public sealed record GetCollectionItemsQuery(
|
||||
public sealed record CollectionMediaItemDto(
|
||||
Guid Id,
|
||||
string? Reference,
|
||||
MediaType Type,
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@ public sealed class GetCollectionItemsQueryHandler
|
||||
{
|
||||
var collection = await _collections.GetByIdAsync(request.CollectionId, cancellationToken);
|
||||
|
||||
// Return null → 404 when collection missing or belongs to someone else
|
||||
if (collection is null || collection.OwnerTelegramId != request.RequestingTelegramId)
|
||||
// null → 404: коллекция не найдена или пользователь не является участником/публичный доступ
|
||||
if (collection is null || !collection.CanView(request.RequestingTelegramId))
|
||||
return null;
|
||||
|
||||
var items = await _mediaItems.GetByCollectionAsync(request.CollectionId, cancellationToken);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
|
||||
/// <summary>
|
||||
/// Returns a short-lived pre-signed URL so the Mini App can display a media item.
|
||||
/// </summary>
|
||||
/// <param name="MediaItemId">Id of the MediaItem to fetch.</param>
|
||||
/// <param name="RequestingUserTelegramId">Telegram id of the caller (for ownership check).</param>
|
||||
public record GetMediaDownloadUrlQuery(Guid MediaItemId, long RequestingUserTelegramId)
|
||||
: IRequest<string>;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
|
||||
public sealed class GetMediaDownloadUrlQueryHandler
|
||||
: IRequestHandler<GetMediaDownloadUrlQuery, string>
|
||||
{
|
||||
private static readonly TimeSpan UrlExpiry = TimeSpan.FromMinutes(15);
|
||||
|
||||
private readonly IMediaItemRepository _mediaItems;
|
||||
private readonly ITelegramFileCacheService _cache;
|
||||
|
||||
public GetMediaDownloadUrlQueryHandler(
|
||||
IMediaItemRepository mediaItems,
|
||||
ITelegramFileCacheService cache)
|
||||
{
|
||||
_mediaItems = mediaItems;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
public async Task<string> Handle(GetMediaDownloadUrlQuery request, CancellationToken ct)
|
||||
{
|
||||
var item = await _mediaItems.GetByIdAsync(request.MediaItemId, ct)
|
||||
?? throw new DomainException("Media item not found.");
|
||||
|
||||
if (item.OwnerTelegramId != request.RequestingUserTelegramId)
|
||||
throw new DomainException("Access denied.");
|
||||
|
||||
if (item.Type == MediaType.Text || item.Source is null)
|
||||
throw new DomainException("This media item has no downloadable file.");
|
||||
|
||||
if (item.Source.Origin == MediaOrigin.S3)
|
||||
{
|
||||
// Already stored in S3 — just generate a presigned URL directly.
|
||||
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
|
||||
}
|
||||
|
||||
// Telegram source — go through cache (lock → S3 check → fetch → upload → presign).
|
||||
return await _cache.GetCachedUrlAsync(item.Source.Reference!, UrlExpiry, ct);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ public sealed record CollectionDto(
|
||||
string? Description,
|
||||
bool IsInbox,
|
||||
CollectionVisibility Visibility,
|
||||
bool IsNsfw,
|
||||
string? ShareToken,
|
||||
int ItemCount,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
+6
-6
@@ -12,13 +12,12 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
GetUserCollectionsQuery request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var cols = await collections.GetByOwnerAsync(request.OwnerTelegramId, ct);
|
||||
// Все коллекции, в которых пользователь — участник (любая роль), включая шаренные
|
||||
var cols = await collections.GetByMemberAsync(request.OwnerTelegramId, ct);
|
||||
|
||||
// Подсчёт элементов по коллекциям за один запрос
|
||||
var allItems = await mediaItems.GetByOwnerAsync(request.OwnerTelegramId, ct);
|
||||
var countByCollection = allItems
|
||||
.GroupBy(i => i.CollectionId)
|
||||
.ToDictionary(g => g.Key, g => g.Count());
|
||||
// Подсчёт элементов по всем коллекциям за один GROUP BY запрос
|
||||
var collectionIds = cols.Select(c => c.Id).ToList();
|
||||
var countByCollection = await mediaItems.GetCountsByCollectionIdsAsync(collectionIds, ct);
|
||||
|
||||
return cols.Select(c => new CollectionDto(
|
||||
c.Id,
|
||||
@@ -26,6 +25,7 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
c.Description,
|
||||
c.IsInbox,
|
||||
c.Visibility,
|
||||
c.IsNsfw,
|
||||
c.ShareToken,
|
||||
countByCollection.GetValueOrDefault(c.Id, 0),
|
||||
c.CreatedAt
|
||||
|
||||
@@ -10,14 +10,15 @@ namespace MemeVault.Application.Queries.SearchMedia;
|
||||
public sealed record SearchMediaQuery(
|
||||
long OwnerTelegramId,
|
||||
string RawQuery,
|
||||
int Limit = 50
|
||||
int Limit = 50,
|
||||
bool IncludeNsfw = true
|
||||
) : IRequest<IReadOnlyList<MediaItemDto>>;
|
||||
|
||||
public sealed record MediaItemDto(
|
||||
Guid Id,
|
||||
Guid CollectionId,
|
||||
string? FileId,
|
||||
MediaType Type,
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
DateTimeOffset CreatedAt
|
||||
|
||||
@@ -23,6 +23,7 @@ public sealed class SearchMediaQueryHandler : IRequestHandler<SearchMediaQuery,
|
||||
request.OwnerTelegramId,
|
||||
query,
|
||||
request.Limit,
|
||||
request.IncludeNsfw,
|
||||
cancellationToken);
|
||||
|
||||
return items.Select(i => new MediaItemDto(
|
||||
|
||||
@@ -6,7 +6,6 @@ using MemeVault.Bot.Telegram.Handlers;
|
||||
using MemeVault.Bot.Telegram.InlineMode;
|
||||
using MemeVault.Infrastructure;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
@@ -24,14 +23,6 @@ builder.Services.AddSingleton<BotMetrics>();
|
||||
|
||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<BotOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.Token,
|
||||
baseUrl: string.IsNullOrWhiteSpace(opts.ApiBaseUrl) ? null : opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
builder.Services.AddScoped<MessageHandler>();
|
||||
builder.Services.AddScoped<InlineQueryHandler>();
|
||||
|
||||
@@ -24,7 +24,7 @@ public sealed class InlineQueryHandler
|
||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||
{
|
||||
var results = await _mediator.Send(
|
||||
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 50), ct);
|
||||
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 10, IncludeNsfw: false), ct);
|
||||
|
||||
var answers = results
|
||||
.Select(ToInlineResult)
|
||||
@@ -43,7 +43,7 @@ public sealed class InlineQueryHandler
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
|
||||
return item.Type switch
|
||||
return item.MediaType switch
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||
{
|
||||
|
||||
@@ -26,6 +26,9 @@ public sealed class Collection
|
||||
/// <summary>Системная коллекция входящих. Нельзя удалить или переименовать.</summary>
|
||||
public bool IsInbox { get; private set; }
|
||||
|
||||
/// <summary>Коллекция содержит контент 18+. Скрывается в inline-режиме.</summary>
|
||||
public bool IsNsfw { get; private set; }
|
||||
|
||||
/// <summary>Токен для доступа по ссылке (для Visibility = LinkOnly и Public).</summary>
|
||||
public string? ShareToken { get; private set; }
|
||||
|
||||
@@ -102,7 +105,15 @@ public sealed class Collection
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Видимость и шаринг ────────────────────────────────────────────────────
|
||||
// ── Видимость, NSFW и шаринг ─────────────────────────────────────────────
|
||||
|
||||
/// <summary>Устанавливает NSFW-флаг коллекции. Только Owner.</summary>
|
||||
public void SetNsfw(bool isNsfw, long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
IsNsfw = isNsfw;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void SetVisibility(CollectionVisibility visibility, long requestingTelegramId)
|
||||
{
|
||||
@@ -132,6 +143,58 @@ public sealed class Collection
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Удаление ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет, что коллекцию можно удалить, и бросает <see cref="DomainException"/> если нет.
|
||||
/// Фактическое удаление из хранилища выполняет репозиторий.
|
||||
/// </summary>
|
||||
public void Delete(long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
if (IsInbox)
|
||||
throw new DomainException("Cannot delete the Inbox collection.");
|
||||
}
|
||||
|
||||
// ── Inbox ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Делает коллекцию основной (Inbox). Вызывать только после снятия флага с текущего Inbox.
|
||||
/// </summary>
|
||||
public void PromoteToInbox(long requestingTelegramId)
|
||||
{
|
||||
EnsureRole(requestingTelegramId, CollectionRole.Owner);
|
||||
if (IsInbox)
|
||||
throw new DomainException("Collection is already the Inbox.");
|
||||
IsInbox = true;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Снимает флаг Inbox. Вызывать перед промоцией другой коллекции.</summary>
|
||||
public void DemoteFromInbox()
|
||||
{
|
||||
IsInbox = false;
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
// ── Инвайты ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Добавляет принимающего инвайт как участника коллекции.
|
||||
/// Если пользователь уже является участником (или владельцем) — ничего не делает (идемпотентно).
|
||||
/// Авторизация производится через инвайт-токен, а не через requestingTelegramId.
|
||||
/// </summary>
|
||||
/// <returns>true — участник добавлен; false — уже был участником, изменений нет.</returns>
|
||||
public bool TryAcceptInvite(long acceptingTelegramId, CollectionRole inviteRole)
|
||||
{
|
||||
if (GetRole(acceptingTelegramId) is not null)
|
||||
return false;
|
||||
|
||||
_members.Add(new CollectionMember(Id, acceptingTelegramId, inviteRole));
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Доступ ────────────────────────────────────────────────────────────────
|
||||
|
||||
public bool CanView(long telegramId)
|
||||
@@ -140,6 +203,13 @@ public sealed class Collection
|
||||
return _members.Any(m => m.TelegramId == telegramId);
|
||||
}
|
||||
|
||||
/// <summary>Пользователь может добавлять/изменять элементы коллекции (Менеджер или Владелец).</summary>
|
||||
public bool CanWrite(long telegramId)
|
||||
{
|
||||
var role = GetRole(telegramId);
|
||||
return role is not null && role >= CollectionRole.Manager;
|
||||
}
|
||||
|
||||
public CollectionRole? GetRole(long telegramId) =>
|
||||
_members.FirstOrDefault(m => m.TelegramId == telegramId)?.Role;
|
||||
|
||||
|
||||
@@ -24,10 +24,16 @@ public sealed class CollectionInvite
|
||||
public bool IsRevoked { get; private set; }
|
||||
public DateTimeOffset? RevokedAt { get; private set; }
|
||||
|
||||
/// <summary>Дата истечения инвайта. null — инвайт бессрочный (действует до отзыва).</summary>
|
||||
public DateTimeOffset? ExpiresAt { get; private set; }
|
||||
|
||||
/// <summary>Инвайт истёк по сроку (не связан с ручным отзывом).</summary>
|
||||
public bool IsExpired => ExpiresAt.HasValue && DateTimeOffset.UtcNow > ExpiresAt.Value;
|
||||
|
||||
// EF Core constructor
|
||||
private CollectionInvite() { }
|
||||
|
||||
private CollectionInvite(Guid collectionId, long createdBy, CollectionRole role)
|
||||
private CollectionInvite(Guid collectionId, long createdBy, CollectionRole role, DateTimeOffset? expiresAt)
|
||||
{
|
||||
Id = Guid.NewGuid();
|
||||
CollectionId = collectionId;
|
||||
@@ -35,15 +41,23 @@ public sealed class CollectionInvite
|
||||
Role = role;
|
||||
Token = GenerateToken();
|
||||
CreatedAt = DateTimeOffset.UtcNow;
|
||||
ExpiresAt = expiresAt;
|
||||
IsRevoked = false;
|
||||
}
|
||||
|
||||
public static CollectionInvite Create(Guid collectionId, long createdBy, CollectionRole role)
|
||||
public static CollectionInvite Create(
|
||||
Guid collectionId,
|
||||
long createdBy,
|
||||
CollectionRole role,
|
||||
DateTimeOffset? expiresAt = null)
|
||||
{
|
||||
if (role == CollectionRole.Owner)
|
||||
throw new DomainException("Cannot create an invite with Owner role.");
|
||||
|
||||
return new CollectionInvite(collectionId, createdBy, role);
|
||||
if (expiresAt.HasValue && expiresAt.Value <= DateTimeOffset.UtcNow)
|
||||
throw new DomainException("Invite expiry must be in the future.");
|
||||
|
||||
return new CollectionInvite(collectionId, createdBy, role, expiresAt);
|
||||
}
|
||||
|
||||
public void Revoke()
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace MemeVault.Domain.Aggregates.MediaItem;
|
||||
/// </summary>
|
||||
public sealed class MediaItem
|
||||
{
|
||||
// Не readonly: EF Core перезаписывает ссылку при материализации из text[] через value conversion.
|
||||
private List<Tag> _tags = [];
|
||||
private readonly List<IDomainEvent> _domainEvents = [];
|
||||
|
||||
@@ -122,5 +123,17 @@ public sealed class MediaItem
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Полностью заменяет набор тегов. Дубли игнорируются. Лимит — 20 тегов.</summary>
|
||||
public void ReplaceTags(IEnumerable<Tag> newTags)
|
||||
{
|
||||
var distinct = newTags.Distinct().ToList();
|
||||
if (distinct.Count > 20)
|
||||
throw new DomainException("Cannot have more than 20 tags per item.");
|
||||
|
||||
_tags.Clear();
|
||||
_tags.AddRange(distinct);
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
public void ClearDomainEvents() => _domainEvents.Clear();
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ public interface ICollectionRepository
|
||||
Task<Collection?> GetByShareTokenAsync(string shareToken, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<Collection>> GetByOwnerAsync(long ownerTelegramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Все коллекции, в которых пользователь является участником (любая роль).</summary>
|
||||
Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Возвращает системную коллекцию Inbox пользователя.</summary>
|
||||
Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -12,13 +12,19 @@ public interface IMediaItemRepository
|
||||
|
||||
/// <summary>
|
||||
/// Поиск с поддержкой тег-фильтров (#tag, -#tag) и полнотекстового поиска по caption.
|
||||
/// <paramref name="includeNsfw"/> = false исключает элементы из коллекций с флагом IsNsfw.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaItem>> SearchAsync(
|
||||
long ownerTelegramId,
|
||||
TagSearchQuery query,
|
||||
int limit = 50,
|
||||
bool includeNsfw = true,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Количество элементов в каждой из указанных коллекций за один запрос.</summary>
|
||||
Task<Dictionary<Guid, int>> GetCountsByCollectionIdsAsync(
|
||||
IReadOnlyList<Guid> collectionIds, CancellationToken ct = default);
|
||||
|
||||
Task AddAsync(MediaItem item, CancellationToken ct = default);
|
||||
Task RemoveAsync(MediaItem item, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using MemeVault.Domain.Exceptions;
|
||||
|
||||
namespace MemeVault.Domain.ValueObjects;
|
||||
|
||||
public sealed record Tag
|
||||
@@ -7,12 +9,12 @@ public sealed record Tag
|
||||
public Tag(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
throw new ArgumentException("Tag cannot be empty.", nameof(value));
|
||||
throw new DomainException("Tag cannot be empty.");
|
||||
|
||||
Value = value.Trim().ToLowerInvariant();
|
||||
|
||||
if (Value.Length > 50)
|
||||
throw new ArgumentException("Tag must be 50 characters or less.", nameof(value));
|
||||
throw new DomainException("Tag must be 50 characters or less.");
|
||||
}
|
||||
|
||||
public static implicit operator string(Tag tag) => tag.Value;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using MemeVault.Domain.Exceptions;
|
||||
|
||||
namespace MemeVault.Domain.ValueObjects;
|
||||
|
||||
/// <summary>
|
||||
@@ -11,7 +13,7 @@ public sealed record TelegramFileId
|
||||
public TelegramFileId(string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
throw new ArgumentException("FileId cannot be empty.", nameof(value));
|
||||
throw new DomainException("FileId cannot be empty.");
|
||||
|
||||
Value = value;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
using Amazon.Runtime;
|
||||
using Amazon.S3;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using MemeVault.Infrastructure.Persistence.Repositories;
|
||||
using MemeVault.Infrastructure.Persistence.Repositories;
|
||||
using MemeVault.Infrastructure.Services;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Infrastructure;
|
||||
|
||||
@@ -15,6 +21,7 @@ public static class InfrastructureServiceExtensions
|
||||
this IServiceCollection services,
|
||||
IConfiguration config)
|
||||
{
|
||||
// ── PostgreSQL / EF Core ──────────────────────────────────────────────
|
||||
services.AddDbContext<AppDbContext>(opts =>
|
||||
opts.UseNpgsql(config.GetConnectionString("Postgres")));
|
||||
|
||||
@@ -24,8 +31,57 @@ public static class InfrastructureServiceExtensions
|
||||
services.AddScoped<ICollectionRepository, CollectionRepository>();
|
||||
services.AddScoped<ICollectionInviteRepository, CollectionInviteRepository>();
|
||||
|
||||
var redisConn = config.GetConnectionString("Redis") ?? "localhost:6379";
|
||||
services.AddStackExchangeRedisCache(opts => opts.Configuration = redisConn);
|
||||
// ── Redis ─────────────────────────────────────────────────────────────
|
||||
var redisConn = config.GetConnectionString("Redis")
|
||||
?? throw new InvalidOperationException(
|
||||
"Required configuration value 'ConnectionStrings:Redis' is missing or empty.");
|
||||
|
||||
var multiplexer = ConnectionMultiplexer.Connect(redisConn);
|
||||
services.AddSingleton<IConnectionMultiplexer>(multiplexer);
|
||||
services.AddStackExchangeRedisCache(opts =>
|
||||
{
|
||||
opts.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(multiplexer);
|
||||
});
|
||||
|
||||
// ── Options ───────────────────────────────────────────────────────────
|
||||
services.AddOptions<S3Options>()
|
||||
.BindConfiguration(S3Options.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<TelegramApiOptions>()
|
||||
.BindConfiguration(TelegramApiOptions.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// ── S3 / MinIO ────────────────────────────────────────────────────────
|
||||
services.AddSingleton<IAmazonS3>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<S3Options>>().Value;
|
||||
var credentials = new BasicAWSCredentials(opts.AccessKey, opts.SecretKey);
|
||||
var cfg = new AmazonS3Config
|
||||
{
|
||||
ServiceURL = opts.ServiceUrl,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = opts.ServiceUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase),
|
||||
};
|
||||
return new AmazonS3Client(credentials, cfg);
|
||||
});
|
||||
|
||||
services.AddScoped<IFileStorage, S3FileStorage>();
|
||||
|
||||
// ── Telegram Bot Client ───────────────────────────────────────────────
|
||||
services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<TelegramApiOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.BotToken,
|
||||
baseUrl: opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
services.AddScoped<ITelegramFileCacheService, TelegramFileCacheService>();
|
||||
services.AddScoped<ITelegramQueryAnswerer, TelegramQueryAnswererService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,13 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AWSSDK.S3" Version="3.7.*" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.12" />
|
||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.12" />
|
||||
<PackageReference Include="Telegram.Bot" Version="22.10.3.2" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261006171407_AddCollectionNsfw")]
|
||||
partial class AddCollectionNsfw
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsInbox")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("MediaGroupId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("media_group_id");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCollectionNsfw : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "is_nsfw",
|
||||
table: "collections",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "is_nsfw",
|
||||
table: "collections");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+306
@@ -0,0 +1,306 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261006221608_AddCollectionInviteExpiry")]
|
||||
partial class AddCollectionInviteExpiry
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsInbox")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("MediaGroupId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("media_group_id");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddCollectionInviteExpiry : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<DateTimeOffset>(
|
||||
name: "expires_at",
|
||||
table: "collection_invites",
|
||||
type: "timestamp with time zone",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "expires_at",
|
||||
table: "collection_invites");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,12 @@ namespace MemeVault.Infrastructure.Migrations
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_inbox");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
@@ -130,6 +136,10 @@ namespace MemeVault.Infrastructure.Migrations
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MemeVault.Infrastructure.Options;
|
||||
|
||||
public sealed class S3Options
|
||||
{
|
||||
public const string Section = "S3";
|
||||
|
||||
/// <summary>
|
||||
/// S3/MinIO endpoint — used both by the .NET SDK for uploads/downloads
|
||||
/// and as the base URL in generated presigned links.
|
||||
/// Must be reachable both from the server and from the browser.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string ServiceUrl { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string AccessKey { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Bucket where cached Telegram files are stored.</summary>
|
||||
[Required]
|
||||
public string BucketName { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace MemeVault.Infrastructure.Options;
|
||||
|
||||
/// <summary>
|
||||
/// Options for calling the Telegram Bot API from Infrastructure services.
|
||||
/// Reads from the same "Telegram" config section as MemeVault.Api.
|
||||
/// </summary>
|
||||
public sealed class TelegramApiOptions
|
||||
{
|
||||
public const string Section = "Telegram";
|
||||
|
||||
[Required]
|
||||
public string BotToken { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Custom Telegram Bot API server base URL (e.g. a local server).
|
||||
/// Null means the official https://api.telegram.org — the library handles the default.
|
||||
/// </summary>
|
||||
public string? ApiBaseUrl { get; set; }
|
||||
}
|
||||
@@ -29,6 +29,11 @@ public sealed class CollectionConfiguration : IEntityTypeConfiguration<Collectio
|
||||
.HasColumnName("is_inbox")
|
||||
.IsRequired();
|
||||
|
||||
builder.Property(x => x.IsNsfw)
|
||||
.HasColumnName("is_nsfw")
|
||||
.IsRequired()
|
||||
.HasDefaultValue(false);
|
||||
|
||||
builder.Property(x => x.Visibility)
|
||||
.HasColumnName("visibility")
|
||||
.HasConversion<string>()
|
||||
|
||||
+1
@@ -39,6 +39,7 @@ public sealed class CollectionInviteConfiguration : IEntityTypeConfiguration<Col
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
builder.Property(x => x.CreatedAt).HasColumnName("created_at");
|
||||
builder.Property(x => x.ExpiresAt).HasColumnName("expires_at");
|
||||
builder.Property(x => x.IsRevoked).HasColumnName("is_revoked");
|
||||
builder.Property(x => x.RevokedAt).HasColumnName("revoked_at");
|
||||
}
|
||||
|
||||
@@ -32,6 +32,16 @@ public sealed class CollectionRepository : ICollectionRepository
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Collection>> GetByMemberAsync(long telegramId, CancellationToken ct)
|
||||
{
|
||||
return await _db.Collections
|
||||
.Include(c => c.Members)
|
||||
.Where(c => c.Members.Any(m => m.TelegramId == telegramId))
|
||||
.OrderBy(x => x.IsInbox ? 0 : 1) // Inbox всегда первым
|
||||
.ThenBy(x => x.Name)
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public Task<Collection?> GetInboxAsync(long ownerTelegramId, CancellationToken ct) =>
|
||||
_db.Collections
|
||||
.Include(c => c.Members)
|
||||
|
||||
@@ -42,12 +42,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
long ownerTelegramId,
|
||||
TagSearchQuery query,
|
||||
int limit,
|
||||
bool includeNsfw,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var sql = _db.MediaItems.Where(x => x.OwnerTelegramId == ownerTelegramId);
|
||||
|
||||
if (query.IsEmpty)
|
||||
{
|
||||
if (!includeNsfw)
|
||||
sql = sql.Where(x => !_db.Collections.Any(c => c.Id == x.CollectionId && c.IsNsfw));
|
||||
|
||||
return await sql
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.Take(limit)
|
||||
@@ -79,6 +83,9 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
conditions.Add($"caption ILIKE {{{idx}}}");
|
||||
}
|
||||
|
||||
if (!includeNsfw)
|
||||
conditions.Add("NOT EXISTS (SELECT 1 FROM collections c WHERE c.id = collection_id AND c.is_nsfw = true)");
|
||||
|
||||
var where = string.Join(" AND ", conditions);
|
||||
var rawSql = $"SELECT * FROM media_items WHERE {where} ORDER BY created_at DESC LIMIT {limit}";
|
||||
|
||||
@@ -87,6 +94,16 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<Dictionary<Guid, int>> GetCountsByCollectionIdsAsync(
|
||||
IReadOnlyList<Guid> collectionIds, CancellationToken ct)
|
||||
{
|
||||
return await _db.MediaItems
|
||||
.Where(x => collectionIds.Contains(x.CollectionId))
|
||||
.GroupBy(x => x.CollectionId)
|
||||
.Select(g => new { CollectionId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(x => x.CollectionId, x => x.Count, ct);
|
||||
}
|
||||
|
||||
public async Task AddAsync(MediaItem item, CancellationToken ct)
|
||||
{
|
||||
await _db.MediaItems.AddAsync(item, ct);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// S3/MinIO-backed implementation of <see cref="IFileStorage"/>.
|
||||
/// </summary>
|
||||
public sealed class S3FileStorage : IFileStorage
|
||||
{
|
||||
private readonly IAmazonS3 _s3;
|
||||
private readonly S3Options _opts;
|
||||
|
||||
public S3FileStorage(IAmazonS3 s3, IOptions<S3Options> opts)
|
||||
{
|
||||
_s3 = s3;
|
||||
_opts = opts.Value;
|
||||
}
|
||||
|
||||
public async Task<MediaSource> UploadAsync(
|
||||
Stream content,
|
||||
string objectKey,
|
||||
string contentType,
|
||||
long ownerTelegramId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var request = new PutObjectRequest
|
||||
{
|
||||
BucketName = _opts.BucketName,
|
||||
Key = objectKey,
|
||||
InputStream = content,
|
||||
ContentType = contentType,
|
||||
// CalcMD5 + autoCloseStream defaults are fine
|
||||
};
|
||||
|
||||
await _s3.PutObjectAsync(request, ct);
|
||||
return MediaSource.FromS3(objectKey);
|
||||
}
|
||||
|
||||
public async Task<string> GetDownloadUrlAsync(
|
||||
string objectKey,
|
||||
TimeSpan expiry,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var request = new GetPreSignedUrlRequest
|
||||
{
|
||||
BucketName = _opts.BucketName,
|
||||
Key = objectKey,
|
||||
Expires = DateTime.UtcNow.Add(expiry),
|
||||
Protocol = _opts.ServiceUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
|
||||
? Protocol.HTTPS
|
||||
: Protocol.HTTP,
|
||||
};
|
||||
|
||||
return await _s3.GetPreSignedURLAsync(request);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(string objectKey, CancellationToken ct = default)
|
||||
{
|
||||
await _s3.DeleteObjectAsync(_opts.BucketName, objectKey, ct);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.IO.Pipelines;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Infrastructure.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StackExchange.Redis;
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Fetches a Telegram file, caches it in S3, and returns a pre-signed download URL.
|
||||
///
|
||||
/// Flow per request:
|
||||
/// 1. Acquire Redis lock (SET … NX EX 60).
|
||||
/// 2. Check whether the object already exists in S3 (HeadObject).
|
||||
/// 3. If cache miss: call Telegram getFile → stream to S3 with ContentLength.
|
||||
/// 4. Generate and return a pre-signed URL regardless of cache hit/miss.
|
||||
/// 5. Release Redis lock.
|
||||
/// </summary>
|
||||
public sealed class TelegramFileCacheService : ITelegramFileCacheService
|
||||
{
|
||||
private const string CacheKeyPrefix = "cache/";
|
||||
private const string LockKeyPrefix = "lock:file:";
|
||||
private const int LockTtlSeconds = 60;
|
||||
|
||||
private readonly IConnectionMultiplexer _redis;
|
||||
private readonly IAmazonS3 _s3;
|
||||
private readonly IFileStorage _storage;
|
||||
private readonly ITelegramBotClient _botClient;
|
||||
private readonly S3Options _s3Opts;
|
||||
private readonly ILogger<TelegramFileCacheService> _logger;
|
||||
|
||||
public TelegramFileCacheService(
|
||||
IConnectionMultiplexer redis,
|
||||
IAmazonS3 s3,
|
||||
IFileStorage storage,
|
||||
ITelegramBotClient botClient,
|
||||
IOptions<S3Options> s3Opts,
|
||||
ILogger<TelegramFileCacheService> logger)
|
||||
{
|
||||
_redis = redis;
|
||||
_s3 = s3;
|
||||
_storage = storage;
|
||||
_botClient = botClient;
|
||||
_s3Opts = s3Opts.Value;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<string> GetCachedUrlAsync(
|
||||
string telegramFileId,
|
||||
TimeSpan urlExpiry,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var hash = ComputeHash(telegramFileId);
|
||||
var s3Key = $"{CacheKeyPrefix}{hash}";
|
||||
var lockKey = $"{LockKeyPrefix}{hash}";
|
||||
var db = _redis.GetDatabase();
|
||||
|
||||
// ── 1. Acquire Redis lock ─────────────────────────────────────────────
|
||||
var lockAcquired = await db.StringSetAsync(
|
||||
lockKey, "1",
|
||||
TimeSpan.FromSeconds(LockTtlSeconds),
|
||||
When.NotExists);
|
||||
|
||||
try
|
||||
{
|
||||
// ── 2. Check S3 ───────────────────────────────────────────────────
|
||||
var existsInS3 = await ObjectExistsAsync(s3Key, ct);
|
||||
|
||||
// ── 3. Cache miss: fetch from Telegram and upload to S3 ───────────
|
||||
if (!existsInS3)
|
||||
{
|
||||
_logger.LogInformation("Cache miss for fileId {FileId}, fetching from Telegram.", telegramFileId);
|
||||
await FetchAndCacheAsync(telegramFileId, s3Key, ct);
|
||||
}
|
||||
|
||||
// ── 4. Generate presigned URL ─────────────────────────────────────
|
||||
return await _storage.GetDownloadUrlAsync(s3Key, urlExpiry, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// ── 5. Release lock (only if we acquired it) ──────────────────────
|
||||
if (lockAcquired)
|
||||
await db.KeyDeleteAsync(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Private helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private static string ComputeHash(string fileId)
|
||||
{
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(fileId));
|
||||
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private async Task<bool> ObjectExistsAsync(string key, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _s3.GetObjectMetadataAsync(_s3Opts.BucketName, key, ct);
|
||||
return true;
|
||||
}
|
||||
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FetchAndCacheAsync(string telegramFileId, string s3Key, CancellationToken ct)
|
||||
{
|
||||
// Resolve file_path and file_size via Bot API
|
||||
var file = await _botClient.GetFile(telegramFileId, ct);
|
||||
var filePath = file.FilePath ?? throw new InvalidOperationException("Telegram returned null file_path.");
|
||||
var contentType = InferContentType(filePath);
|
||||
|
||||
// Stream from Telegram to S3 via a pipe — no full buffering
|
||||
var pipe = new Pipe();
|
||||
|
||||
// Download runs on a thread-pool thread, writing into the pipe writer
|
||||
var downloadTask = Task.Run(async () =>
|
||||
{
|
||||
try { await _botClient.DownloadFile(filePath, pipe.Writer.AsStream(), ct); }
|
||||
finally { pipe.Writer.Complete(); }
|
||||
}, CancellationToken.None);
|
||||
|
||||
var putRequest = new PutObjectRequest
|
||||
{
|
||||
BucketName = _s3Opts.BucketName,
|
||||
Key = s3Key,
|
||||
InputStream = pipe.Reader.AsStream(),
|
||||
ContentType = contentType,
|
||||
};
|
||||
// Provide ContentLength when available so the AWS SDK doesn't buffer internally
|
||||
if (file.FileSize.HasValue)
|
||||
putRequest.Headers.ContentLength = file.FileSize.Value;
|
||||
|
||||
await Task.WhenAll(_s3.PutObjectAsync(putRequest, ct), downloadTask);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Cached Telegram fileId {FileId} → S3 key {Key} ({Bytes} bytes).",
|
||||
telegramFileId, s3Key, file.FileSize);
|
||||
}
|
||||
|
||||
private static string InferContentType(string filePath)
|
||||
{
|
||||
var ext = Path.GetExtension(filePath).ToLowerInvariant();
|
||||
return ext switch
|
||||
{
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".png" => "image/png",
|
||||
".gif" => "image/gif",
|
||||
".webp" => "image/webp",
|
||||
".mp4" => "video/mp4",
|
||||
".webm" => "video/webm",
|
||||
".tgs" => "application/x-tgsticker",
|
||||
".ogg" => "audio/ogg",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
using MemeVault.Domain.Enums;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.InlineQueryResults;
|
||||
|
||||
namespace MemeVault.Infrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Вызывает Telegram Bot API answerWebAppQuery, чтобы отправить медиа в чат.
|
||||
/// Формирует нужный InlineQueryResult в зависимости от типа медиа.
|
||||
/// </summary>
|
||||
public sealed class TelegramQueryAnswererService : ITelegramQueryAnswerer
|
||||
{
|
||||
private readonly ITelegramBotClient _botClient;
|
||||
private readonly ILogger<TelegramQueryAnswererService> _logger;
|
||||
|
||||
public TelegramQueryAnswererService(
|
||||
ITelegramBotClient botClient,
|
||||
ILogger<TelegramQueryAnswererService> logger)
|
||||
{
|
||||
_botClient = botClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task AnswerAsync(string queryId, MediaItem item, CancellationToken ct = default)
|
||||
{
|
||||
var result = BuildResult(item);
|
||||
await _botClient.AnswerWebAppQuery(queryId, result, ct);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Sent item {ItemId} (type={Type}) to chat via queryId {QueryId}",
|
||||
item.Id, item.Type, queryId);
|
||||
}
|
||||
|
||||
// ── Строим нужный тип InlineQueryResult ──────────────────────────────────
|
||||
|
||||
private static InlineQueryResult BuildResult(MediaItem item)
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
var fileId = item.Source?.Reference;
|
||||
var caption = item.Caption;
|
||||
|
||||
return item.Type switch
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id,
|
||||
fileId ?? throw new InvalidOperationException("Photo has no file_id"))
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Video => new InlineQueryResultCachedVideo(id,
|
||||
fileId ?? throw new InvalidOperationException("Video has no file_id"),
|
||||
title: caption?[..Math.Min(60, caption.Length)] ?? "Video")
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Sticker => new InlineQueryResultCachedSticker(id,
|
||||
fileId ?? throw new InvalidOperationException("Sticker has no file_id")),
|
||||
|
||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id,
|
||||
fileId ?? throw new InvalidOperationException("Animation has no file_id"))
|
||||
{
|
||||
Caption = caption,
|
||||
},
|
||||
|
||||
MediaType.Text => new InlineQueryResultArticle(id,
|
||||
title: caption?[..Math.Min(60, caption?.Length ?? 0)] ?? "Текст",
|
||||
inputMessageContent: new InputTextMessageContent(caption ?? string.Empty))
|
||||
{
|
||||
Description = caption,
|
||||
},
|
||||
|
||||
_ => throw new NotSupportedException($"MediaType {item.Type} is not supported for chat sending."),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -81,12 +81,12 @@ public sealed class GetCollectionItemsQueryHandlerTests
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, result.Count);
|
||||
|
||||
var dto1 = result.Single(d => d.Type == MediaType.Photo);
|
||||
var dto1 = result.Single(d => d.MediaType == MediaType.Photo);
|
||||
Assert.Equal("file1", dto1.Reference);
|
||||
Assert.Equal("funny cat", dto1.Caption);
|
||||
Assert.Equal("cats", Assert.Single(dto1.Tags));
|
||||
|
||||
var dto2 = result.Single(d => d.Type == MediaType.Text);
|
||||
var dto2 = result.Single(d => d.MediaType == MediaType.Text);
|
||||
Assert.Null(dto2.Reference);
|
||||
Assert.Equal("hello world", dto2.Caption);
|
||||
Assert.Empty(dto2.Tags);
|
||||
|
||||
Reference in New Issue
Block a user