Compare commits
7
Commits
v1.0.0
..
22c0bf7697
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22c0bf7697 | ||
|
|
be4f492314 | ||
|
|
8a867d04a3 | ||
|
|
57e2264929 | ||
|
|
2f9effeffc | ||
|
|
4d588c89fb | ||
|
|
2a41ac9423 |
@@ -0,0 +1,180 @@
|
||||
name: CI / CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
tags: ['v*']
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
REGISTRY: code.kruzya.dev
|
||||
# backend: api + bot + migrator (единый образ, разные CMD)
|
||||
BACKEND_IMAGE: code.kruzya.dev/crazyhackgut/telegrammemevault/backend
|
||||
# frontend: miniapp nginx (для docker-compose)
|
||||
FRONTEND_IMAGE: code.kruzya.dev/crazyhackgut/telegrammemevault/frontend
|
||||
# frontend-static: FROM scratch, используется как image volume в k8s
|
||||
FRONTEND_STATIC_IMAGE: code.kruzya.dev/crazyhackgut/telegrammemevault/frontend-static
|
||||
|
||||
jobs:
|
||||
# ─────────────────────────────── TESTS ──────────────────────────────────────
|
||||
test:
|
||||
name: Unit tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore MemeVault.sln
|
||||
|
||||
- name: Test
|
||||
run: |
|
||||
dotnet test src/MemeVault.Tests.Unit \
|
||||
--configuration Release \
|
||||
--no-restore \
|
||||
--logger "console;verbosity=normal"
|
||||
|
||||
# ─────────────────────────────── BACKEND ────────────────────────────────────
|
||||
build-backend:
|
||||
name: Build & push backend
|
||||
needs: test
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Compute image tags
|
||||
id: meta
|
||||
run: |
|
||||
SHA="${GITHUB_SHA:0:12}"
|
||||
SAFE_REF=$(echo "$GITHUB_REF_NAME" \
|
||||
| tr '[:upper:]' '[:lower:]' \
|
||||
| sed 's/[^a-z0-9._-]/-/g')
|
||||
IMG="${{ env.BACKEND_IMAGE }}"
|
||||
TAGS="${IMG}:sha-${SHA},${IMG}:${SAFE_REF}"
|
||||
if [ "$GITHUB_REF_TYPE" = "tag" ]; then
|
||||
TAGS="${TAGS},${IMG}:latest"
|
||||
fi
|
||||
echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: CrazyHackGUT
|
||||
password: ${{ secrets.IMAGE_PUSH_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
cache-from: type=registry,ref=${{ env.BACKEND_IMAGE }}:cache
|
||||
cache-to: type=registry,ref=${{ env.BACKEND_IMAGE }}:cache,mode=max
|
||||
|
||||
# ─────────────────────── FRONTEND-STATIC (FROM scratch) ─────────────────────
|
||||
build-frontend-static:
|
||||
name: Build & push frontend-static
|
||||
needs: test
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
outputs:
|
||||
# Передаём точный sha-тег следующему джобу
|
||||
image: ${{ steps.meta.outputs.image }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Compute image tags
|
||||
id: meta
|
||||
run: |
|
||||
SHA="${GITHUB_SHA:0:12}"
|
||||
SAFE_REF=$(echo "$GITHUB_REF_NAME" \
|
||||
| tr '[:upper:]' '[:lower:]' \
|
||||
| sed 's/[^a-z0-9._-]/-/g')
|
||||
IMG="${{ env.FRONTEND_STATIC_IMAGE }}"
|
||||
TAGS="${IMG}:sha-${SHA},${IMG}:${SAFE_REF}"
|
||||
if [ "$GITHUB_REF_TYPE" = "tag" ]; then
|
||||
TAGS="${TAGS},${IMG}:latest"
|
||||
fi
|
||||
echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"
|
||||
echo "image=${IMG}:sha-${SHA}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: CrazyHackGUT
|
||||
password: ${{ secrets.IMAGE_PUSH_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: miniapp
|
||||
file: miniapp/Dockerfile.frontend
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
cache-from: type=registry,ref=${{ env.FRONTEND_STATIC_IMAGE }}:cache
|
||||
cache-to: type=registry,ref=${{ env.FRONTEND_STATIC_IMAGE }}:cache,mode=max
|
||||
|
||||
# ─────────────────────── FRONTEND (nginx поверх static) ─────────────────────
|
||||
build-frontend:
|
||||
name: Build & push frontend (nginx)
|
||||
needs: build-frontend-static
|
||||
if: github.event_name == 'push'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Compute image tags
|
||||
id: meta
|
||||
run: |
|
||||
SHA="${GITHUB_SHA:0:12}"
|
||||
SAFE_REF=$(echo "$GITHUB_REF_NAME" \
|
||||
| tr '[:upper:]' '[:lower:]' \
|
||||
| sed 's/[^a-z0-9._-]/-/g')
|
||||
IMG="${{ env.FRONTEND_IMAGE }}"
|
||||
TAGS="${IMG}:sha-${SHA},${IMG}:${SAFE_REF}"
|
||||
if [ "$GITHUB_REF_TYPE" = "tag" ]; then
|
||||
TAGS="${TAGS},${IMG}:latest"
|
||||
fi
|
||||
echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Log in to registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: CrazyHackGUT
|
||||
password: ${{ secrets.IMAGE_PUSH_TOKEN }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: miniapp
|
||||
file: miniapp/Dockerfile.nginx
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
# Передаём точный тег собранного frontend-static
|
||||
build-args: |
|
||||
STATIC_IMAGE=${{ needs.build-frontend-static.outputs.image }}
|
||||
cache-from: type=registry,ref=${{ env.FRONTEND_IMAGE }}:cache
|
||||
cache-to: type=registry,ref=${{ env.FRONTEND_IMAGE }}:cache,mode=max
|
||||
@@ -30,5 +30,9 @@ spec:
|
||||
value: {{ .Values.telegram.apiBaseUrl }}
|
||||
- name: Bot__Mode
|
||||
value: {{ .Values.telegram.mode }}
|
||||
{{- if .Values.telegram.miniAppUrl }}
|
||||
- name: Bot__MiniAppUrl
|
||||
value: {{ .Values.telegram.miniAppUrl }}
|
||||
{{- end }}
|
||||
resources:
|
||||
{{- toYaml .Values.bot.resources | nindent 12 }}
|
||||
|
||||
@@ -75,6 +75,10 @@ s3:
|
||||
telegram:
|
||||
apiBaseUrl: https://api.telegram.org
|
||||
mode: Polling
|
||||
# Публичный URL Mini App (https://example.com).
|
||||
# Подставляется в кнопку «Открыть MemeVault» над inline-результатами.
|
||||
# Если пусто — кнопка не показывается.
|
||||
miniAppUrl: ""
|
||||
|
||||
jwt:
|
||||
expiryHours: 24
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
# 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
|
||||
@@ -1,17 +0,0 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Образ содержит только собранные статические файлы в корне (/).
|
||||
# Используется как Image Volume в Kubernetes (≥ 1.31):
|
||||
# volumes[].image монтирует содержимое образа напрямую в nginx-контейнер.
|
||||
|
||||
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
|
||||
|
||||
FROM scratch
|
||||
COPY --from=build /app/dist /
|
||||
@@ -0,0 +1,18 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# Образ со статикой для image volume в Kubernetes (v1.31+).
|
||||
# Содержит только собранные файлы Vite — без nginx и системных слоёв.
|
||||
# Используется как init-volume: nginx монтирует его содержимое в /usr/share/nginx/html.
|
||||
|
||||
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
|
||||
|
||||
# Финальный образ — FROM scratch, файлы в корне
|
||||
FROM scratch
|
||||
COPY --from=build /app/dist /
|
||||
@@ -0,0 +1,21 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
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
|
||||
|
||||
# ── frontend-static: FROM scratch, image volume для k8s (v1.31+) ─────────────
|
||||
FROM scratch AS static
|
||||
COPY --from=build /app/dist /
|
||||
|
||||
# ── frontend: nginx для docker-compose ───────────────────────────────────────
|
||||
FROM nginx:1.27-alpine AS nginx-runtime
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
EXPOSE 80
|
||||
+3
-11
@@ -2,13 +2,13 @@
|
||||
import { onMount } from 'svelte'
|
||||
import { jwt, isAuthed } from './stores/auth.js'
|
||||
import { api } from './lib/api.js'
|
||||
import { initData, applyTheme, isAttachmentMode } from './lib/telegram.js'
|
||||
import { initData, applyTheme, isAttachmentMode, isInlineMode } from './lib/telegram.js'
|
||||
import MediaPage from './pages/MediaPage.svelte'
|
||||
import CollectionsPage from './pages/CollectionsPage.svelte'
|
||||
import SendPage from './pages/SendPage.svelte'
|
||||
|
||||
// Режим: пользователь хочет отправить медиа в чат (Mini App открыта через «Прикрепить»)
|
||||
const sendMode = isAttachmentMode()
|
||||
// Режим отправки: attachment menu (query_id) или inline кнопка (?mode=inline)
|
||||
const sendMode = isAttachmentMode() || isInlineMode()
|
||||
|
||||
let tab = 'media' // 'media' | 'collections'
|
||||
let authError = null
|
||||
@@ -70,14 +70,6 @@
|
||||
</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 {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
background: var(--tg-bg, #fff);
|
||||
color: var(--tg-text, #000);
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* iOS Safari: без этого при фокусе на input страница зумится */
|
||||
input, textarea, select {
|
||||
font-size: 16px;
|
||||
}
|
||||
@@ -16,6 +16,20 @@ export const close = () => tg?.close()
|
||||
export const getQueryId = () => tg?.initDataUnsafe?.query_id ?? null
|
||||
export const isAttachmentMode = () => !!getQueryId()
|
||||
|
||||
/**
|
||||
* Mini App открыта из кнопки над inline-результатами (?mode=inline).
|
||||
* Пользователь выбирает медиа → вызываем switchInlineQuery → бот возвращает элемент.
|
||||
*/
|
||||
export const isInlineMode = () =>
|
||||
new URLSearchParams(window.location.search).get('mode') === 'inline'
|
||||
|
||||
/**
|
||||
* Переключиться в inline-режим с заданным запросом.
|
||||
* Вставляет «@botname query» в поле ввода чата и закрывает Mini App.
|
||||
* @param {string} query — например 'send:uuid'
|
||||
*/
|
||||
export const switchInlineQuery = (query) => tg?.switchInlineQuery(query)
|
||||
|
||||
/**
|
||||
* Имя чата/собеседника, в который будет отправлено медиа.
|
||||
* - Личный чат → receiver.first_name (+ last_name если есть)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import './app.css'
|
||||
import { mount } from 'svelte'
|
||||
import App from './App.svelte'
|
||||
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
import { User, Users, Megaphone } from 'lucide-svelte'
|
||||
import { onMount } from 'svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { getQueryId, getChatName, getChatType, close as tgClose, showAlert } from '../lib/telegram.js'
|
||||
import {
|
||||
getQueryId, getChatName, getChatType,
|
||||
isInlineMode, switchInlineQuery,
|
||||
close as tgClose, showAlert,
|
||||
} from '../lib/telegram.js'
|
||||
|
||||
const queryId = getQueryId()
|
||||
const chatName = getChatName()
|
||||
const chatType = getChatType()
|
||||
const inlineMode = isInlineMode()
|
||||
const queryId = getQueryId()
|
||||
const chatName = getChatName()
|
||||
const chatType = getChatType()
|
||||
|
||||
const PREVIEWABLE = new Set(['Photo', 'Video', 'Animation', 'Sticker'])
|
||||
|
||||
@@ -45,6 +50,17 @@
|
||||
async function send(id) {
|
||||
if (sending) return
|
||||
sending = id
|
||||
|
||||
if (inlineMode) {
|
||||
// Inline-режим: передаём управление боту через switchInlineQuery.
|
||||
// Telegram вставляет «@bot send:<id>» в поле ввода — пользователь тапает результат.
|
||||
switchInlineQuery(`send:${id}`)
|
||||
// switchInlineQuery закрывает Mini App сам, но на случай если нет — подстрахуемся
|
||||
tgClose()
|
||||
return
|
||||
}
|
||||
|
||||
// Attachment-режим (query_id): отправляем через answerWebAppQuery
|
||||
try {
|
||||
await api.sendToChat(id, queryId)
|
||||
tgClose()
|
||||
@@ -65,8 +81,8 @@
|
||||
|
||||
<div class="page">
|
||||
<div class="header">
|
||||
<div class="title">Отправить в чат</div>
|
||||
{#if chatName}
|
||||
<div class="title">{inlineMode ? 'Выберите медиа' : 'Отправить в чат'}</div>
|
||||
{#if chatName && !inlineMode}
|
||||
<div class="chat-name">
|
||||
{#if chatType === 'private'}
|
||||
<User size={14} strokeWidth={2} />
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaItem;
|
||||
|
||||
/// <summary>
|
||||
/// Возвращает один медиа-элемент по Id.
|
||||
/// Проверяет, что запрашивающий является членом коллекции, которой принадлежит элемент.
|
||||
/// Используется ботом в inline-режиме (обработка запроса "send:uuid").
|
||||
/// </summary>
|
||||
public sealed record GetMediaItemQuery(
|
||||
long RequesterTelegramId,
|
||||
Guid ItemId
|
||||
) : IRequest<MediaItemDto?>;
|
||||
@@ -0,0 +1,40 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetMediaItem;
|
||||
|
||||
public sealed class GetMediaItemQueryHandler : IRequestHandler<GetMediaItemQuery, MediaItemDto?>
|
||||
{
|
||||
private readonly IMediaItemRepository _mediaItems;
|
||||
private readonly ICollectionRepository _collections;
|
||||
|
||||
public GetMediaItemQueryHandler(IMediaItemRepository mediaItems, ICollectionRepository collections)
|
||||
{
|
||||
_mediaItems = mediaItems;
|
||||
_collections = collections;
|
||||
}
|
||||
|
||||
public async Task<MediaItemDto?> Handle(GetMediaItemQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = await _mediaItems.GetByIdAsync(request.ItemId, cancellationToken);
|
||||
if (item is null) return null;
|
||||
|
||||
// Пользователь должен быть членом коллекции, содержащей элемент (любая роль)
|
||||
var collection = await _collections.GetByIdAsync(item.CollectionId, cancellationToken);
|
||||
if (collection is null || collection.GetRole(request.RequesterTelegramId) is null)
|
||||
return null;
|
||||
|
||||
return new MediaItemDto(
|
||||
item.Id,
|
||||
item.CollectionId,
|
||||
item.Source?.Reference,
|
||||
item.Type,
|
||||
item.Caption,
|
||||
item.Tags.Select(t => t.Value).ToList(),
|
||||
item.CreatedAt,
|
||||
item.InlineTitle,
|
||||
item.InlineDescription
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,9 @@ public sealed class BotOptions
|
||||
/// </summary>
|
||||
public string? ApiBaseUrl { get; set; }
|
||||
|
||||
/// <summary>Публичный URL Mini App — используется в кнопке inline-режима.</summary>
|
||||
public string MiniAppUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Публичный URL хоста для регистрации webhook (только в режиме Webhook).</summary>
|
||||
public string WebhookHost { get; set; } = string.Empty;
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Queries.GetMediaItem;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using MemeVault.Bot.Options;
|
||||
using MemeVault.Domain.Enums;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.InlineQueryResults;
|
||||
@@ -8,37 +11,90 @@ using Telegram.Bot.Types.InlineQueryResults;
|
||||
namespace MemeVault.Bot.Telegram.InlineMode;
|
||||
|
||||
/// <summary>
|
||||
/// Обрабатывает inline-запросы: @bot #мем #кот -#толстый
|
||||
/// Обрабатывает inline-запросы двух видов:
|
||||
/// • обычный поиск — @bot #мем #кот -#толстый
|
||||
/// • точечная отправка — @bot send:<guid> (пользователь выбрал элемент в Mini App)
|
||||
/// </summary>
|
||||
public sealed class InlineQueryHandler
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ITelegramBotClient _bot;
|
||||
private readonly BotOptions _options;
|
||||
|
||||
public InlineQueryHandler(IMediator mediator, ITelegramBotClient bot)
|
||||
public InlineQueryHandler(IMediator mediator, ITelegramBotClient bot, IOptions<BotOptions> options)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_bot = bot;
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||
{
|
||||
var userId = inlineQuery.From.Id;
|
||||
var rawQuery = inlineQuery.Query ?? string.Empty;
|
||||
|
||||
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
||||
if (rawQuery.StartsWith("send:", StringComparison.OrdinalIgnoreCase)
|
||||
&& Guid.TryParse(rawQuery[5..], out var itemId))
|
||||
{
|
||||
await HandleSendAsync(inlineQuery.Id, userId, itemId, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Обычный поиск
|
||||
await HandleSearchAsync(inlineQuery.Id, userId, rawQuery, ct);
|
||||
}
|
||||
|
||||
// ── Точечная отправка ────────────────────────────────────────────────────
|
||||
|
||||
private async Task HandleSendAsync(string queryId, long userId, Guid itemId, CancellationToken ct)
|
||||
{
|
||||
var item = await _mediator.Send(new GetMediaItemQuery(RequesterTelegramId: userId, ItemId: itemId), ct);
|
||||
|
||||
InlineQueryResult[] answers = item is null
|
||||
? []
|
||||
: [ToInlineResult(item)!];
|
||||
|
||||
await _bot.AnswerInlineQuery(
|
||||
queryId,
|
||||
answers.OfType<InlineQueryResult>(),
|
||||
cacheTime: 0,
|
||||
isPersonal: true,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Поиск ────────────────────────────────────────────────────────────────
|
||||
|
||||
private async Task HandleSearchAsync(string queryId, long userId, string rawQuery, CancellationToken ct)
|
||||
{
|
||||
var results = await _mediator.Send(
|
||||
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 10, IncludeNsfw: false), ct);
|
||||
new SearchMediaQuery(userId, rawQuery, Limit: 10, IncludeNsfw: false), ct);
|
||||
|
||||
var answers = results
|
||||
.Select(ToInlineResult)
|
||||
.OfType<InlineQueryResult>()
|
||||
.ToArray();
|
||||
|
||||
// Кнопка над результатами — открывает Mini App в inline-режиме
|
||||
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
||||
? null
|
||||
: new InlineQueryResultsButton
|
||||
{
|
||||
Text = "Открыть MemeVault",
|
||||
WebApp = new WebAppInfo { Url = _options.MiniAppUrl + "?mode=inline" }
|
||||
};
|
||||
|
||||
await _bot.AnswerInlineQuery(
|
||||
inlineQuery.Id,
|
||||
queryId,
|
||||
answers,
|
||||
button: button,
|
||||
cacheTime: 10,
|
||||
isPersonal: true,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Конвертер ────────────────────────────────────────────────────────────
|
||||
|
||||
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
using MemeVault.Application.Queries.GetMediaItem;
|
||||
using MemeVault.Domain.Aggregates.Collection;
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace MemeVault.Tests.Unit.Handlers;
|
||||
|
||||
public sealed class GetMediaItemQueryHandlerTests
|
||||
{
|
||||
private readonly IMediaItemRepository _mediaItems = Substitute.For<IMediaItemRepository>();
|
||||
private readonly ICollectionRepository _collections = Substitute.For<ICollectionRepository>();
|
||||
private readonly GetMediaItemQueryHandler _handler;
|
||||
|
||||
private const long OwnerId = 1L;
|
||||
private const long MemberId = 2L;
|
||||
private const long StrangerId = 99L;
|
||||
|
||||
public GetMediaItemQueryHandlerTests()
|
||||
{
|
||||
_handler = new GetMediaItemQueryHandler(_mediaItems, _collections);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static (Collection col, MediaItem item) MakeCollectionWithItem(
|
||||
long ownerId, long? memberId = null)
|
||||
{
|
||||
var col = Collection.Create(ownerId, "Test");
|
||||
if (memberId.HasValue)
|
||||
col.AddMember(memberId.Value, CollectionRole.Viewer, requestingTelegramId: ownerId);
|
||||
|
||||
var item = MediaItem.Create(
|
||||
ownerId, col.Id,
|
||||
MediaSource.FromTelegram("file123"),
|
||||
MediaType.Photo, caption: null);
|
||||
|
||||
return (col, item);
|
||||
}
|
||||
|
||||
// ── Item not found ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ItemNotFound_ReturnsNull()
|
||||
{
|
||||
_mediaItems.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns((MediaItem?)null);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(OwnerId, Guid.NewGuid()), default);
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
// ── Access denied ─────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_CollectionNotFound_ReturnsNull()
|
||||
{
|
||||
var (_, item) = MakeCollectionWithItem(OwnerId);
|
||||
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
|
||||
_collections.GetByIdAsync(item.CollectionId, Arg.Any<CancellationToken>())
|
||||
.Returns((Collection?)null);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(OwnerId, item.Id), default);
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_Stranger_ReturnsNull()
|
||||
{
|
||||
var (col, item) = MakeCollectionWithItem(OwnerId);
|
||||
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
|
||||
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(StrangerId, item.Id), default);
|
||||
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
// ── Access granted ────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_Owner_ReturnsDto()
|
||||
{
|
||||
var (col, item) = MakeCollectionWithItem(OwnerId);
|
||||
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
|
||||
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(OwnerId, item.Id), default);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(item.Id, result.Id);
|
||||
Assert.Equal("file123", result.FileId);
|
||||
Assert.Equal(MediaType.Photo, result.MediaType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_CollectionMemberViewer_ReturnsDto()
|
||||
{
|
||||
// Элемент сохранён владельцем, но запрашивает другой участник коллекции
|
||||
var (col, item) = MakeCollectionWithItem(OwnerId, memberId: MemberId);
|
||||
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
|
||||
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(MemberId, item.Id), default);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(item.Id, result.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ItemWithTags_MapsTagsToDto()
|
||||
{
|
||||
var (col, item) = MakeCollectionWithItem(OwnerId);
|
||||
item.AddTag(new Tag("мем"));
|
||||
item.AddTag(new Tag("кот"));
|
||||
|
||||
_mediaItems.GetByIdAsync(item.Id, Arg.Any<CancellationToken>()).Returns(item);
|
||||
_collections.GetByIdAsync(col.Id, Arg.Any<CancellationToken>()).Returns(col);
|
||||
|
||||
var result = await _handler.Handle(
|
||||
new GetMediaItemQuery(OwnerId, item.Id), default);
|
||||
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(2, result.Tags.Count);
|
||||
Assert.Contains("мем", result.Tags);
|
||||
Assert.Contains("кот", result.Tags);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user