Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d58fff4a7 | ||
|
|
f67a544d7a | ||
|
|
8169b6474a |
+34
-9
@@ -15,12 +15,23 @@
|
|||||||
let authing = true
|
let authing = true
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Читает #token=<jwt> из хэш-фрагмента URL.
|
* Возвращает параметры inline-авторизации из query-строки URL,
|
||||||
* Используется в двух случаях:
|
* если они были переданы ботом (?user_id=...&signed_at=...&sign=...).
|
||||||
* • dev-режим: вручную вставить #token=... для тестирования без Telegram
|
|
||||||
* • inline-режим (прод): бот передаёт JWT в хэше, т.к. Telegram не даёт initData
|
|
||||||
*/
|
*/
|
||||||
function tokenFromHash() {
|
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))
|
const params = new URLSearchParams(window.location.hash.slice(1))
|
||||||
return params.get('token') ?? null
|
return params.get('token') ?? null
|
||||||
}
|
}
|
||||||
@@ -28,14 +39,28 @@
|
|||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
applyTheme()
|
applyTheme()
|
||||||
|
|
||||||
// JWT из хэша: dev-режим или inline-кнопка от бота
|
// Dev-режим: #token=<jwt>
|
||||||
const hashToken = tokenFromHash()
|
const devToken = devTokenFromHash()
|
||||||
if (hashToken) {
|
if (devToken) {
|
||||||
jwt.set(hashToken)
|
jwt.set(devToken)
|
||||||
authing = false
|
authing = false
|
||||||
return
|
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 заполняет её)
|
// Обычный WebApp: авторизация через initData (Telegram заполняет её)
|
||||||
try {
|
try {
|
||||||
const { token } = await api.auth(initData)
|
const { token } = await api.auth(initData)
|
||||||
|
|||||||
@@ -33,7 +33,8 @@ async function request(method, path, body) {
|
|||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
// ── 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 ────────────────────────────────────────────────────────────────────
|
// ── Me ────────────────────────────────────────────────────────────────────
|
||||||
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
||||||
@@ -65,6 +66,9 @@ export const api = {
|
|||||||
joinCollection: (id) => request('POST', `/collections/${id}/join`),
|
joinCollection: (id) => request('POST', `/collections/${id}/join`),
|
||||||
regenerateShareLink: (id) => request('POST', `/collections/${id}/share-link/regenerate`),
|
regenerateShareLink: (id) => request('POST', `/collections/${id}/share-link/regenerate`),
|
||||||
|
|
||||||
|
// ── Bot ───────────────────────────────────────────────────────────────────
|
||||||
|
getBotInfo: () => request('GET', '/bot/info'),
|
||||||
|
|
||||||
// ── Invites ───────────────────────────────────────────────────────────────
|
// ── Invites ───────────────────────────────────────────────────────────────
|
||||||
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
||||||
createInvite: (collectionId, role, expiresAt) =>
|
createInvite: (collectionId, role, expiresAt) =>
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
<script>
|
<script>
|
||||||
import { onMount } from 'svelte'
|
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 { api } from '../lib/api.js'
|
||||||
import { showAlert } from '../lib/telegram.js'
|
import { showAlert } from '../lib/telegram.js'
|
||||||
|
|
||||||
|
let botUsername = $state('')
|
||||||
|
|
||||||
let collections = $state([])
|
let collections = $state([])
|
||||||
let loading = $state(true)
|
let loading = $state(true)
|
||||||
let error = $state(null)
|
let error = $state(null)
|
||||||
@@ -23,9 +25,35 @@
|
|||||||
// Клонирование: id коллекции, которая клонируется прямо сейчас
|
// Клонирование: id коллекции, которая клонируется прямо сейчас
|
||||||
let cloning = $state(null)
|
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 deleteTarget = $derived(collections.find(c => c.id === confirmDelete))
|
||||||
let inboxTarget = $derived(collections.find(c => c.id === confirmInbox))
|
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() {
|
async function load() {
|
||||||
loading = true; error = null
|
loading = true; error = null
|
||||||
try { collections = await api.getCollections() }
|
try { collections = await api.getCollections() }
|
||||||
@@ -50,6 +78,7 @@
|
|||||||
itemCount: 0,
|
itemCount: 0,
|
||||||
visibility: 0,
|
visibility: 0,
|
||||||
shareToken: null,
|
shareToken: null,
|
||||||
|
myRole: ROLE_OWNER,
|
||||||
createdAt: new Date().toISOString(),
|
createdAt: new Date().toISOString(),
|
||||||
}]
|
}]
|
||||||
} catch (e) {
|
} 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>
|
</script>
|
||||||
|
|
||||||
<div class="page">
|
<div class="page">
|
||||||
@@ -208,6 +317,16 @@
|
|||||||
>
|
>
|
||||||
<Copy size={16}/>
|
<Copy size={16}/>
|
||||||
</button>
|
</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}
|
{#if !col.isInbox}
|
||||||
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
||||||
<Pencil size={16}/>
|
<Pencil size={16}/>
|
||||||
@@ -223,6 +342,91 @@
|
|||||||
</div>
|
</div>
|
||||||
</li>
|
</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}
|
{#if confirmDelete === col.id && deleteTarget}
|
||||||
<li class="confirm-panel">
|
<li class="confirm-panel">
|
||||||
@@ -335,6 +539,9 @@
|
|||||||
.icon-btn.nsfw { color: var(--tg-hint, #999); }
|
.icon-btn.nsfw { color: var(--tg-hint, #999); }
|
||||||
.icon-btn.nsfw:hover { color: #e53935; background: var(--tg-secondary-bg, #e8e8e8); }
|
.icon-btn.nsfw:hover { color: #e53935; background: var(--tg-secondary-bg, #e8e8e8); }
|
||||||
.icon-btn.nsfw--on { color: #e53935; }
|
.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 {
|
.confirm-panel {
|
||||||
@@ -353,4 +560,97 @@
|
|||||||
.btn-primary { background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #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 { background: none; color: var(--tg-hint, #888); }
|
||||||
.btn-ghost:hover { background: var(--tg-secondary-bg, #e8e8e8); }
|
.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>
|
</style>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
|
|
||||||
let items = $state([])
|
let items = $state([])
|
||||||
let query = $state('')
|
let query = $state('')
|
||||||
|
let includeNsfw = $state(false)
|
||||||
let loading = $state(true)
|
let loading = $state(true)
|
||||||
let error = $state(null)
|
let error = $state(null)
|
||||||
let sending = $state(null) // id медиа, которое сейчас отправляется
|
let sending = $state(null) // id медиа, которое сейчас отправляется
|
||||||
@@ -26,7 +27,7 @@
|
|||||||
async function load() {
|
async function load() {
|
||||||
loading = true; error = null; previews = {}
|
loading = true; error = null; previews = {}
|
||||||
try {
|
try {
|
||||||
items = await api.getMedia(query)
|
items = await api.getMedia(query, includeNsfw)
|
||||||
for (const item of items) {
|
for (const item of items) {
|
||||||
if (PREVIEWABLE.has(item.mediaType)) loadPreview(item.id)
|
if (PREVIEWABLE.has(item.mediaType)) loadPreview(item.id)
|
||||||
}
|
}
|
||||||
@@ -76,6 +77,11 @@
|
|||||||
searchTimer = setTimeout(load, 400)
|
searchTimer = setTimeout(load, 400)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toggleNsfw() {
|
||||||
|
includeNsfw = !includeNsfw
|
||||||
|
load()
|
||||||
|
}
|
||||||
|
|
||||||
onMount(load)
|
onMount(load)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -96,12 +102,20 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<input
|
<div class="search-row">
|
||||||
class="search"
|
<input
|
||||||
placeholder="Поиск: #мем -#кот слово"
|
class="search"
|
||||||
bind:value={query}
|
placeholder="Поиск: #мем -#кот слово"
|
||||||
oninput={onSearch}
|
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}
|
{#if loading}
|
||||||
<div class="hint">Загрузка…</div>
|
<div class="hint">Загрузка…</div>
|
||||||
@@ -180,13 +194,30 @@
|
|||||||
}
|
}
|
||||||
.chat-name :global(svg) { flex-shrink: 0; color: var(--tg-hint, #888); }
|
.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 {
|
.search {
|
||||||
margin: 4px 8px 6px; width: calc(100% - 16px);
|
flex: 1; min-width: 0;
|
||||||
padding: 8px 12px; border-radius: 8px; border: none;
|
padding: 8px 12px; border-radius: 8px; border: none;
|
||||||
background: var(--tg-secondary-bg, #f0f0f0);
|
background: var(--tg-secondary-bg, #f0f0f0);
|
||||||
color: var(--tg-text, #000); font-size: 14px;
|
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); }
|
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||||
.error { color: #e53935; }
|
.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]")]
|
[Route("api/[controller]")]
|
||||||
public sealed class AuthController(
|
public sealed class AuthController(
|
||||||
TelegramInitDataValidator validator,
|
TelegramInitDataValidator validator,
|
||||||
|
InlineAuthValidator inlineValidator,
|
||||||
JwtTokenService jwt) : ControllerBase
|
JwtTokenService jwt) : ControllerBase
|
||||||
{
|
{
|
||||||
|
/// <summary>Стандартная авторизация через Telegram initData (обычный WebApp).</summary>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("telegram")]
|
[HttpPost("telegram")]
|
||||||
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
public IActionResult Telegram([FromBody] TelegramAuthRequest request)
|
||||||
@@ -20,6 +22,23 @@ public sealed class AuthController(
|
|||||||
var token = jwt.IssueToken(userId, username);
|
var token = jwt.IssueToken(userId, username);
|
||||||
return Ok(new { token });
|
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 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.Middleware;
|
||||||
using MemeVault.Api.Auth;
|
using MemeVault.Api.Auth;
|
||||||
|
using MemeVault.Api.Services;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using MemeVault.Api.Options;
|
using MemeVault.Api.Options;
|
||||||
using MemeVault.Infrastructure;
|
using MemeVault.Infrastructure;
|
||||||
@@ -27,7 +28,9 @@ builder.Services.Configure<JwtOptions>(
|
|||||||
builder.Configuration.GetSection(JwtOptions.Section));
|
builder.Configuration.GetSection(JwtOptions.Section));
|
||||||
|
|
||||||
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
builder.Services.AddSingleton<TelegramInitDataValidator>();
|
||||||
|
builder.Services.AddSingleton<InlineAuthValidator>();
|
||||||
builder.Services.AddSingleton<JwtTokenService>();
|
builder.Services.AddSingleton<JwtTokenService>();
|
||||||
|
builder.Services.AddSingleton<BotInfoService>();
|
||||||
builder.Services.AddHttpContextAccessor();
|
builder.Services.AddHttpContextAccessor();
|
||||||
builder.Services.AddScoped<CurrentUser>();
|
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;
|
||||||
|
}
|
||||||
@@ -15,5 +15,6 @@ public sealed record CollectionDto(
|
|||||||
bool IsNsfw,
|
bool IsNsfw,
|
||||||
string? ShareToken,
|
string? ShareToken,
|
||||||
int ItemCount,
|
int ItemCount,
|
||||||
DateTimeOffset CreatedAt
|
DateTimeOffset CreatedAt,
|
||||||
|
CollectionRole MyRole
|
||||||
);
|
);
|
||||||
|
|||||||
+3
-1
@@ -1,4 +1,5 @@
|
|||||||
using MediatR;
|
using MediatR;
|
||||||
|
using MemeVault.Domain.Enums;
|
||||||
using MemeVault.Domain.Repositories;
|
using MemeVault.Domain.Repositories;
|
||||||
|
|
||||||
namespace MemeVault.Application.Queries.GetUserCollections;
|
namespace MemeVault.Application.Queries.GetUserCollections;
|
||||||
@@ -35,7 +36,8 @@ public sealed class GetUserCollectionsQueryHandler(
|
|||||||
c.IsNsfw,
|
c.IsNsfw,
|
||||||
c.ShareToken,
|
c.ShareToken,
|
||||||
countByCollection.GetValueOrDefault(c.Id, 0),
|
countByCollection.GetValueOrDefault(c.Id, 0),
|
||||||
c.CreatedAt
|
c.CreatedAt,
|
||||||
|
c.GetRole(request.OwnerTelegramId) ?? CollectionRole.Viewer
|
||||||
)).ToList();
|
)).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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
using System.IdentityModel.Tokens.Jwt;
|
|
||||||
using System.Security.Claims;
|
|
||||||
using System.Text;
|
|
||||||
using MemeVault.Bot.Options;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using Microsoft.IdentityModel.Tokens;
|
|
||||||
|
|
||||||
namespace MemeVault.Bot.Auth;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Выдаёт JWT для передачи в Mini App через хэш-фрагмент URL.
|
|
||||||
/// Используется только в inline-режиме, где Telegram не предоставляет initData.
|
|
||||||
/// </summary>
|
|
||||||
public sealed class BotJwtTokenService(IOptions<JwtOptions> options)
|
|
||||||
{
|
|
||||||
public string IssueToken(long telegramUserId, string? username)
|
|
||||||
{
|
|
||||||
var opt = options.Value;
|
|
||||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(opt.SecretKey));
|
|
||||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
||||||
|
|
||||||
var claims = new List<Claim>
|
|
||||||
{
|
|
||||||
new(JwtRegisteredClaimNames.Sub, telegramUserId.ToString()),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(username))
|
|
||||||
claims.Add(new Claim(JwtRegisteredClaimNames.Name, username));
|
|
||||||
|
|
||||||
var token = new JwtSecurityToken(
|
|
||||||
issuer: opt.Issuer,
|
|
||||||
audience: opt.Audience,
|
|
||||||
claims: claims,
|
|
||||||
notBefore: DateTime.UtcNow,
|
|
||||||
expires: DateTime.UtcNow.AddHours(opt.ExpiryHours),
|
|
||||||
signingCredentials: creds);
|
|
||||||
|
|
||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,6 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.10.3.2" />
|
<PackageReference Include="Telegram.Bot" Version="22.10.3.2" />
|
||||||
<PackageReference Include="MediatR" Version="12.4.1" />
|
<PackageReference Include="MediatR" Version="12.4.1" />
|
||||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.4.0" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ builder.Services.AddSingleton<BotMetrics>();
|
|||||||
|
|
||||||
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
builder.Services.Configure<BotOptions>(builder.Configuration.GetSection(BotOptions.Section));
|
||||||
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.Section));
|
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection(JwtOptions.Section));
|
||||||
builder.Services.AddSingleton<BotJwtTokenService>();
|
builder.Services.AddSingleton<BotInlineSigner>();
|
||||||
|
|
||||||
builder.Services.AddScoped<MessageHandler>();
|
builder.Services.AddScoped<MessageHandler>();
|
||||||
builder.Services.AddScoped<InlineQueryHandler>();
|
builder.Services.AddScoped<InlineQueryHandler>();
|
||||||
|
|||||||
@@ -18,26 +18,33 @@ namespace MemeVault.Bot.Telegram.InlineMode;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class InlineQueryHandler
|
public sealed class InlineQueryHandler
|
||||||
{
|
{
|
||||||
|
// cacheTime для результатов поиска (секунды).
|
||||||
|
// Если кэш инлайна мешает тестированию — уменьшить или поставить 0.
|
||||||
|
private const int SearchCacheTime = 10;
|
||||||
|
|
||||||
|
// cacheTime для точечной отправки — всегда 0, результат персональный.
|
||||||
|
private const int SendCacheTime = 0;
|
||||||
|
|
||||||
private readonly IMediator _mediator;
|
private readonly IMediator _mediator;
|
||||||
private readonly ITelegramBotClient _bot;
|
private readonly ITelegramBotClient _bot;
|
||||||
private readonly BotOptions _options;
|
private readonly BotOptions _options;
|
||||||
private readonly BotJwtTokenService _jwt;
|
private readonly BotInlineSigner _signer;
|
||||||
|
|
||||||
public InlineQueryHandler(
|
public InlineQueryHandler(
|
||||||
IMediator mediator,
|
IMediator mediator,
|
||||||
ITelegramBotClient bot,
|
ITelegramBotClient bot,
|
||||||
IOptions<BotOptions> options,
|
IOptions<BotOptions> options,
|
||||||
BotJwtTokenService jwt)
|
BotInlineSigner signer)
|
||||||
{
|
{
|
||||||
_mediator = mediator;
|
_mediator = mediator;
|
||||||
_bot = bot;
|
_bot = bot;
|
||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
_jwt = jwt;
|
_signer = signer;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var userId = inlineQuery.From.Id;
|
var userId = inlineQuery.From.Id;
|
||||||
var rawQuery = inlineQuery.Query ?? string.Empty;
|
var rawQuery = inlineQuery.Query ?? string.Empty;
|
||||||
|
|
||||||
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
// Режим точечной отправки: Mini App выбрала конкретный элемент
|
||||||
@@ -49,7 +56,7 @@ public sealed class InlineQueryHandler
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Обычный поиск
|
// Обычный поиск
|
||||||
await HandleSearchAsync(inlineQuery, userId, rawQuery, ct);
|
await HandleSearchAsync(inlineQuery.Id, userId, rawQuery, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Точечная отправка ────────────────────────────────────────────────────
|
// ── Точечная отправка ────────────────────────────────────────────────────
|
||||||
@@ -65,14 +72,14 @@ public sealed class InlineQueryHandler
|
|||||||
await _bot.AnswerInlineQuery(
|
await _bot.AnswerInlineQuery(
|
||||||
queryId,
|
queryId,
|
||||||
answers.OfType<InlineQueryResult>(),
|
answers.OfType<InlineQueryResult>(),
|
||||||
cacheTime: 0,
|
cacheTime: SendCacheTime,
|
||||||
isPersonal: true,
|
isPersonal: true,
|
||||||
cancellationToken: ct);
|
cancellationToken: ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Поиск ────────────────────────────────────────────────────────────────
|
// ── Поиск ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
private async Task HandleSearchAsync(InlineQuery inlineQuery, long userId, string rawQuery, CancellationToken ct)
|
private async Task HandleSearchAsync(string queryId, long userId, string rawQuery, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var results = await _mediator.Send(
|
var results = await _mediator.Send(
|
||||||
new SearchMediaQuery(userId, rawQuery, Limit: 10, IncludeNsfw: false), ct);
|
new SearchMediaQuery(userId, rawQuery, Limit: 10, IncludeNsfw: false), ct);
|
||||||
@@ -83,30 +90,35 @@ public sealed class InlineQueryHandler
|
|||||||
.ToArray();
|
.ToArray();
|
||||||
|
|
||||||
// Кнопка над результатами — открывает Mini App в inline-режиме.
|
// Кнопка над результатами — открывает Mini App в inline-режиме.
|
||||||
// JWT передаётся в хэш-фрагменте (#token=…), чтобы не попадал в серверные логи.
|
// Telegram не предоставляет initData в этом режиме, поэтому бот подписывает
|
||||||
// Telegram не предоставляет initData в inline-режиме, поэтому используем JWT.
|
// userId + timestamp и передаёт в query-строке для обмена на JWT.
|
||||||
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
InlineQueryResultsButton? button = string.IsNullOrEmpty(_options.MiniAppUrl)
|
||||||
? null
|
? null
|
||||||
: new InlineQueryResultsButton
|
: BuildButton(userId);
|
||||||
{
|
|
||||||
Text = "Открыть MemeVault",
|
|
||||||
WebApp = new WebAppInfo
|
|
||||||
{
|
|
||||||
Url = _options.MiniAppUrl
|
|
||||||
+ "?mode=inline"
|
|
||||||
+ "#token=" + _jwt.IssueToken(userId, inlineQuery.From.Username)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
await _bot.AnswerInlineQuery(
|
await _bot.AnswerInlineQuery(
|
||||||
inlineQuery.Id,
|
queryId,
|
||||||
answers,
|
answers,
|
||||||
button: button,
|
button: button,
|
||||||
cacheTime: 10,
|
cacheTime: SearchCacheTime,
|
||||||
isPersonal: true,
|
isPersonal: true,
|
||||||
cancellationToken: ct);
|
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)
|
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||||||
@@ -121,8 +133,8 @@ public sealed class InlineQueryHandler
|
|||||||
{
|
{
|
||||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Title = item.InlineTitle,
|
Title = item.InlineTitle,
|
||||||
Description = item.InlineDescription ?? tagsLine,
|
Description = item.InlineDescription ?? tagsLine,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -131,7 +143,7 @@ public sealed class InlineQueryHandler
|
|||||||
item.FileId!,
|
item.FileId!,
|
||||||
title: item.InlineTitle ?? item.Caption ?? "Video")
|
title: item.InlineTitle ?? item.Caption ?? "Video")
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Description = item.InlineDescription ?? tagsLine,
|
Description = item.InlineDescription ?? tagsLine,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -140,7 +152,7 @@ public sealed class InlineQueryHandler
|
|||||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||||||
{
|
{
|
||||||
Caption = item.Caption,
|
Caption = item.Caption,
|
||||||
Title = item.InlineTitle,
|
Title = item.InlineTitle,
|
||||||
},
|
},
|
||||||
|
|
||||||
MediaType.Text => new InlineQueryResultArticle(
|
MediaType.Text => new InlineQueryResultArticle(
|
||||||
|
|||||||
Reference in New Issue
Block a user