Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d58fff4a7 | ||
|
|
f67a544d7a | ||
|
|
8169b6474a | ||
|
|
693840d662 | ||
|
|
309e3416d6 | ||
|
|
e6a440e3f3 | ||
|
|
6108885c5d | ||
|
|
b283696cd7 | ||
|
|
22c0bf7697 | ||
|
|
be4f492314 | ||
|
|
8a867d04a3 | ||
|
|
57e2264929 | ||
|
|
2f9effeffc | ||
|
|
4d588c89fb | ||
|
|
2a41ac9423 |
@@ -0,0 +1,210 @@
|
||||
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"
|
||||
|
||||
# ─────────────────────────────── HELM ───────────────────────────────────────
|
||||
build-helm:
|
||||
name: Build & push Helm chart
|
||||
needs: test
|
||||
if: github.event_name == 'push' && github.ref_type == 'tag'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Compute chart version
|
||||
id: meta
|
||||
run: |
|
||||
VERSION="${GITHUB_REF_NAME#v}"
|
||||
echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install Helm
|
||||
uses: azure/setup-helm@v4
|
||||
|
||||
- name: Log in to registry
|
||||
run: |
|
||||
helm registry login ${{ env.REGISTRY }} \
|
||||
--username CrazyHackGUT \
|
||||
--password ${{ secrets.IMAGE_PUSH_TOKEN }}
|
||||
|
||||
- name: Package and push
|
||||
run: |
|
||||
helm package helm/memevault --version ${{ steps.meta.outputs.version }}
|
||||
helm push memevault-${{ steps.meta.outputs.version }}.tgz \
|
||||
oci://${{ env.REGISTRY }}/crazyhackgut/telegrammemevault
|
||||
|
||||
# ─────────────────────────────── 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
|
||||
@@ -0,0 +1,46 @@
|
||||
name: Deploy to production
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
chart_version:
|
||||
description: 'Helm chart version (e.g. 0.0.0-sha-abc123def456 or 1.2.3)'
|
||||
required: true
|
||||
image_tag:
|
||||
description: 'Docker image tag (e.g. sha-abc123def456 or v1.2.3)'
|
||||
required: true
|
||||
|
||||
env:
|
||||
REGISTRY: code.kruzya.dev
|
||||
NAMESPACE: memevault
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Helm upgrade
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Set up kubeconfig
|
||||
run: |
|
||||
mkdir -p ~/.kube
|
||||
echo "${{ secrets.KUBE_CONFIG }}" > ~/.kube/config
|
||||
chmod 600 ~/.kube/config
|
||||
|
||||
- name: Install Helm
|
||||
uses: azure/setup-helm@v4
|
||||
|
||||
- name: Log in to Helm registry
|
||||
run: |
|
||||
helm registry login ${{ env.REGISTRY }} \
|
||||
--username CrazyHackGUT \
|
||||
--password ${{ secrets.IMAGE_PUSH_TOKEN }}
|
||||
|
||||
- name: Deploy
|
||||
run: |
|
||||
helm upgrade --install memevault \
|
||||
oci://${{ env.REGISTRY }}/crazyhackgut/telegrammemevault/memevault \
|
||||
--version ${{ github.event.inputs.chart_version }} \
|
||||
--namespace ${{ env.NAMESPACE }} \
|
||||
--set image.tag=${{ github.event.inputs.image_tag }} \
|
||||
--set miniapp.image.tag=${{ github.event.inputs.image_tag }} \
|
||||
--atomic \
|
||||
--timeout 5m
|
||||
@@ -30,5 +30,16 @@ spec:
|
||||
value: {{ .Values.telegram.apiBaseUrl }}
|
||||
- name: Bot__Mode
|
||||
value: {{ .Values.telegram.mode }}
|
||||
{{- if .Values.telegram.miniAppUrl }}
|
||||
- name: Bot__MiniAppUrl
|
||||
value: {{ .Values.telegram.miniAppUrl }}
|
||||
{{- end }}
|
||||
- name: Jwt__SecretKey
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ .Values.secretName }}
|
||||
key: jwt-secret-key
|
||||
- name: Jwt__ExpiryHours
|
||||
value: {{ .Values.jwt.expiryHours | quote }}
|
||||
resources:
|
||||
{{- toYaml .Values.bot.resources | nindent 12 }}
|
||||
|
||||
@@ -25,7 +25,7 @@ spec:
|
||||
{{- if .Values.ingress.tls.certResolver }}
|
||||
# ACME-резолвер (Let's Encrypt и т.п.) — Traefik сам получает сертификат.
|
||||
certResolver: {{ .Values.ingress.tls.certResolver }}
|
||||
{{- else if .Values.ingress.tls.store }}
|
||||
{{- else if .Values.ingress.tls.store.name }}
|
||||
# TLSStore из произвольного неймспейса (требует allowCrossNamespace=true).
|
||||
store:
|
||||
name: {{ .Values.ingress.tls.store.name }}
|
||||
|
||||
@@ -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
|
||||
+35
-12
@@ -2,18 +2,34 @@
|
||||
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
|
||||
let authing = true
|
||||
|
||||
/**
|
||||
* Возвращает параметры inline-авторизации из query-строки URL,
|
||||
* если они были переданы ботом (?user_id=...&signed_at=...&sign=...).
|
||||
*/
|
||||
function inlineParams() {
|
||||
const p = new URLSearchParams(window.location.search)
|
||||
const userId = p.get('user_id')
|
||||
const signedAt = p.get('signed_at')
|
||||
const sign = p.get('sign')
|
||||
return (userId && signedAt && sign) ? { userId, signedAt, sign } : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Dev-режим: #token=<jwt> в хэш-фрагменте для тестирования без Telegram.
|
||||
* Хэш не отправляется на сервер, поэтому безопасен для локальной отладки.
|
||||
*/
|
||||
function devTokenFromHash() {
|
||||
if (!import.meta.env.DEV) return null
|
||||
const params = new URLSearchParams(window.location.hash.slice(1))
|
||||
@@ -23,7 +39,7 @@
|
||||
onMount(async () => {
|
||||
applyTheme()
|
||||
|
||||
// Dev-режим: #token=<jwt> в URL — пропускаем обмен initData
|
||||
// Dev-режим: #token=<jwt>
|
||||
const devToken = devTokenFromHash()
|
||||
if (devToken) {
|
||||
jwt.set(devToken)
|
||||
@@ -31,6 +47,21 @@
|
||||
return
|
||||
}
|
||||
|
||||
// Inline-режим: бот передал подпись в query-строке
|
||||
const inline = inlineParams()
|
||||
if (inline) {
|
||||
try {
|
||||
const { token } = await api.authInline(inline.userId, inline.signedAt, inline.sign)
|
||||
jwt.set(token)
|
||||
} catch (e) {
|
||||
authError = e.message
|
||||
} finally {
|
||||
authing = false
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Обычный WebApp: авторизация через initData (Telegram заполняет её)
|
||||
try {
|
||||
const { token } = await api.auth(initData)
|
||||
jwt.set(token)
|
||||
@@ -70,14 +101,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;
|
||||
}
|
||||
@@ -33,7 +33,8 @@ async function request(method, path, body) {
|
||||
|
||||
export const api = {
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
authInline: (userId, signedAt, sign) => request('POST', '/auth/inline', { userId: Number(userId), signedAt: Number(signedAt), sign }),
|
||||
|
||||
// ── Me ────────────────────────────────────────────────────────────────────
|
||||
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
||||
@@ -65,6 +66,9 @@ export const api = {
|
||||
joinCollection: (id) => request('POST', `/collections/${id}/join`),
|
||||
regenerateShareLink: (id) => request('POST', `/collections/${id}/share-link/regenerate`),
|
||||
|
||||
// ── Bot ───────────────────────────────────────────────────────────────────
|
||||
getBotInfo: () => request('GET', '/bot/info'),
|
||||
|
||||
// ── Invites ───────────────────────────────────────────────────────────────
|
||||
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
||||
createInvite: (collectionId, role, expiresAt) =>
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { Pencil, Trash2, Star, Check, X, EyeOff, Copy } from 'lucide-svelte'
|
||||
import { Pencil, Trash2, Star, Check, X, EyeOff, Copy, Link, Plus, UserCheck } from 'lucide-svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { showAlert } from '../lib/telegram.js'
|
||||
|
||||
let botUsername = $state('')
|
||||
|
||||
let collections = $state([])
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
@@ -23,9 +25,35 @@
|
||||
// Клонирование: id коллекции, которая клонируется прямо сейчас
|
||||
let cloning = $state(null)
|
||||
|
||||
// Управление инвайтами: id раскрытой коллекции
|
||||
let invitesPanelId = $state(null)
|
||||
// { [collectionId]: CollectionInviteDto[] }
|
||||
let invitesByCol = $state({})
|
||||
let invitesLoading = $state(false)
|
||||
// Форма создания инвайта: { role: 0|1, expiresAt: string|null }
|
||||
let newInvite = $state({ role: 0, expiresAt: '' })
|
||||
let creatingInvite = $state(false)
|
||||
|
||||
let deleteTarget = $derived(collections.find(c => c.id === confirmDelete))
|
||||
let inboxTarget = $derived(collections.find(c => c.id === confirmInbox))
|
||||
|
||||
// CollectionRole: Viewer=0, Manager=1, Owner=2
|
||||
const ROLE_OWNER = 2
|
||||
|
||||
function inviteLink(token) {
|
||||
if (!botUsername) return null
|
||||
return `https://t.me/${botUsername}?start=inv_${token}`
|
||||
}
|
||||
|
||||
function roleLabel(role) {
|
||||
return role === 0 ? 'Читатель' : 'Менеджер'
|
||||
}
|
||||
|
||||
function formatExpiry(expiresAt) {
|
||||
if (!expiresAt) return null
|
||||
return new Date(expiresAt).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null
|
||||
try { collections = await api.getCollections() }
|
||||
@@ -50,6 +78,7 @@
|
||||
itemCount: 0,
|
||||
visibility: 0,
|
||||
shareToken: null,
|
||||
myRole: ROLE_OWNER,
|
||||
createdAt: new Date().toISOString(),
|
||||
}]
|
||||
} catch (e) {
|
||||
@@ -129,7 +158,87 @@
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
// ── Инвайты ────────────────────────────────────────────────────────────────
|
||||
async function toggleInvitesPanel(colId) {
|
||||
if (invitesPanelId === colId) {
|
||||
invitesPanelId = null
|
||||
return
|
||||
}
|
||||
invitesPanelId = colId
|
||||
newInvite = { role: 0, expiresAt: '' }
|
||||
if (invitesByCol[colId]) return // уже загружены
|
||||
|
||||
invitesLoading = true
|
||||
try {
|
||||
invitesByCol = { ...invitesByCol, [colId]: await api.getInvites(colId) }
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
invitesPanelId = null
|
||||
} finally {
|
||||
invitesLoading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function createInvite(colId) {
|
||||
creatingInvite = true
|
||||
try {
|
||||
const expiresAt = newInvite.expiresAt
|
||||
? new Date(newInvite.expiresAt).toISOString()
|
||||
: null
|
||||
const { token } = await api.createInvite(colId, newInvite.role, expiresAt)
|
||||
const created = {
|
||||
id: crypto.randomUUID(), // placeholder до перезагрузки
|
||||
token,
|
||||
role: newInvite.role,
|
||||
isRevoked: false,
|
||||
createdAt: new Date().toISOString(),
|
||||
revokedAt: null,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
invitesByCol = {
|
||||
...invitesByCol,
|
||||
[colId]: [created, ...(invitesByCol[colId] ?? [])],
|
||||
}
|
||||
newInvite = { role: 0, expiresAt: '' }
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
creatingInvite = false
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeInvite(colId, inviteId) {
|
||||
try {
|
||||
await api.revokeInvite(colId, inviteId)
|
||||
invitesByCol = {
|
||||
...invitesByCol,
|
||||
[colId]: invitesByCol[colId].filter(i => i.id !== inviteId),
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToClipboard(text) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
} catch {
|
||||
// fallback для старых WebView
|
||||
const el = document.createElement('textarea')
|
||||
el.value = text
|
||||
document.body.appendChild(el)
|
||||
el.select()
|
||||
document.execCommand('copy')
|
||||
document.body.removeChild(el)
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
load()
|
||||
api.getBotInfo()
|
||||
.then(r => { botUsername = r?.username ?? '' })
|
||||
.catch(() => {})
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
@@ -208,6 +317,16 @@
|
||||
>
|
||||
<Copy size={16}/>
|
||||
</button>
|
||||
{#if col.myRole === ROLE_OWNER}
|
||||
<button
|
||||
class="icon-btn invite"
|
||||
class:invite--on={invitesPanelId === col.id}
|
||||
onclick={() => toggleInvitesPanel(col.id)}
|
||||
title="Управление приглашениями"
|
||||
>
|
||||
<Link size={16}/>
|
||||
</button>
|
||||
{/if}
|
||||
{#if !col.isInbox}
|
||||
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
||||
<Pencil size={16}/>
|
||||
@@ -223,6 +342,91 @@
|
||||
</div>
|
||||
</li>
|
||||
|
||||
<!-- Панель инвайтов -->
|
||||
{#if invitesPanelId === col.id}
|
||||
<li class="invites-panel">
|
||||
<div class="invites-header">
|
||||
<UserCheck size={14}/> Приглашения
|
||||
</div>
|
||||
|
||||
{#if invitesLoading}
|
||||
<div class="invites-loading">Загрузка…</div>
|
||||
{:else}
|
||||
<!-- Список активных инвайтов -->
|
||||
{#if invitesByCol[col.id]?.length > 0}
|
||||
<ul class="invites-list">
|
||||
{#each invitesByCol[col.id] as inv (inv.id)}
|
||||
<li class="invite-item">
|
||||
<span class="invite-role-badge">{roleLabel(inv.role)}</span>
|
||||
{#if inviteLink(inv.token)}
|
||||
<button
|
||||
class="invite-link-btn"
|
||||
onclick={() => copyToClipboard(inviteLink(inv.token))}
|
||||
title="Скопировать ссылку"
|
||||
>
|
||||
<Copy size={12}/> Копировать
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
class="invite-link-btn"
|
||||
onclick={() => copyToClipboard(inv.token)}
|
||||
title="Скопировать токен"
|
||||
>
|
||||
<Copy size={12}/> Токен
|
||||
</button>
|
||||
{/if}
|
||||
{#if inv.expiresAt}
|
||||
<span class="invite-expiry">до {formatExpiry(inv.expiresAt)}</span>
|
||||
{/if}
|
||||
<button
|
||||
class="icon-btn del invite-revoke"
|
||||
onclick={() => revokeInvite(col.id, inv.id)}
|
||||
title="Отозвать"
|
||||
>
|
||||
<X size={14}/>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{:else}
|
||||
<div class="invites-empty">Нет активных приглашений</div>
|
||||
{/if}
|
||||
|
||||
<!-- Форма создания нового инвайта -->
|
||||
<div class="invite-create">
|
||||
<div class="invite-create-row">
|
||||
<div class="role-toggle">
|
||||
<button
|
||||
class="role-btn"
|
||||
class:role-btn--active={newInvite.role === 0}
|
||||
onclick={() => newInvite = { ...newInvite, role: 0 }}
|
||||
>Читатель</button>
|
||||
<button
|
||||
class="role-btn"
|
||||
class:role-btn--active={newInvite.role === 1}
|
||||
onclick={() => newInvite = { ...newInvite, role: 1 }}
|
||||
>Менеджер</button>
|
||||
</div>
|
||||
<input
|
||||
class="expiry-input"
|
||||
type="date"
|
||||
bind:value={newInvite.expiresAt}
|
||||
title="Срок действия (необязательно)"
|
||||
/>
|
||||
<button
|
||||
class="invite-add-btn"
|
||||
onclick={() => createInvite(col.id)}
|
||||
disabled={creatingInvite}
|
||||
title="Создать ссылку-приглашение"
|
||||
>
|
||||
<Plus size={14}/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</li>
|
||||
{/if}
|
||||
|
||||
<!-- Подтверждение удаления -->
|
||||
{#if confirmDelete === col.id && deleteTarget}
|
||||
<li class="confirm-panel">
|
||||
@@ -335,6 +539,9 @@
|
||||
.icon-btn.nsfw { color: var(--tg-hint, #999); }
|
||||
.icon-btn.nsfw:hover { color: #e53935; background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
.icon-btn.nsfw--on { color: #e53935; }
|
||||
.icon-btn.invite { color: var(--tg-hint, #999); }
|
||||
.icon-btn.invite:hover { color: var(--tg-button, #2196f3); }
|
||||
.icon-btn.invite--on { color: var(--tg-button, #2196f3); }
|
||||
|
||||
/* Подтверждение */
|
||||
.confirm-panel {
|
||||
@@ -353,4 +560,97 @@
|
||||
.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); }
|
||||
|
||||
/* ── Панель инвайтов ─────────────────────────────────────────────────────── */
|
||||
.invites-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid var(--tg-button, #2196f3);
|
||||
display: flex; flex-direction: column; gap: 8px;
|
||||
}
|
||||
|
||||
.invites-header {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; font-weight: 600; color: var(--tg-hint, #888);
|
||||
text-transform: uppercase; letter-spacing: .05em;
|
||||
}
|
||||
|
||||
.invites-loading { font-size: 13px; color: var(--tg-hint, #888); }
|
||||
.invites-empty { font-size: 13px; color: var(--tg-hint, #888); text-align: center; padding: 4px 0; }
|
||||
|
||||
.invites-list {
|
||||
list-style: none; margin: 0; padding: 0;
|
||||
display: flex; flex-direction: column; gap: 4px;
|
||||
}
|
||||
|
||||
.invite-item {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
background: var(--tg-bg, #fff);
|
||||
border-radius: 8px; padding: 6px 8px;
|
||||
}
|
||||
|
||||
.invite-role-badge {
|
||||
font-size: 11px; font-weight: 600;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
border-radius: 4px; padding: 1px 6px;
|
||||
white-space: nowrap; flex-shrink: 0;
|
||||
}
|
||||
|
||||
.invite-link-btn {
|
||||
display: flex; align-items: center; gap: 4px;
|
||||
padding: 3px 8px; border-radius: 6px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 12px; cursor: pointer;
|
||||
white-space: nowrap; flex-shrink: 0;
|
||||
transition: background .12s;
|
||||
}
|
||||
.invite-link-btn:hover { background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff); }
|
||||
|
||||
.invite-expiry {
|
||||
font-size: 11px; color: var(--tg-hint, #888);
|
||||
white-space: nowrap; flex-shrink: 0; margin-left: auto;
|
||||
}
|
||||
|
||||
.invite-revoke {
|
||||
width: 26px; height: 26px; flex-shrink: 0;
|
||||
color: var(--tg-hint, #999);
|
||||
}
|
||||
.invite-revoke:hover { color: #e53935; }
|
||||
|
||||
/* Форма создания инвайта */
|
||||
.invite-create { margin-top: 2px; }
|
||||
.invite-create-row {
|
||||
display: flex; gap: 6px; align-items: center;
|
||||
}
|
||||
|
||||
.role-toggle {
|
||||
display: flex; border-radius: 8px; overflow: hidden;
|
||||
border: 1px solid var(--tg-hint, #ccc);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.role-btn {
|
||||
padding: 5px 10px; border: none; font-size: 12px; font-weight: 500;
|
||||
background: none; color: var(--tg-hint, #888); cursor: pointer;
|
||||
transition: background .12s, color .12s;
|
||||
}
|
||||
.role-btn:first-child { border-right: 1px solid var(--tg-hint, #ccc); }
|
||||
.role-btn--active {
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
}
|
||||
|
||||
.expiry-input {
|
||||
flex: 1; min-width: 0; padding: 5px 8px; border-radius: 8px;
|
||||
border: 1px solid var(--tg-hint, #ccc);
|
||||
background: var(--tg-bg, #fff); color: var(--tg-text, #000);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.invite-add-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
cursor: pointer; flex-shrink: 0;
|
||||
transition: opacity .12s;
|
||||
}
|
||||
.invite-add-btn:disabled { opacity: .4; cursor: default; }
|
||||
</style>
|
||||
|
||||
@@ -2,16 +2,22 @@
|
||||
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'])
|
||||
|
||||
let items = $state([])
|
||||
let query = $state('')
|
||||
let includeNsfw = $state(false)
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
let sending = $state(null) // id медиа, которое сейчас отправляется
|
||||
@@ -21,7 +27,7 @@
|
||||
async function load() {
|
||||
loading = true; error = null; previews = {}
|
||||
try {
|
||||
items = await api.getMedia(query)
|
||||
items = await api.getMedia(query, includeNsfw)
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType)) loadPreview(item.id)
|
||||
}
|
||||
@@ -45,6 +51,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()
|
||||
@@ -60,13 +77,18 @@
|
||||
searchTimer = setTimeout(load, 400)
|
||||
}
|
||||
|
||||
function toggleNsfw() {
|
||||
includeNsfw = !includeNsfw
|
||||
load()
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
<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} />
|
||||
@@ -80,12 +102,20 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
oninput={onSearch}
|
||||
/>
|
||||
<div class="search-row">
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
oninput={onSearch}
|
||||
/>
|
||||
<button
|
||||
class="nsfw-btn"
|
||||
class:nsfw-btn--active={includeNsfw}
|
||||
onclick={toggleNsfw}
|
||||
title={includeNsfw ? 'Скрыть 18+' : 'Показать 18+'}
|
||||
>18+</button>
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
@@ -164,13 +194,30 @@
|
||||
}
|
||||
.chat-name :global(svg) { flex-shrink: 0; color: var(--tg-hint, #888); }
|
||||
|
||||
.search-row {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
margin: 4px 8px 6px;
|
||||
}
|
||||
.search {
|
||||
margin: 4px 8px 6px; width: calc(100% - 16px);
|
||||
flex: 1; min-width: 0;
|
||||
padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 14px;
|
||||
}
|
||||
|
||||
.nsfw-btn {
|
||||
flex-shrink: 0;
|
||||
padding: 8px 10px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-hint, #888); font-size: 13px; font-weight: 600;
|
||||
cursor: pointer; transition: background .15s, color .15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.nsfw-btn--active {
|
||||
background: var(--tg-button, #2196f3);
|
||||
color: var(--tg-btn-text, #fff);
|
||||
}
|
||||
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Api.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет подпись, которую бот вкладывает в URL Mini App при inline-режиме.
|
||||
/// Telegram не предоставляет initData через InlineQueryResultsButton,
|
||||
/// поэтому используем собственную схему:
|
||||
/// sign = HMAC-SHA256(jwt_secret_key, "{userId}:{signedAt}")
|
||||
/// Окно свежести — 60 секунд (то же, что у TelegramInitDataValidator).
|
||||
/// </summary>
|
||||
public sealed class InlineAuthValidator(IOptions<JwtOptions> options)
|
||||
{
|
||||
private static readonly TimeSpan MaxAge = TimeSpan.FromSeconds(60);
|
||||
|
||||
public bool TryValidate(long userId, long signedAt, string sign)
|
||||
{
|
||||
// Проверка свежести
|
||||
var authDate = DateTimeOffset.FromUnixTimeSeconds(signedAt);
|
||||
if (DateTimeOffset.UtcNow - authDate > MaxAge)
|
||||
return false;
|
||||
|
||||
// Ожидаемая подпись
|
||||
var data = $"{userId}:{signedAt}";
|
||||
var key = Encoding.UTF8.GetBytes(options.Value.SecretKey);
|
||||
var expectedHash = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(data));
|
||||
var expectedHex = Convert.ToHexString(expectedHash).ToLowerInvariant();
|
||||
|
||||
// Constant-time сравнение
|
||||
return CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(expectedHex),
|
||||
Encoding.UTF8.GetBytes(sign.ToLowerInvariant()));
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,10 @@ namespace MemeVault.Api.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public sealed class AuthController(
|
||||
TelegramInitDataValidator validator,
|
||||
InlineAuthValidator inlineValidator,
|
||||
JwtTokenService jwt) : ControllerBase
|
||||
{
|
||||
/// <summary>Стандартная авторизация через Telegram initData (обычный WebApp).</summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("telegram")]
|
||||
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
||||
@@ -20,6 +22,23 @@ public sealed class AuthController(
|
||||
var token = jwt.IssueToken(userId, username);
|
||||
return Ok(new { token });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Авторизация через HMAC-подпись от бота — для inline-режима,
|
||||
/// где Telegram не передаёт initData.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("inline")]
|
||||
public IActionResult Inline([FromBody] InlineAuthRequest request)
|
||||
{
|
||||
if (!inlineValidator.TryValidate(request.UserId, request.SignedAt, request.Sign))
|
||||
return Unauthorized();
|
||||
|
||||
// username в этом режиме неизвестен — будет обновлён при следующем сообщении боту
|
||||
var token = jwt.IssueToken(request.UserId, username: null);
|
||||
return Ok(new { token });
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TelegramAuthRequest(string InitData);
|
||||
public sealed record InlineAuthRequest(long UserId, long SignedAt, string Sign);
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using MemeVault.Api.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace MemeVault.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/bot")]
|
||||
public sealed class BotController(BotInfoService botInfo) : ControllerBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Возвращает публичный username бота.
|
||||
/// Не требует авторизации — username бота публичен.
|
||||
/// </summary>
|
||||
[HttpGet("info")]
|
||||
public async Task<IActionResult> GetInfo(CancellationToken ct)
|
||||
{
|
||||
var username = await botInfo.GetBotUsernameAsync();
|
||||
return Ok(new { username });
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using MemeVault.Api.Middleware;
|
||||
using MemeVault.Api.Auth;
|
||||
using MemeVault.Api.Services;
|
||||
using System.Text;
|
||||
using MemeVault.Api.Options;
|
||||
using MemeVault.Infrastructure;
|
||||
@@ -27,7 +28,9 @@ builder.Services.Configure<JwtOptions>(
|
||||
builder.Configuration.GetSection(JwtOptions.Section));
|
||||
|
||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||
builder.Services.AddSingleton<InlineAuthValidator>();
|
||||
builder.Services.AddSingleton<JwtTokenService>();
|
||||
builder.Services.AddSingleton<BotInfoService>();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<CurrentUser>();
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
using Telegram.Bot;
|
||||
|
||||
namespace MemeVault.Api.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Кэширует username бота на весь lifetime процесса.
|
||||
/// GetMeAsync вызывается ровно один раз при первом обращении.
|
||||
/// </summary>
|
||||
public sealed class BotInfoService
|
||||
{
|
||||
private readonly Lazy<Task<string>> _username;
|
||||
|
||||
public BotInfoService(ITelegramBotClient botClient)
|
||||
{
|
||||
_username = new Lazy<Task<string>>(
|
||||
() => FetchAsync(botClient),
|
||||
LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
}
|
||||
|
||||
private static async Task<string> FetchAsync(ITelegramBotClient botClient)
|
||||
{
|
||||
var me = await botClient.GetMe();
|
||||
return me.Username ?? string.Empty;
|
||||
}
|
||||
|
||||
public Task<string> GetBotUsernameAsync() => _username.Value;
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -15,5 +15,6 @@ public sealed record CollectionDto(
|
||||
bool IsNsfw,
|
||||
string? ShareToken,
|
||||
int ItemCount,
|
||||
DateTimeOffset CreatedAt
|
||||
DateTimeOffset CreatedAt,
|
||||
CollectionRole MyRole
|
||||
);
|
||||
|
||||
+3
-1
@@ -1,4 +1,5 @@
|
||||
using MediatR;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetUserCollections;
|
||||
@@ -35,7 +36,8 @@ public sealed class GetUserCollectionsQueryHandler(
|
||||
c.IsNsfw,
|
||||
c.ShareToken,
|
||||
countByCollection.GetValueOrDefault(c.Id, 0),
|
||||
c.CreatedAt
|
||||
c.CreatedAt,
|
||||
c.GetRole(request.OwnerTelegramId) ?? CollectionRole.Viewer
|
||||
)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using MemeVault.Bot.Options;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MemeVault.Bot.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует параметры авторизации для передачи в URL Mini App в inline-режиме.
|
||||
/// Telegram не предоставляет initData при открытии через InlineQueryResultsButton,
|
||||
/// поэтому бот самостоятельно подписывает userId + timestamp секретным ключом.
|
||||
///
|
||||
/// Схема: sign = HMAC-SHA256(jwt_secret_key, "{userId}:{signedAt}")
|
||||
/// </summary>
|
||||
public sealed class BotInlineSigner(IOptions<JwtOptions> options)
|
||||
{
|
||||
public (long UserId, long SignedAt, string Sign) CreateParams(long telegramUserId)
|
||||
{
|
||||
var signedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
var data = $"{telegramUserId}:{signedAt}";
|
||||
var key = Encoding.UTF8.GetBytes(options.Value.SecretKey);
|
||||
var hash = HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(data));
|
||||
var sign = Convert.ToHexString(hash).ToLowerInvariant();
|
||||
return (telegramUserId, signedAt, sign);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace MemeVault.Bot.Options;
|
||||
|
||||
public sealed class JwtOptions
|
||||
{
|
||||
public const string Section = "Jwt";
|
||||
|
||||
public string SecretKey { get; set; } = string.Empty;
|
||||
public string Issuer { get; set; } = "memevault-api";
|
||||
public string Audience { get; set; } = "memevault-miniapp";
|
||||
public int ExpiryHours { get; set; } = 24;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using MemeVault.Bot.Auth;
|
||||
using MemeVault.Bot.Telemetry;
|
||||
using Prometheus;
|
||||
using MemeVault.Bot.Options;
|
||||
@@ -22,7 +23,8 @@ builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddSingleton<BotMetrics>();
|
||||
|
||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
||||
|
||||
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.Section));
|
||||
builder.Services.AddSingleton<BotInlineSigner>();
|
||||
|
||||
builder.Services.AddScoped<MessageHandler>();
|
||||
builder.Services.AddScoped<InlineQueryHandler>();
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Queries.GetMediaItem;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using MemeVault.Bot.Auth;
|
||||
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 +12,115 @@ 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
|
||||
{
|
||||
// cacheTime для результатов поиска (секунды).
|
||||
// Если кэш инлайна мешает тестированию — уменьшить или поставить 0.
|
||||
private const int SearchCacheTime = 10;
|
||||
|
||||
// cacheTime для точечной отправки — всегда 0, результат персональный.
|
||||
private const int SendCacheTime = 0;
|
||||
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ITelegramBotClient _bot;
|
||||
private readonly BotOptions _options;
|
||||
private readonly BotInlineSigner _signer;
|
||||
|
||||
public InlineQueryHandler(IMediator mediator, ITelegramBotClient bot)
|
||||
public InlineQueryHandler(
|
||||
IMediator mediator,
|
||||
ITelegramBotClient bot,
|
||||
IOptions<BotOptions> options,
|
||||
BotInlineSigner signer)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_bot = bot;
|
||||
_options = options.Value;
|
||||
_signer = signer;
|
||||
}
|
||||
|
||||
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: SendCacheTime,
|
||||
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-режиме.
|
||||
// Telegram не предоставляет initData в этом режиме, поэтому бот подписывает
|
||||
// userId + timestamp и передаёт в query-строке для обмена на JWT.
|
||||
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
||||
? null
|
||||
: BuildButton(userId);
|
||||
|
||||
await _bot.AnswerInlineQuery(
|
||||
inlineQuery.Id,
|
||||
queryId,
|
||||
answers,
|
||||
cacheTime: 10,
|
||||
button: button,
|
||||
cacheTime: SearchCacheTime,
|
||||
isPersonal: true,
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Кнопка Mini App ──────────────────────────────────────────────────────
|
||||
|
||||
private InlineQueryResultsButton BuildButton(long userId)
|
||||
{
|
||||
var (uid, ts, sign) = _signer.CreateParams(userId);
|
||||
var url = $"{_options.MiniAppUrl}?mode=inline&user_id={uid}&signed_at={ts}&sign={sign}";
|
||||
|
||||
return new InlineQueryResultsButton
|
||||
{
|
||||
Text = "Открыть MemeVault",
|
||||
WebApp = new WebAppInfo { Url = url },
|
||||
};
|
||||
}
|
||||
|
||||
// ── Конвертер ────────────────────────────────────────────────────────────
|
||||
|
||||
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
@@ -51,8 +133,8 @@ public sealed class InlineQueryHandler
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
@@ -61,7 +143,7 @@ public sealed class InlineQueryHandler
|
||||
item.FileId!,
|
||||
title: item.InlineTitle ?? item.Caption ?? "Video")
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Caption = item.Caption,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
@@ -70,7 +152,7 @@ public sealed class InlineQueryHandler
|
||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Title = item.InlineTitle,
|
||||
},
|
||||
|
||||
MediaType.Text => new InlineQueryResultArticle(
|
||||
|
||||
@@ -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