too many changes
This commit is contained in:
+15
-3
@@ -2,9 +2,13 @@
|
||||
import { onMount } from 'svelte'
|
||||
import { jwt, isAuthed } from './stores/auth.js'
|
||||
import { api } from './lib/api.js'
|
||||
import { initData, applyTheme } from './lib/telegram.js'
|
||||
import { initData, applyTheme, isAttachmentMode } 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()
|
||||
|
||||
let tab = 'media' // 'media' | 'collections'
|
||||
let authError = null
|
||||
@@ -44,9 +48,15 @@
|
||||
{:else if authError}
|
||||
<div class="splash error">Ошибка авторизации:<br/>{authError}</div>
|
||||
{:else if $isAuthed}
|
||||
|
||||
{#if sendMode}
|
||||
<!-- ── Режим отправки: только поиск и листинг ───────────────────────── -->
|
||||
<SendPage />
|
||||
{:else}
|
||||
<!-- ── Режим управления: полный интерфейс с вкладками ──────────────── -->
|
||||
<nav>
|
||||
<button class:active={tab === 'media'} on:click={() => (tab = 'media')}>Медиа</button>
|
||||
<button class:active={tab === 'collections'} on:click={() => (tab = 'collections')}>Коллекции</button>
|
||||
<button class:active={tab === 'media'} onclick={() => (tab = 'media')}>Медиа</button>
|
||||
<button class:active={tab === 'collections'} onclick={() => (tab = 'collections')}>Коллекции</button>
|
||||
</nav>
|
||||
|
||||
{#if tab === 'media'}
|
||||
@@ -55,6 +65,8 @@
|
||||
<CollectionsPage />
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{/if}
|
||||
</main>
|
||||
|
||||
<style>
|
||||
|
||||
+30
-5
@@ -15,6 +15,14 @@ async function request(method, path, body) {
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const errCt = res.headers.get('content-type') ?? ''
|
||||
if (errCt.includes('json')) {
|
||||
const body = await res.json().catch(() => null)
|
||||
const err = new Error(body?.detail ?? body?.title ?? `${res.status}`)
|
||||
err.errorCode = body?.extensions?.errorCode ?? body?.errorCode ?? null
|
||||
err.status = res.status
|
||||
throw err
|
||||
}
|
||||
const text = await res.text()
|
||||
throw new Error(`${res.status}: ${text}`)
|
||||
}
|
||||
@@ -27,23 +35,40 @@ export const api = {
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
auth: (initData) => request('POST', '/auth/telegram', { initData }),
|
||||
|
||||
// ── Me ────────────────────────────────────────────────────────────────────
|
||||
// GET /api/me → { telegramId, username, firstName, inboxCollectionId }
|
||||
getMe: () => request('GET', '/me'),
|
||||
// PATCH /api/me { inboxCollectionId } → 204
|
||||
setInboxCollection: (collectionId) => request('PATCH', '/me', { inboxCollectionId: collectionId }),
|
||||
|
||||
// ── Media ─────────────────────────────────────────────────────────────────
|
||||
getMedia: (q) => request('GET', `/media${q ? `?q=${encodeURIComponent(q)}` : ''}`),
|
||||
createText: (caption, tags) => request('POST', '/media', { caption, tags }),
|
||||
getMedia: (q, includeNsfw = false) => {
|
||||
const params = new URLSearchParams({ includeNsfw })
|
||||
if (q) params.set('q', q)
|
||||
return request('GET', `/media?${params}`)
|
||||
},
|
||||
getDownloadUrl: (id) => request('GET', `/media/${id}/download-url`).then((r) => r?.url),
|
||||
sendToChat: (id, queryId) => request('POST', `/media/${id}/send`, { queryId }),
|
||||
updateMedia: (id, patch) => request('PATCH', `/media/${id}`, patch),
|
||||
deleteMedia: (id) => request('DELETE', `/media/${id}`),
|
||||
copyMedia: (id, targetCollectionId) => request('POST', `/media/${id}/copy`, { targetCollectionId }),
|
||||
|
||||
// ── Collections ───────────────────────────────────────────────────────────
|
||||
getCollections: () => request('GET', '/collections'),
|
||||
createCollection: (name, description) => request('POST', '/collections', { name, description }),
|
||||
updateCollection: (id, name, description) => request('PATCH', `/collections/${id}`, { name, description }),
|
||||
// patch: { name, description?, isNsfw?, visibility? } → { shareToken }
|
||||
updateCollection: (id, patch) => request('PATCH', `/collections/${id}`, patch),
|
||||
deleteCollection: (id) => request('DELETE', `/collections/${id}`),
|
||||
setCollectionInbox: (id) => request('PUT', `/collections/${id}/inbox`),
|
||||
getCollectionItems: (id) => request('GET', `/collections/${id}/items`),
|
||||
cloneCollection: (id) => request('POST', `/collections/${id}/clone`),
|
||||
joinCollection: (id) => request('POST', `/collections/${id}/join`),
|
||||
regenerateShareLink: (id) => request('POST', `/collections/${id}/share-link/regenerate`),
|
||||
|
||||
// ── Invites ───────────────────────────────────────────────────────────────
|
||||
getInvites: (collectionId) => request('GET', `/collections/${collectionId}/invites`),
|
||||
createInvite: (collectionId, role) => request('POST', `/collections/${collectionId}/invites`, { role }),
|
||||
revokeInvite: (collectionId, inviteId) => request('DELETE', `/collections/${collectionId}/invites/${inviteId}`),
|
||||
createInvite: (collectionId, role, expiresAt) =>
|
||||
request('POST', `/collections/${collectionId}/invites`, { role, expiresAt }),
|
||||
revokeInvite: (collectionId, inviteId) =>
|
||||
request('DELETE', `/collections/${collectionId}/invites/${inviteId}`),
|
||||
}
|
||||
|
||||
@@ -16,10 +16,50 @@ export const close = () => tg?.close()
|
||||
export const getQueryId = () => tg?.initDataUnsafe?.query_id ?? null
|
||||
export const isAttachmentMode = () => !!getQueryId()
|
||||
|
||||
/** Показать нативный алерт Telegram, или fallback на browser alert вне TG-контекста */
|
||||
/**
|
||||
* Имя чата/собеседника, в который будет отправлено медиа.
|
||||
* - Личный чат → receiver.first_name (+ last_name если есть)
|
||||
* - Группа/канал → chat.title
|
||||
* Возвращает null, если информации нет.
|
||||
*/
|
||||
export function getChatName() {
|
||||
const d = tg?.initDataUnsafe
|
||||
if (!d) return null
|
||||
if (d.receiver) {
|
||||
const name = [d.receiver.first_name, d.receiver.last_name].filter(Boolean).join(' ')
|
||||
return name || d.receiver.username || null
|
||||
}
|
||||
if (d.chat) return d.chat.title ?? null
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Тип чата, в который будет отправлено медиа.
|
||||
* - 'private' → личный чат (есть receiver)
|
||||
* - 'group' → группа
|
||||
* - 'supergroup' → супергруппа
|
||||
* - 'channel' → канал
|
||||
* - null → неизвестно
|
||||
*/
|
||||
export function getChatType() {
|
||||
const d = tg?.initDataUnsafe
|
||||
if (!d) return null
|
||||
if (d.receiver) return 'private'
|
||||
if (d.chat?.type) return d.chat.type // 'group' | 'supergroup' | 'channel'
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Показать нативный алерт Telegram.
|
||||
* Если WebApp не поддерживает метод (версия < 6.1) или контекст — обычный браузер,
|
||||
* падаем на стандартный window.alert.
|
||||
*/
|
||||
export const showAlert = (msg) => {
|
||||
if (tg?.showAlert) tg.showAlert(msg)
|
||||
else alert(msg)
|
||||
if (tg?.showAlert) {
|
||||
try { tg.showAlert(msg) } catch { alert(msg) }
|
||||
} else {
|
||||
alert(msg)
|
||||
}
|
||||
}
|
||||
|
||||
/** Применить тему Telegram к CSS-переменным */
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
// Синглтон: живёт на уровне модуля, не сбрасывается при перемонтировании компонента.
|
||||
export const urlCache = {}
|
||||
@@ -1,6 +1,6 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { Pencil, Trash2, Star, Check, X } from 'lucide-svelte'
|
||||
import { Pencil, Trash2, Star, Check, X, EyeOff, Copy } from 'lucide-svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { showAlert } from '../lib/telegram.js'
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
let error = $state(null)
|
||||
let creating = $state(false)
|
||||
let newName = $state('')
|
||||
let createError = $state(null)
|
||||
|
||||
// Inline-редактирование: { id, value }
|
||||
let editing = $state(null)
|
||||
@@ -19,8 +20,11 @@
|
||||
// Подтверждение смены Inbox: id целевой коллекции
|
||||
let confirmInbox = $state(null)
|
||||
|
||||
$derived: var deleteTarget = collections.find(c => c.id === confirmDelete)
|
||||
$derived: var inboxTarget = collections.find(c => c.id === confirmInbox)
|
||||
// Клонирование: id коллекции, которая клонируется прямо сейчас
|
||||
let cloning = $state(null)
|
||||
|
||||
let deleteTarget = $derived(collections.find(c => c.id === confirmDelete))
|
||||
let inboxTarget = $derived(collections.find(c => c.id === confirmInbox))
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null
|
||||
@@ -32,12 +36,24 @@
|
||||
async function createCollection() {
|
||||
if (!newName.trim()) return
|
||||
creating = true
|
||||
const name = newName.trim()
|
||||
createError = null
|
||||
try {
|
||||
await api.createCollection(newName.trim(), null)
|
||||
const result = await api.createCollection(name, null)
|
||||
newName = ''
|
||||
await load()
|
||||
collections = [...collections, {
|
||||
id: result.id,
|
||||
name,
|
||||
description: null,
|
||||
isInbox: false,
|
||||
isNsfw: false,
|
||||
itemCount: 0,
|
||||
visibility: 0,
|
||||
shareToken: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
}]
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
createError = e.message
|
||||
} finally { creating = false }
|
||||
}
|
||||
|
||||
@@ -49,7 +65,7 @@
|
||||
async function commitEdit() {
|
||||
if (!editing || !editing.value.trim()) { editing = null; return }
|
||||
try {
|
||||
await api.updateCollection(editing.id, editing.value.trim(), null)
|
||||
await api.updateCollection(editing.id, { name: editing.value.trim(), description: null })
|
||||
const idx = collections.findIndex(c => c.id === editing.id)
|
||||
if (idx !== -1) collections[idx] = { ...collections[idx], name: editing.value.trim() }
|
||||
editing = null
|
||||
@@ -60,6 +76,17 @@
|
||||
|
||||
function cancelEdit() { editing = null }
|
||||
|
||||
// ── NSFW ───────────────────────────────────────────────────────────────────
|
||||
async function toggleNsfw(col) {
|
||||
try {
|
||||
await api.updateCollection(col.id, { name: col.name, description: null, isNsfw: !col.isNsfw })
|
||||
const idx = collections.findIndex(c => c.id === col.id)
|
||||
if (idx !== -1) collections[idx] = { ...collections[idx], isNsfw: !col.isNsfw }
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Удаление ───────────────────────────────────────────────────────────────
|
||||
async function commitDelete() {
|
||||
if (!confirmDelete) return
|
||||
@@ -77,7 +104,7 @@
|
||||
async function commitSetInbox() {
|
||||
if (!confirmInbox) return
|
||||
try {
|
||||
await api.setCollectionInbox(confirmInbox)
|
||||
await api.setInboxCollection(confirmInbox)
|
||||
collections = collections.map(c => ({
|
||||
...c,
|
||||
isInbox: c.id === confirmInbox,
|
||||
@@ -89,11 +116,27 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ── Клонирование ───────────────────────────────────────────────────────────
|
||||
async function cloneCollection(id) {
|
||||
cloning = id
|
||||
try {
|
||||
await api.cloneCollection(id)
|
||||
await load()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
cloning = null
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
<!-- Форма создания -->
|
||||
{#if createError}
|
||||
<div class="create-error">{createError}</div>
|
||||
{/if}
|
||||
<div class="new-row">
|
||||
<input
|
||||
class="new-input"
|
||||
@@ -133,6 +176,9 @@
|
||||
{#if col.isInbox}
|
||||
<span class="badge-inbox">основная</span>
|
||||
{/if}
|
||||
{#if col.isNsfw}
|
||||
<span class="badge-nsfw">18+</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if col.itemCount > 0}
|
||||
<div class="col-meta">{col.itemCount} эл.</div>
|
||||
@@ -146,6 +192,22 @@
|
||||
<button class="icon-btn ok" onclick={commitEdit} title="Сохранить"><Check size={16}/></button>
|
||||
<button class="icon-btn cancel" onclick={cancelEdit} title="Отмена"> <X size={16}/></button>
|
||||
{:else}
|
||||
<button
|
||||
class="icon-btn nsfw"
|
||||
class:nsfw--on={col.isNsfw}
|
||||
onclick={() => toggleNsfw(col)}
|
||||
title={col.isNsfw ? 'Снять метку 18+' : 'Пометить как 18+'}
|
||||
>
|
||||
<EyeOff size={16}/>
|
||||
</button>
|
||||
<button
|
||||
class="icon-btn clone"
|
||||
onclick={() => cloneCollection(col.id)}
|
||||
disabled={cloning === col.id}
|
||||
title="Клонировать коллекцию"
|
||||
>
|
||||
<Copy size={16}/>
|
||||
</button>
|
||||
{#if !col.isInbox}
|
||||
<button class="icon-btn" onclick={() => startEdit(col)} title="Переименовать">
|
||||
<Pencil size={16}/>
|
||||
@@ -211,6 +273,10 @@
|
||||
font-size: 20px; cursor: pointer;
|
||||
}
|
||||
.btn-create:disabled { opacity: .4; cursor: default; }
|
||||
.create-error {
|
||||
margin: 0 0 6px; padding: 8px 12px; border-radius: 8px;
|
||||
background: #fdecea; color: #c62828; font-size: 13px; line-height: 1.4;
|
||||
}
|
||||
|
||||
/* Список */
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
@@ -237,6 +303,11 @@
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
border-radius: 4px; padding: 1px 5px;
|
||||
}
|
||||
.badge-nsfw {
|
||||
font-size: 11px; font-weight: 700; letter-spacing: .03em;
|
||||
background: #e53935; color: #fff;
|
||||
border-radius: 4px; padding: 1px 5px;
|
||||
}
|
||||
|
||||
/* Inline-редактор */
|
||||
.edit-input {
|
||||
@@ -257,8 +328,13 @@
|
||||
.icon-btn:hover { background: var(--tg-secondary-bg, #e8e8e8); color: var(--tg-text, #000); }
|
||||
.icon-btn.star:hover { color: #f5a623; }
|
||||
.icon-btn.del:hover { color: #e53935; }
|
||||
.icon-btn.clone:hover { color: #7e57c2; }
|
||||
.icon-btn.clone:disabled { opacity: .4; cursor: default; }
|
||||
.icon-btn.ok { color: #43a047; }
|
||||
.icon-btn.cancel { 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--on { color: #e53935; }
|
||||
|
||||
/* Подтверждение */
|
||||
.confirm-panel {
|
||||
|
||||
@@ -1,34 +1,76 @@
|
||||
<script>
|
||||
import { onMount } from 'svelte'
|
||||
import { Trash2, FolderInput, Plus, Pencil, Check, X } from 'lucide-svelte'
|
||||
import { api } from '../lib/api.js'
|
||||
import { isAttachmentMode, getQueryId, close as tgClose, showAlert } from '../lib/telegram.js'
|
||||
import { showAlert } from '../lib/telegram.js'
|
||||
import { collectionsStore } from '../stores/collections.svelte.js'
|
||||
import { urlCache } from '../lib/urlCache.js'
|
||||
|
||||
const attachMode = isAttachmentMode()
|
||||
const queryId = getQueryId()
|
||||
|
||||
// Types that have a downloadable file preview
|
||||
const PREVIEWABLE = new Set(['Photo', 'Video', 'Animation', 'Sticker'])
|
||||
|
||||
let items = []
|
||||
let query = ''
|
||||
let loading = true
|
||||
let error = null
|
||||
let items = $state([])
|
||||
let query = $state('')
|
||||
let includeNsfw = $state(false)
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
let previews = $state({})
|
||||
|
||||
// Map of itemId → { url: string|null, loading: boolean, error: boolean }
|
||||
let previews = {}
|
||||
// Создание текстовой записи
|
||||
let showCreate = $state(false)
|
||||
let newCaption = $state('')
|
||||
let newTags = $state('')
|
||||
let creating = $state(false)
|
||||
|
||||
async function handleCreate() {
|
||||
if (!newCaption.trim()) return
|
||||
creating = true
|
||||
try {
|
||||
const tags = newTags
|
||||
.split(/[\s,]+/)
|
||||
.map(t => t.replace(/^#/, '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
await api.createText(newCaption.trim(), tags)
|
||||
showCreate = false
|
||||
newCaption = ''
|
||||
newTags = ''
|
||||
await load()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
creating = false
|
||||
}
|
||||
}
|
||||
|
||||
// Копирование в коллекцию
|
||||
let copyTarget = $state(null)
|
||||
let copying = $state(null)
|
||||
|
||||
// Редактирование
|
||||
let editTarget = $state(null) // id редактируемого элемента
|
||||
let editCaption = $state('')
|
||||
let editTags = $state('') // теги через пробел, без #
|
||||
let saving = $state(false)
|
||||
let editInlineTitle = $state('')
|
||||
let editInlineDesc = $state('')
|
||||
|
||||
async function load() {
|
||||
loading = true
|
||||
error = null
|
||||
previews = {}
|
||||
loading = true; error = null
|
||||
try {
|
||||
items = await api.getMedia(query)
|
||||
// Kick off preview loading for each previewable item (fire & forget)
|
||||
items = await api.getMedia(query, includeNsfw)
|
||||
// Rebuild previews: use cache for known items, fetch only uncached
|
||||
const next = {}
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType)) {
|
||||
loadPreview(item.id)
|
||||
if (!PREVIEWABLE.has(item.mediaType)) continue
|
||||
if (urlCache[item.id]) {
|
||||
next[item.id] = { url: urlCache[item.id], loading: false, error: false }
|
||||
} else {
|
||||
next[item.id] = { url: null, loading: true, error: false }
|
||||
}
|
||||
}
|
||||
previews = next
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType) && !urlCache[item.id]) loadPreview(item.id)
|
||||
}
|
||||
} catch (e) {
|
||||
error = e.message
|
||||
} finally {
|
||||
@@ -37,21 +79,44 @@
|
||||
}
|
||||
|
||||
async function loadPreview(id) {
|
||||
previews[id] = { url: null, loading: true, error: false }
|
||||
try {
|
||||
const url = await api.getDownloadUrl(id)
|
||||
previews[id] = { url, loading: false, error: false }
|
||||
urlCache[id] = url
|
||||
previews = { ...previews, [id]: { url, loading: false, error: false } }
|
||||
} catch {
|
||||
previews[id] = { url: null, loading: false, error: true }
|
||||
previews = { ...previews, [id]: { url: null, loading: false, error: true } }
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendToChat(id) {
|
||||
async function openCopyPicker(id) {
|
||||
editTarget = null
|
||||
copyTarget = copyTarget === id ? null : id
|
||||
if (copyTarget !== null) {
|
||||
try {
|
||||
await api.sendToChat(id, queryId)
|
||||
tgClose()
|
||||
await collectionsStore.load()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
copyTarget = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopy(mediaId, collectionId) {
|
||||
copying = collectionId
|
||||
try {
|
||||
const result = await api.copyMedia(mediaId, collectionId)
|
||||
const original = items.find(i => i.id === mediaId)
|
||||
if (original && result?.id) {
|
||||
const newItem = { ...original, id: result.id, collectionId }
|
||||
items = [newItem, ...items]
|
||||
if (previews[mediaId]) previews = { ...previews, [result.id]: previews[mediaId] }
|
||||
if (urlCache[mediaId]) urlCache[result.id] = urlCache[mediaId]
|
||||
}
|
||||
copyTarget = null
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
copying = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,55 +126,143 @@
|
||||
items = items.filter((i) => i.id !== id)
|
||||
const { [id]: _, ...rest } = previews
|
||||
previews = rest
|
||||
delete urlCache[id]
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function openEditPanel(item) {
|
||||
copyTarget = null
|
||||
if (editTarget === item.id) {
|
||||
editTarget = null
|
||||
return
|
||||
}
|
||||
editTarget = item.id
|
||||
editCaption = item.caption ?? ''
|
||||
editTags = item.tags?.join(' ') ?? ''
|
||||
editInlineTitle = item.inlineTitle ?? ''
|
||||
editInlineDesc = item.inlineDescription ?? ''
|
||||
}
|
||||
|
||||
function cancelEdit() {
|
||||
editTarget = null
|
||||
}
|
||||
|
||||
async function handleSave(id) {
|
||||
saving = true
|
||||
try {
|
||||
const tags = editTags
|
||||
.split(/[\s,]+/)
|
||||
.map(t => t.replace(/^#/, '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
await api.updateMedia(id, {
|
||||
caption: editCaption || null,
|
||||
tags,
|
||||
inlineTitle: editInlineTitle.trim() || null,
|
||||
inlineDescription: editInlineDesc.trim() || null,
|
||||
})
|
||||
// Обновляем локально
|
||||
const idx = items.findIndex(i => i.id === id)
|
||||
if (idx !== -1) {
|
||||
items[idx] = { ...items[idx], caption: editCaption || null, tags,
|
||||
inlineTitle: editInlineTitle.trim() || null,
|
||||
inlineDescription: editInlineDesc.trim() || null }
|
||||
}
|
||||
editTarget = null
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
|
||||
let searchTimer
|
||||
function onSearch() {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(load, 400)
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
function toggleNsfw() {
|
||||
includeNsfw = !includeNsfw
|
||||
load()
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
collectionsStore.load().catch(() => {})
|
||||
await load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
{#if attachMode}
|
||||
<div class="attach-banner">Выберите медиа для отправки в чат</div>
|
||||
{/if}
|
||||
<div class="search-row">
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
on:input={onSearch}
|
||||
oninput={onSearch}
|
||||
/>
|
||||
<button
|
||||
class="nsfw-toggle"
|
||||
class:nsfw-toggle--on={includeNsfw}
|
||||
onclick={toggleNsfw}
|
||||
title={includeNsfw ? 'Скрыть 18+' : 'Показать 18+'}
|
||||
>18+</button>
|
||||
<button
|
||||
class="btn-add"
|
||||
class:btn-add--active={showCreate}
|
||||
onclick={() => showCreate = !showCreate}
|
||||
title="Создать текстовую запись"
|
||||
><Plus size={18}/></button>
|
||||
</div>
|
||||
|
||||
{#if showCreate}
|
||||
<div class="create-panel">
|
||||
<textarea
|
||||
class="create-textarea"
|
||||
placeholder="Текст записи…"
|
||||
bind:value={newCaption}
|
||||
rows="3"
|
||||
onkeydown={(e) => { if (e.key === 'Escape') showCreate = false }}
|
||||
></textarea>
|
||||
<input
|
||||
class="create-tags"
|
||||
placeholder="Теги: мем реакция кот"
|
||||
bind:value={newTags}
|
||||
onkeydown={(e) => { if (e.key === 'Escape') showCreate = false }}
|
||||
/>
|
||||
<div class="create-actions">
|
||||
<button class="btn-save" onclick={handleCreate} disabled={creating || !newCaption.trim()}>
|
||||
{creating ? 'Сохранение…' : 'Сохранить'}
|
||||
</button>
|
||||
<button class="btn-cancel" onclick={() => { showCreate = false; newCaption = ''; newTags = '' }}>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
{:else if error}
|
||||
<div class="hint error">{error}</div>
|
||||
{:else if items.length === 0}
|
||||
<div class="hint">Нет медиа</div>
|
||||
<div class="hint">Нет медиа{query ? ' по запросу' : ''}</div>
|
||||
{:else}
|
||||
<ul class="list">
|
||||
{#each items as item (item.id)}
|
||||
{@const preview = previews[item.id]}
|
||||
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->
|
||||
<li
|
||||
class="item"
|
||||
class:item--attach={attachMode}
|
||||
on:click={attachMode ? () => handleSendToChat(item.id) : undefined}
|
||||
role={attachMode ? 'button' : undefined}
|
||||
>
|
||||
{@const col = collectionsStore.items.find(c => c.id === item.collectionId)}
|
||||
{@const colName = col?.name}
|
||||
{@const isNsfw = col?.isNsfw}
|
||||
<li class="item">
|
||||
{#if PREVIEWABLE.has(item.mediaType)}
|
||||
<div class="thumb-wrap">
|
||||
{#if preview?.loading || !preview}
|
||||
<div class="thumb-skeleton" aria-hidden="true"></div>
|
||||
<div class="thumb-skeleton"></div>
|
||||
{:else if preview.url}
|
||||
{#if item.mediaType === 'Video'}
|
||||
<video class="thumb" src={preview.url} muted preload="metadata" />
|
||||
{#if item.mediaType === 'Video' || item.mediaType === 'Animation'}
|
||||
<video class="thumb" src={preview.url} muted preload="metadata" loop autoplay playsinline />
|
||||
{:else}
|
||||
<img class="thumb" src={preview.url} alt={item.caption ?? item.mediaType} loading="lazy" />
|
||||
{/if}
|
||||
@@ -117,13 +270,22 @@
|
||||
<div class="thumb-error" title="Не удалось загрузить">🖼</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="thumb-wrap thumb-text">
|
||||
<span class="text-icon">T</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="item-info">
|
||||
<div class="item-meta">
|
||||
<span class="item-type">{item.mediaType}</span>
|
||||
{#if item.caption}
|
||||
<span class="item-caption">{item.caption}</span>
|
||||
{#if colName}
|
||||
<span class="item-col">· {colName}</span>
|
||||
{/if}
|
||||
{#if isNsfw}
|
||||
<span class="item-nsfw">18+</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if item.tags?.length}
|
||||
<div class="tags">
|
||||
{#each item.tags as tag}
|
||||
@@ -131,13 +293,103 @@
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{#if item.caption}
|
||||
<span class="item-caption">{item.caption}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if attachMode}
|
||||
<span class="attach-hint">Отправить</span>
|
||||
|
||||
<div class="item-actions">
|
||||
<button
|
||||
class="icon-btn"
|
||||
class:icon-btn--active={editTarget === item.id}
|
||||
onclick={() => openEditPanel(item)}
|
||||
title="Редактировать"
|
||||
><Pencil size={16}/></button>
|
||||
<button
|
||||
class="icon-btn"
|
||||
class:icon-btn--active={copyTarget === item.id}
|
||||
onclick={() => openCopyPicker(item.id)}
|
||||
title="Копировать в коллекцию"
|
||||
><FolderInput size={16}/></button>
|
||||
<button class="icon-btn del" onclick={() => handleDelete(item.id)} title="Удалить"><Trash2 size={16}/></button>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
{#if editTarget === item.id}
|
||||
<li class="edit-panel">
|
||||
<textarea
|
||||
class="edit-input edit-textarea"
|
||||
placeholder="Подпись"
|
||||
bind:value={editCaption}
|
||||
rows="3"
|
||||
onkeydown={(e) => { if (e.key === 'Escape') cancelEdit() }}
|
||||
></textarea>
|
||||
<input
|
||||
class="edit-input"
|
||||
placeholder="Теги: мем реакция кот"
|
||||
bind:value={editTags}
|
||||
onkeydown={(e) => { if (e.key === 'Escape') cancelEdit() }}
|
||||
/>
|
||||
{#if item.mediaType !== 'Sticker'}
|
||||
<input
|
||||
class="edit-input edit-input--inline"
|
||||
placeholder="Заголовок в пикере (необязательно)"
|
||||
bind:value={editInlineTitle}
|
||||
onkeydown={(e) => { if (e.key === 'Escape') cancelEdit() }}
|
||||
/>
|
||||
{/if}
|
||||
{#if item.mediaType === 'Photo' || item.mediaType === 'Video' || item.mediaType === 'Text'}
|
||||
<input
|
||||
class="edit-input edit-input--inline"
|
||||
placeholder="Описание в пикере (необязательно)"
|
||||
bind:value={editInlineDesc}
|
||||
onkeydown={(e) => { if (e.key === 'Escape') cancelEdit() }}
|
||||
/>
|
||||
{/if}
|
||||
<div class="edit-actions">
|
||||
<button
|
||||
class="icon-btn ok"
|
||||
onclick={() => handleSave(item.id)}
|
||||
disabled={saving}
|
||||
title="Сохранить"
|
||||
><Check size={16}/></button>
|
||||
<button
|
||||
class="icon-btn cancel"
|
||||
onclick={cancelEdit}
|
||||
disabled={saving}
|
||||
title="Отмена"
|
||||
><X size={16}/></button>
|
||||
</div>
|
||||
</li>
|
||||
{/if}
|
||||
|
||||
{#if copyTarget === item.id}
|
||||
<li class="copy-panel">
|
||||
{#if collectionsStore.loading}
|
||||
<div class="copy-hint">Загрузка…</div>
|
||||
{:else if collectionsStore.items.length === 0}
|
||||
<div class="copy-hint">Нет коллекций</div>
|
||||
{:else}
|
||||
<button class="del" on:click={() => handleDelete(item.id)} title="Удалить">✕</button>
|
||||
<div class="copy-hint">Копировать в:</div>
|
||||
<ul class="copy-list">
|
||||
{#each collectionsStore.items as col (col.id)}
|
||||
<li>
|
||||
<button
|
||||
class="copy-col"
|
||||
class:copy-col--busy={copying === col.id}
|
||||
disabled={!!copying}
|
||||
onclick={() => handleCopy(item.id, col.id)}
|
||||
>
|
||||
{col.name}
|
||||
{#if col.isInbox}<span class="copy-badge">основная</span>{/if}
|
||||
{#if col.isNsfw}<span class="copy-badge copy-badge--nsfw">18+</span>{/if}
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</li>
|
||||
{/if}
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
@@ -145,19 +397,67 @@
|
||||
|
||||
<style>
|
||||
.page { padding: 8px; }
|
||||
.attach-banner {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: var(--tg-hint, #888);
|
||||
padding: 6px 0 4px;
|
||||
|
||||
.search-row {
|
||||
display: flex; gap: 6px; margin-bottom: 8px;
|
||||
}
|
||||
.search {
|
||||
width: 100%; box-sizing: border-box;
|
||||
flex: 1; box-sizing: border-box;
|
||||
padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000);
|
||||
font-size: 14px; margin-bottom: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.nsfw-toggle {
|
||||
flex-shrink: 0;
|
||||
padding: 0 10px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-hint, #888);
|
||||
font-size: 12px; font-weight: 700; cursor: pointer;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.nsfw-toggle--on {
|
||||
background: #e53935; color: #fff;
|
||||
}
|
||||
.btn-add {
|
||||
flex-shrink: 0; width: 36px; height: 36px;
|
||||
border-radius: 8px; border: none;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
cursor: pointer; transition: opacity .15s;
|
||||
}
|
||||
.btn-add--active { opacity: .75; }
|
||||
.create-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid var(--tg-button, #2196f3);
|
||||
margin-bottom: 8px;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
}
|
||||
.create-textarea, .create-tags {
|
||||
width: 100%; box-sizing: border-box;
|
||||
padding: 8px 10px; border-radius: 6px; border: none;
|
||||
background: var(--tg-bg, #fff); color: var(--tg-text, #000);
|
||||
font-size: 14px; font-family: inherit; resize: none;
|
||||
outline: 1px solid var(--tg-secondary-bg, #ddd);
|
||||
}
|
||||
.create-textarea:focus, .create-tags:focus {
|
||||
outline: 2px solid var(--tg-button, #2196f3);
|
||||
}
|
||||
.create-actions { display: flex; gap: 6px; }
|
||||
.btn-save {
|
||||
padding: 6px 14px; border-radius: 8px; border: none;
|
||||
background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
font-size: 13px; font-weight: 500; cursor: pointer;
|
||||
}
|
||||
.btn-save:disabled { opacity: .4; cursor: default; }
|
||||
.btn-cancel {
|
||||
padding: 6px 14px; border-radius: 8px; border: none;
|
||||
background: none; color: var(--tg-hint, #888);
|
||||
font-size: 13px; font-weight: 500; cursor: pointer;
|
||||
}
|
||||
.btn-cancel:hover { background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
.list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
|
||||
@@ -169,13 +469,10 @@
|
||||
|
||||
/* ── Thumbnail ──────────────────────────────────────────────────────────── */
|
||||
.thumb-wrap {
|
||||
flex-shrink: 0;
|
||||
width: 64px; height: 64px;
|
||||
flex-shrink: 0; width: 64px; height: 64px;
|
||||
border-radius: 6px; overflow: hidden;
|
||||
}
|
||||
.thumb {
|
||||
width: 100%; height: 100%; object-fit: cover; display: block;
|
||||
}
|
||||
.thumb { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.thumb-skeleton {
|
||||
width: 100%; height: 100%;
|
||||
background: linear-gradient(90deg,
|
||||
@@ -189,9 +486,14 @@
|
||||
.thumb-error {
|
||||
width: 100%; height: 100%;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 24px;
|
||||
background: var(--tg-secondary-bg, #eee);
|
||||
font-size: 24px; background: var(--tg-secondary-bg, #eee);
|
||||
}
|
||||
.thumb-text {
|
||||
background: var(--tg-secondary-bg, #e8e8e8);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.text-icon { font-size: 24px; font-weight: 700; color: var(--tg-hint, #888); }
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
@@ -199,29 +501,76 @@
|
||||
|
||||
/* ── Text info ──────────────────────────────────────────────────────────── */
|
||||
.item-info { flex: 1; min-width: 0; }
|
||||
.item-meta { display: flex; align-items: baseline; gap: 4px; }
|
||||
.item-type { font-size: 11px; color: var(--tg-hint, #888); text-transform: uppercase; }
|
||||
.item-caption { display: block; font-size: 14px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.item-col { font-size: 11px; color: var(--tg-hint, #888); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.item-caption { display: block; font-size: 14px; margin-top: 2px; white-space: pre-wrap; word-break: break-word; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
|
||||
.tag {
|
||||
font-size: 12px; background: var(--tg-button, #2196f3);
|
||||
color: var(--tg-btn-text, #fff); border-radius: 4px; padding: 1px 6px;
|
||||
}
|
||||
.item--attach {
|
||||
cursor: pointer;
|
||||
.item-actions { display: flex; flex-direction: row; gap: 2px; flex-shrink: 0; align-self: flex-start; }
|
||||
|
||||
.icon-btn {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
width: 32px; height: 32px; border-radius: 8px; border: none;
|
||||
background: none; color: var(--tg-hint, #888); cursor: pointer;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.item--attach:active {
|
||||
opacity: 0.7;
|
||||
.icon-btn:hover { background: var(--tg-secondary-bg, #e8e8e8); color: var(--tg-text, #000); }
|
||||
.icon-btn--active { color: var(--tg-button, #2196f3); }
|
||||
.icon-btn.del:hover { color: #e53935; }
|
||||
.icon-btn.ok { color: #43a047; }
|
||||
.icon-btn.ok:hover { color: #43a047; background: var(--tg-secondary-bg, #e8e8e8); }
|
||||
.icon-btn.cancel { color: var(--tg-hint, #999); }
|
||||
.icon-btn:disabled { opacity: .4; cursor: default; }
|
||||
|
||||
/* ── Edit panel ─────────────────────────────────────────────────────────── */
|
||||
.edit-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid #43a047;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
}
|
||||
.attach-hint {
|
||||
font-size: 12px;
|
||||
color: var(--tg-button, #2196f3);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
align-self: center;
|
||||
.edit-input {
|
||||
width: 100%; padding: 7px 10px; border-radius: 7px; border: none;
|
||||
background: var(--tg-bg, #fff); color: var(--tg-text, #000);
|
||||
font-size: 14px;
|
||||
outline: 1px solid var(--tg-hint, #ccc);
|
||||
}
|
||||
.del {
|
||||
background: none; border: none; color: var(--tg-hint, #888);
|
||||
font-size: 16px; cursor: pointer; padding: 0; flex-shrink: 0;
|
||||
align-self: flex-start;
|
||||
.edit-input:focus { outline-color: #43a047; }
|
||||
.edit-textarea { resize: vertical; font-family: inherit; }
|
||||
.edit-input--inline { font-size: 12px; color: var(--tg-hint, #888); }
|
||||
.edit-input--inline::placeholder { font-style: italic; }
|
||||
.edit-actions { display: flex; gap: 4px; justify-content: flex-end; }
|
||||
|
||||
/* ── Copy panel ─────────────────────────────────────────────────────────── */
|
||||
.copy-panel {
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
border-left: 3px solid var(--tg-button, #2196f3);
|
||||
}
|
||||
.copy-hint { font-size: 12px; color: var(--tg-hint, #888); margin-bottom: 6px; }
|
||||
.copy-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.copy-col {
|
||||
width: 100%; text-align: left; background: none; border: none;
|
||||
padding: 6px 8px; border-radius: 6px; cursor: pointer;
|
||||
font-size: 14px; color: var(--tg-text, #000);
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
transition: background .12s;
|
||||
}
|
||||
.copy-col:hover:not(:disabled) { background: var(--tg-bg, #fff); }
|
||||
.copy-col:disabled { opacity: .5; cursor: default; }
|
||||
.copy-col--busy { opacity: .5; }
|
||||
.copy-badge--nsfw { background: #e53935; }
|
||||
.copy-badge {
|
||||
font-size: 10px; background: var(--tg-button, #2196f3); color: var(--tg-btn-text, #fff);
|
||||
border-radius: 3px; padding: 1px 4px;
|
||||
}
|
||||
.item-nsfw {
|
||||
font-size: 10px; font-weight: 700; letter-spacing: .02em;
|
||||
background: #e53935; color: #fff;
|
||||
border-radius: 3px; padding: 1px 5px; flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
<script>
|
||||
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'
|
||||
|
||||
const queryId = getQueryId()
|
||||
const chatName = getChatName()
|
||||
const chatType = getChatType()
|
||||
|
||||
const PREVIEWABLE = new Set(['Photo', 'Video', 'Animation', 'Sticker'])
|
||||
|
||||
let items = $state([])
|
||||
let query = $state('')
|
||||
let loading = $state(true)
|
||||
let error = $state(null)
|
||||
let sending = $state(null) // id медиа, которое сейчас отправляется
|
||||
|
||||
let previews = $state({})
|
||||
|
||||
async function load() {
|
||||
loading = true; error = null; previews = {}
|
||||
try {
|
||||
items = await api.getMedia(query)
|
||||
for (const item of items) {
|
||||
if (PREVIEWABLE.has(item.mediaType)) loadPreview(item.id)
|
||||
}
|
||||
} catch (e) {
|
||||
error = e.message
|
||||
} finally {
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPreview(id) {
|
||||
previews = { ...previews, [id]: { url: null, loading: true, error: false } }
|
||||
try {
|
||||
const url = await api.getDownloadUrl(id)
|
||||
previews = { ...previews, [id]: { url, loading: false, error: false } }
|
||||
} catch {
|
||||
previews = { ...previews, [id]: { url: null, loading: false, error: true } }
|
||||
}
|
||||
}
|
||||
|
||||
async function send(id) {
|
||||
if (sending) return
|
||||
sending = id
|
||||
try {
|
||||
await api.sendToChat(id, queryId)
|
||||
tgClose()
|
||||
} catch (e) {
|
||||
showAlert(e.message)
|
||||
sending = null
|
||||
}
|
||||
}
|
||||
|
||||
let searchTimer
|
||||
function onSearch() {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(load, 400)
|
||||
}
|
||||
|
||||
onMount(load)
|
||||
</script>
|
||||
|
||||
<div class="page">
|
||||
<div class="header">
|
||||
<div class="title">Отправить в чат</div>
|
||||
{#if chatName}
|
||||
<div class="chat-name">
|
||||
{#if chatType === 'private'}
|
||||
<User size={14} strokeWidth={2} />
|
||||
{:else if chatType === 'channel'}
|
||||
<Megaphone size={14} strokeWidth={2} />
|
||||
{:else if chatType === 'group' || chatType === 'supergroup'}
|
||||
<Users size={14} strokeWidth={2} />
|
||||
{/if}
|
||||
{chatName}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="search"
|
||||
placeholder="Поиск: #мем -#кот слово"
|
||||
bind:value={query}
|
||||
oninput={onSearch}
|
||||
/>
|
||||
|
||||
{#if loading}
|
||||
<div class="hint">Загрузка…</div>
|
||||
{:else if error}
|
||||
<div class="hint error">{error}</div>
|
||||
{:else if items.length === 0}
|
||||
<div class="hint">Нет медиа{query ? ' по запросу' : ''}</div>
|
||||
{:else}
|
||||
<ul class="list">
|
||||
{#each items as item (item.id)}
|
||||
{@const preview = previews[item.id]}
|
||||
{@const isSending = sending === item.id}
|
||||
<!-- svelte-ignore a11y-click-events-have-key-events a11y-no-noninteractive-element-interactions -->
|
||||
<li
|
||||
class="item"
|
||||
class:item--sending={isSending}
|
||||
onclick={() => send(item.id)}
|
||||
role="button"
|
||||
>
|
||||
{#if PREVIEWABLE.has(item.mediaType)}
|
||||
<div class="thumb-wrap">
|
||||
{#if preview?.loading || !preview}
|
||||
<div class="thumb-skeleton"></div>
|
||||
{:else if preview.url}
|
||||
{#if item.mediaType === 'Video'}
|
||||
<video class="thumb" src={preview.url} muted preload="metadata" />
|
||||
{:else}
|
||||
<img class="thumb" src={preview.url} alt={item.caption ?? item.mediaType} loading="lazy" />
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="thumb-error">🖼</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="thumb-wrap thumb-text">
|
||||
<span class="text-icon">T</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="item-info">
|
||||
<span class="item-type">{item.mediaType}</span>
|
||||
{#if item.caption}
|
||||
<span class="item-caption">{item.caption}</span>
|
||||
{/if}
|
||||
{#if item.tags?.length}
|
||||
<div class="tags">
|
||||
{#each item.tags as tag}
|
||||
<span class="tag">#{tag}</span>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<span class="send-label">
|
||||
{#if isSending}…{:else}→{/if}
|
||||
</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.page { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
|
||||
|
||||
.header {
|
||||
padding: 12px 12px 4px;
|
||||
}
|
||||
.title {
|
||||
font-size: 16px; font-weight: 600; color: var(--tg-text, #000);
|
||||
}
|
||||
.chat-name {
|
||||
font-size: 13px; color: var(--tg-hint, #888); margin-top: 2px;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
display: flex; align-items: center; gap: 4px;
|
||||
}
|
||||
.chat-name :global(svg) { flex-shrink: 0; color: var(--tg-hint, #888); }
|
||||
|
||||
.search {
|
||||
margin: 4px 8px 6px; width: calc(100% - 16px);
|
||||
padding: 8px 12px; border-radius: 8px; border: none;
|
||||
background: var(--tg-secondary-bg, #f0f0f0);
|
||||
color: var(--tg-text, #000); font-size: 14px;
|
||||
}
|
||||
|
||||
.hint { text-align: center; padding: 32px; color: var(--tg-hint, #888); }
|
||||
.error { color: #e53935; }
|
||||
|
||||
.list {
|
||||
list-style: none; margin: 0; padding: 0 8px 8px;
|
||||
display: flex; flex-direction: column; gap: 6px;
|
||||
overflow-y: auto; flex: 1;
|
||||
}
|
||||
|
||||
.item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
background: var(--tg-secondary-bg, #f5f5f5);
|
||||
border-radius: 10px; padding: 10px 12px;
|
||||
cursor: pointer; transition: opacity .15s;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
.item:active, .item--sending { opacity: 0.6; }
|
||||
|
||||
/* ── Thumbnail ─────────────────────────────────────────────────────── */
|
||||
.thumb-wrap {
|
||||
flex-shrink: 0; width: 52px; height: 52px;
|
||||
border-radius: 6px; overflow: hidden;
|
||||
}
|
||||
.thumb { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.thumb-skeleton {
|
||||
width: 100%; height: 100%;
|
||||
background: linear-gradient(90deg,
|
||||
var(--tg-secondary-bg, #e0e0e0) 25%,
|
||||
var(--tg-bg, #f5f5f5) 50%,
|
||||
var(--tg-secondary-bg, #e0e0e0) 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.4s infinite;
|
||||
}
|
||||
.thumb-error {
|
||||
width: 100%; height: 100%;
|
||||
display: flex; align-items: center; justify-content: center; font-size: 20px;
|
||||
background: var(--tg-secondary-bg, #eee);
|
||||
}
|
||||
.thumb-text {
|
||||
background: var(--tg-secondary-bg, #e8e8e8);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.text-icon { font-size: 20px; font-weight: 700; color: var(--tg-hint, #888); }
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: 200% 0; }
|
||||
100% { background-position: -200% 0; }
|
||||
}
|
||||
|
||||
/* ── Text info ─────────────────────────────────────────────────────── */
|
||||
.item-info { flex: 1; min-width: 0; }
|
||||
.item-type { font-size: 11px; color: var(--tg-hint, #888); text-transform: uppercase; }
|
||||
.item-caption { display: block; font-size: 14px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tags { display: flex; flex-wrap: wrap; gap: 3px; margin-top: 4px; }
|
||||
.tag {
|
||||
font-size: 11px; background: var(--tg-button, #2196f3);
|
||||
color: var(--tg-btn-text, #fff); border-radius: 4px; padding: 1px 5px;
|
||||
}
|
||||
|
||||
.send-label {
|
||||
font-size: 18px; color: var(--tg-button, #2196f3);
|
||||
flex-shrink: 0; font-weight: 500;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,32 @@
|
||||
import { api } from '../lib/api.js'
|
||||
|
||||
class CollectionsStore {
|
||||
items = $state([])
|
||||
ready = $state(false)
|
||||
loading = $state(false)
|
||||
|
||||
/** Загрузить, если ещё не загружали (для MediaPage) */
|
||||
async load() {
|
||||
if (this.ready || this.loading) return
|
||||
await this._fetch()
|
||||
}
|
||||
|
||||
/** Всегда перезагружать (для CollectionsPage при mount) */
|
||||
async forceLoad() {
|
||||
if (this.loading) return
|
||||
this.ready = false
|
||||
await this._fetch()
|
||||
}
|
||||
|
||||
async _fetch() {
|
||||
this.loading = true
|
||||
try {
|
||||
this.items = await api.getCollections()
|
||||
this.ready = true
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const collectionsStore = new CollectionsStore()
|
||||
@@ -1,15 +1,12 @@
|
||||
using MediatR;
|
||||
using MemeVault.Api.Auth;
|
||||
using MemeVault.Application.Commands.CloneCollection;
|
||||
using MemeVault.Application.Commands.CreateCollection;
|
||||
using MemeVault.Application.Commands.CreateCollectionInvite;
|
||||
using MemeVault.Application.Commands.DeleteCollection;
|
||||
using MemeVault.Application.Commands.RevokeCollectionInvite;
|
||||
using MemeVault.Application.Commands.CloneCollection;
|
||||
using MemeVault.Application.Commands.RegenerateShareLink;
|
||||
using MemeVault.Application.Commands.JoinPublicCollection;
|
||||
using MemeVault.Application.Commands.SetCollectionInbox;
|
||||
using MemeVault.Application.Commands.SetCollectionNsfw;
|
||||
using MemeVault.Application.Commands.ShareCollection;
|
||||
using MemeVault.Application.Commands.RegenerateShareLink;
|
||||
using MemeVault.Application.Commands.RevokeCollectionInvite;
|
||||
using MemeVault.Application.Commands.UpdateCollection;
|
||||
using MemeVault.Application.Queries.GetCollectionInvites;
|
||||
using MemeVault.Application.Queries.GetCollectionItems;
|
||||
@@ -47,17 +44,27 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
}
|
||||
|
||||
// PATCH /api/collections/{id}
|
||||
// Обновляет имя, описание, nsfw-флаг, видимость.
|
||||
// Всегда возвращает { shareToken } — null, если коллекция Private.
|
||||
[HttpPatch("{id:guid}")]
|
||||
[ProducesResponseType(typeof(UpdateCollectionResponse), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(
|
||||
Guid id,
|
||||
[FromBody] UpdateCollectionRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new UpdateCollectionCommand(id, currentUser.TelegramId, request.Name, request.Description),
|
||||
var result = await mediator.Send(
|
||||
new UpdateCollectionCommand(
|
||||
id,
|
||||
currentUser.TelegramId,
|
||||
request.Name,
|
||||
request.Description,
|
||||
request.IsNsfw,
|
||||
request.Visibility),
|
||||
ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
return result is null ? NotFound() : Ok(new UpdateCollectionResponse(result.ShareToken));
|
||||
}
|
||||
|
||||
// DELETE /api/collections/{id}
|
||||
@@ -140,28 +147,6 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/inbox
|
||||
[HttpPut("{id:guid}/inbox")]
|
||||
public async Task<IActionResult> SetInbox(Guid id, CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(new SetCollectionInboxCommand(id, currentUser.TelegramId), ct);
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/nsfw
|
||||
[HttpPut("{id:guid}/nsfw")]
|
||||
public async Task<IActionResult> SetNsfw(
|
||||
Guid id,
|
||||
[FromBody] SetNsfwRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SetCollectionNsfwCommand(id, currentUser.TelegramId, request.IsNsfw),
|
||||
ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
}
|
||||
|
||||
// POST /api/collections/{id}/share-link/regenerate
|
||||
[HttpPost("{id:guid}/share-link/regenerate")]
|
||||
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
|
||||
@@ -173,24 +158,16 @@ public sealed class CollectionsController(IMediator mediator, CurrentUser curren
|
||||
|
||||
return token is null ? NotFound() : Ok(new { shareToken = token });
|
||||
}
|
||||
|
||||
// PUT /api/collections/{id}/visibility
|
||||
[HttpPut("{id:guid}/visibility")]
|
||||
public async Task<IActionResult> SetVisibility(
|
||||
Guid id,
|
||||
[FromBody] SetVisibilityRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var shareToken = await mediator.Send(
|
||||
new ShareCollectionCommand(id, currentUser.TelegramId, request.Visibility),
|
||||
ct);
|
||||
|
||||
return Ok(new { shareToken });
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CreateCollectionRequest(string Name, string? Description);
|
||||
public sealed record UpdateCollectionRequest(string Name, string? Description);
|
||||
public sealed record SetNsfwRequest(bool IsNsfw);
|
||||
public sealed record SetVisibilityRequest(CollectionVisibility Visibility);
|
||||
|
||||
public sealed record UpdateCollectionRequest(
|
||||
string Name,
|
||||
string? Description,
|
||||
bool? IsNsfw = null,
|
||||
CollectionVisibility? Visibility = null);
|
||||
|
||||
public sealed record UpdateCollectionResponse(string? ShareToken);
|
||||
|
||||
public sealed record CreateInviteRequest(CollectionRole Role, DateTimeOffset? ExpiresAt = null);
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using MediatR;
|
||||
using MemeVault.Api.Auth;
|
||||
using MemeVault.Application.Commands.SetCollectionInbox;
|
||||
using MemeVault.Application.Queries.GetCurrentUser;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace MemeVault.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/me")]
|
||||
public sealed class MeController(IMediator mediator, CurrentUser currentUser) : ControllerBase
|
||||
{
|
||||
// GET /api/me
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(CurrentUserDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetMe(CancellationToken ct)
|
||||
{
|
||||
var result = await mediator.Send(new GetCurrentUserQuery(currentUser.TelegramId), ct);
|
||||
return result is null ? NotFound() : Ok(result);
|
||||
}
|
||||
|
||||
// PATCH /api/me
|
||||
[HttpPatch]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> PatchMe(
|
||||
[FromBody] PatchMeRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
if (request.InboxCollectionId.HasValue)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new SetCollectionInboxCommand(request.InboxCollectionId.Value, currentUser.TelegramId), ct);
|
||||
|
||||
if (!ok) return NotFound();
|
||||
}
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record PatchMeRequest(Guid? InboxCollectionId);
|
||||
@@ -2,11 +2,13 @@ using MediatR;
|
||||
using MemeVault.Api.Auth;
|
||||
using MemeVault.Application.Commands.CopyMediaToCollection;
|
||||
using MemeVault.Application.Commands.DeleteMedia;
|
||||
using MemeVault.Application.Commands.SaveMedia;
|
||||
using MemeVault.Application.Commands.UpdateMedia;
|
||||
using MemeVault.Application.Commands.SendMediaToChat;
|
||||
using MemeVault.Application.Queries.GetMediaDownloadUrl;
|
||||
using MemeVault.Application.Queries.GetUserMedia;
|
||||
using MemeVault.Application.Queries.SearchMedia;
|
||||
using MemeVault.Domain.Enums;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -17,15 +19,39 @@ namespace MemeVault.Api.Controllers;
|
||||
[Route("api/[controller]")]
|
||||
public sealed class MediaController(IMediator mediator, CurrentUser currentUser) : ControllerBase
|
||||
{
|
||||
// GET /api/media?q=...&includeNsfw=true
|
||||
// POST /api/media
|
||||
// Создаёт текстовую запись напрямую из Mini App (без бота).
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create(
|
||||
[FromBody] CreateMediaRequest request,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var tags = (request.Tags ?? [])
|
||||
.Select(t => t.TrimStart('#').Trim().ToLowerInvariant())
|
||||
.Where(t => t.Length > 0)
|
||||
.ToList();
|
||||
|
||||
var id = await mediator.Send(
|
||||
new SaveMediaCommand(
|
||||
currentUser.TelegramId,
|
||||
Source: null,
|
||||
MediaType: MediaType.Text,
|
||||
Caption: request.Caption?.Trim(),
|
||||
Tags: tags),
|
||||
ct);
|
||||
|
||||
return CreatedAtAction(nameof(GetAll), new { id }, new { id });
|
||||
}
|
||||
|
||||
// GET /api/media?q=...&includeNsfw=false
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] string? q,
|
||||
[FromQuery] bool includeNsfw = true,
|
||||
[FromQuery] bool includeNsfw = false,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var items = string.IsNullOrWhiteSpace(q)
|
||||
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId), ct)
|
||||
? await mediator.Send(new GetUserMediaQuery(currentUser.TelegramId, includeNsfw), ct)
|
||||
: await mediator.Send(new SearchMediaQuery(currentUser.TelegramId, q, IncludeNsfw: includeNsfw), ct);
|
||||
|
||||
return Ok(items);
|
||||
@@ -65,7 +91,8 @@ public sealed class MediaController(IMediator mediator, CurrentUser currentUser)
|
||||
CancellationToken ct)
|
||||
{
|
||||
var ok = await mediator.Send(
|
||||
new UpdateMediaCommand(id, currentUser.TelegramId, request.Caption, request.Tags, request.CollectionId),
|
||||
new UpdateMediaCommand(id, currentUser.TelegramId, request.Caption, request.Tags, request.CollectionId,
|
||||
request.InlineTitle, request.InlineDescription),
|
||||
ct);
|
||||
|
||||
return ok ? NoContent() : NotFound();
|
||||
@@ -97,12 +124,16 @@ public sealed class MediaController(IMediator mediator, CurrentUser currentUser)
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CreateMediaRequest(string? Caption, IReadOnlyList<string>? Tags);
|
||||
|
||||
public sealed record SendToChatRequest(string QueryId);
|
||||
|
||||
public sealed record UpdateMediaRequest(
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
Guid? CollectionId = null
|
||||
Guid? CollectionId = null,
|
||||
string? InlineTitle = null,
|
||||
string? InlineDescription = null
|
||||
);
|
||||
|
||||
public sealed record CopyMediaRequest(Guid TargetCollectionId);
|
||||
|
||||
@@ -32,6 +32,8 @@ public sealed class DomainExceptionHandler : IExceptionHandler
|
||||
Status = status,
|
||||
};
|
||||
|
||||
problem.Extensions["errorCode"] = ex.GetType().Name;
|
||||
|
||||
ctx.Response.StatusCode = status;
|
||||
await ctx.Response.WriteAsJsonAsync(problem, ct);
|
||||
return true;
|
||||
|
||||
@@ -13,6 +13,7 @@ var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// ── Infrastructure (DB + Redis) ───────────────────────────────────────────────
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddS3Storage(builder.Configuration);
|
||||
|
||||
// ── MediatR ───────────────────────────────────────────────────────────────────
|
||||
builder.Services.AddMediatR(cfg =>
|
||||
|
||||
@@ -42,7 +42,6 @@ public sealed class CloneCollectionCommandHandler(
|
||||
item.Source,
|
||||
item.Type,
|
||||
item.Caption,
|
||||
mediaGroupId: null, // клон не связан с оригинальным альбомом
|
||||
item.Tags);
|
||||
|
||||
await mediaItems.AddAsync(copy, ct);
|
||||
|
||||
+10
-2
@@ -3,6 +3,7 @@ using MemeVault.Application.Common;
|
||||
using MemeVault.Domain.Aggregates.MediaItem;
|
||||
using MemeVault.Domain.Exceptions;
|
||||
using MemeVault.Domain.Repositories;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
|
||||
namespace MemeVault.Application.Commands.CopyMediaToCollection;
|
||||
|
||||
@@ -26,13 +27,20 @@ public sealed class CopyMediaToCollectionCommandHandler(
|
||||
if (target is null || !target.CanWrite(request.RequestingTelegramId))
|
||||
throw new DomainException("Target collection not found.");
|
||||
|
||||
// Создаём новый экземпляр MediaSource, а не переиспользуем tracked EF-объект.
|
||||
// OwnsOne-owned entity имеет MediaItemId как часть ключа; передача той же инстанции
|
||||
// другому агрегату вызывает InvalidOperationException в EF Core.
|
||||
var newSource = source.Source is null ? null
|
||||
: source.Source.Origin == MediaOrigin.Telegram
|
||||
? MediaSource.FromTelegram(source.Source.Reference!)
|
||||
: MediaSource.FromS3(source.Source.Reference!);
|
||||
|
||||
var copy = MediaItem.Create(
|
||||
source.OwnerTelegramId,
|
||||
target.Id,
|
||||
source.Source,
|
||||
newSource,
|
||||
source.Type,
|
||||
source.Caption,
|
||||
source.MediaGroupId,
|
||||
source.Tags);
|
||||
|
||||
await mediaItems.AddAsync(copy, ct);
|
||||
|
||||
@@ -15,6 +15,5 @@ public sealed record SaveMediaCommand(
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
string? MediaGroupId = null,
|
||||
Guid? CollectionId = null
|
||||
) : IRequest<Guid>;
|
||||
|
||||
@@ -58,7 +58,6 @@ public sealed class SaveMediaCommandHandler : IRequestHandler<SaveMediaCommand,
|
||||
request.Source,
|
||||
request.MediaType,
|
||||
request.Caption,
|
||||
request.MediaGroupId,
|
||||
tags);
|
||||
|
||||
await _mediaItems.AddAsync(item, cancellationToken);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using MediatR;
|
||||
using MemeVault.Domain.Enums;
|
||||
|
||||
namespace MemeVault.Application.Commands.UpdateCollection;
|
||||
|
||||
@@ -6,5 +7,13 @@ public sealed record UpdateCollectionCommand(
|
||||
Guid CollectionId,
|
||||
long RequestingTelegramId,
|
||||
string Name,
|
||||
string? Description
|
||||
) : IRequest<bool>;
|
||||
string? Description,
|
||||
bool? IsNsfw = null,
|
||||
CollectionVisibility? Visibility = null
|
||||
) : IRequest<UpdateCollectionResult?>;
|
||||
|
||||
/// <summary>
|
||||
/// null = коллекция не найдена или нет доступа.
|
||||
/// ShareToken — текущий токен коллекции после применения изменений (может быть null).
|
||||
/// </summary>
|
||||
public sealed record UpdateCollectionResult(string? ShareToken);
|
||||
|
||||
+13
-6
@@ -7,18 +7,25 @@ namespace MemeVault.Application.Commands.UpdateCollection;
|
||||
public sealed class UpdateCollectionCommandHandler(
|
||||
ICollectionRepository collections,
|
||||
IUnitOfWork unitOfWork)
|
||||
: IRequestHandler<UpdateCollectionCommand, bool>
|
||||
: IRequestHandler<UpdateCollectionCommand, UpdateCollectionResult?>
|
||||
{
|
||||
public async Task<bool> Handle(UpdateCollectionCommand request, CancellationToken ct)
|
||||
public async Task<UpdateCollectionResult?> Handle(UpdateCollectionCommand request, CancellationToken ct)
|
||||
{
|
||||
var collection = await collections.GetByIdAsync(request.CollectionId, ct);
|
||||
// Если коллекции нет или пользователь — не участник, возвращаем 404.
|
||||
// Если роль ниже Manager — domain.Rename() бросит InsufficientPermissionException.
|
||||
// Если коллекции нет или пользователь — не участник, возвращаем null (→ 404).
|
||||
// Если роль ниже Manager — domain-методы бросят InsufficientPermissionException (→ 403).
|
||||
if (collection is null || collection.GetRole(request.RequestingTelegramId) is null)
|
||||
return false;
|
||||
return null;
|
||||
|
||||
collection.Rename(request.Name, request.RequestingTelegramId);
|
||||
|
||||
if (request.IsNsfw.HasValue)
|
||||
collection.SetNsfw(request.IsNsfw.Value, request.RequestingTelegramId);
|
||||
|
||||
if (request.Visibility.HasValue)
|
||||
collection.SetVisibility(request.Visibility.Value, request.RequestingTelegramId);
|
||||
|
||||
await unitOfWork.SaveChangesAsync(ct);
|
||||
return true;
|
||||
return new UpdateCollectionResult(collection.ShareToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,5 +12,7 @@ public sealed record UpdateMediaCommand(
|
||||
long RequestingTelegramId,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
Guid? CollectionId = null
|
||||
Guid? CollectionId = null,
|
||||
string? InlineTitle = null,
|
||||
string? InlineDescription = null
|
||||
) : IRequest<bool>;
|
||||
|
||||
@@ -24,6 +24,7 @@ public sealed class UpdateMediaCommandHandler(
|
||||
|
||||
item.UpdateCaption(request.Caption);
|
||||
item.ReplaceTags(request.Tags.Select(r => new Tag(r)));
|
||||
item.UpdateInlineMeta(request.InlineTitle, request.InlineDescription);
|
||||
|
||||
// Перемещение в другую коллекцию
|
||||
if (request.CollectionId.HasValue && request.CollectionId.Value != item.CollectionId)
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetCurrentUser;
|
||||
|
||||
public sealed record GetCurrentUserQuery(long TelegramId)
|
||||
: IRequest<CurrentUserDto?>;
|
||||
|
||||
public sealed record CurrentUserDto(
|
||||
long TelegramId,
|
||||
string Username,
|
||||
string? FirstName,
|
||||
Guid? InboxCollectionId
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
using MediatR;
|
||||
using MemeVault.Domain.Repositories;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetCurrentUser;
|
||||
|
||||
public sealed class GetCurrentUserQueryHandler(IBotUserRepository users)
|
||||
: IRequestHandler<GetCurrentUserQuery, CurrentUserDto?>
|
||||
{
|
||||
public async Task<CurrentUserDto?> Handle(GetCurrentUserQuery request, CancellationToken ct)
|
||||
{
|
||||
var user = await users.GetByTelegramIdAsync(request.TelegramId, ct);
|
||||
if (user is null) return null;
|
||||
|
||||
return new CurrentUserDto(
|
||||
user.TelegramId,
|
||||
user.Username,
|
||||
user.FirstName,
|
||||
user.InboxCollectionId);
|
||||
}
|
||||
}
|
||||
@@ -3,5 +3,5 @@ using MemeVault.Application.Queries.SearchMedia;
|
||||
|
||||
namespace MemeVault.Application.Queries.GetUserMedia;
|
||||
|
||||
public sealed record GetUserMediaQuery(long OwnerTelegramId)
|
||||
public sealed record GetUserMediaQuery(long OwnerTelegramId, bool IncludeNsfw = false)
|
||||
: IRequest<IReadOnlyList<MediaItemDto>>;
|
||||
|
||||
@@ -18,7 +18,10 @@ public sealed class GetUserMediaQueryHandler
|
||||
GetUserMediaQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var items = await _mediaItems.GetByOwnerAsync(request.OwnerTelegramId, cancellationToken);
|
||||
var items = await _mediaItems.GetByOwnerAsync(
|
||||
request.OwnerTelegramId,
|
||||
request.IncludeNsfw,
|
||||
cancellationToken);
|
||||
|
||||
return items.Select(i => new MediaItemDto(
|
||||
i.Id,
|
||||
@@ -27,7 +30,9 @@ public sealed class GetUserMediaQueryHandler
|
||||
i.Type,
|
||||
i.Caption,
|
||||
i.Tags.Select(t => t.Value).ToList(),
|
||||
i.CreatedAt
|
||||
i.CreatedAt,
|
||||
i.InlineTitle,
|
||||
i.InlineDescription
|
||||
)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,5 +21,7 @@ public sealed record MediaItemDto(
|
||||
MediaType MediaType,
|
||||
string? Caption,
|
||||
IReadOnlyList<string> Tags,
|
||||
DateTimeOffset CreatedAt
|
||||
DateTimeOffset CreatedAt,
|
||||
string? InlineTitle = null,
|
||||
string? InlineDescription = null
|
||||
);
|
||||
|
||||
@@ -33,7 +33,9 @@ public sealed class SearchMediaQueryHandler : IRequestHandler<SearchMediaQuery,
|
||||
i.Type,
|
||||
i.Caption,
|
||||
i.Tags.Select(t => t.Value).ToList(),
|
||||
i.CreatedAt
|
||||
i.CreatedAt,
|
||||
i.InlineTitle,
|
||||
i.InlineDescription
|
||||
)).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ namespace MemeVault.Bot.Telegram.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// Обрабатывает входящие сообщения.
|
||||
/// Поддерживает media groups (альбомы): несколько фото/видео в одном "визуальном" сообщении.
|
||||
/// Альбомы (media groups) не поддерживаются — пользователь получает уведомление.
|
||||
/// </summary>
|
||||
public sealed class MessageHandler
|
||||
{
|
||||
@@ -64,8 +64,7 @@ public sealed class MessageHandler
|
||||
{
|
||||
await SaveSingleItemAsync(message.From.Id, message.Chat.Id,
|
||||
source, mediaType,
|
||||
message.Caption ?? message.Text,
|
||||
mediaGroupId: null, ct);
|
||||
message.Caption ?? message.Text, ct);
|
||||
}
|
||||
else if (message.Text?.StartsWith('/') == true)
|
||||
{
|
||||
@@ -129,39 +128,11 @@ public sealed class MessageHandler
|
||||
var entries = JsonSerializer.Deserialize<List<MediaGroupEntry>>(raw)!;
|
||||
if (entries.Count == 0) return;
|
||||
|
||||
var first = entries[0];
|
||||
var tags = ExtractHashtags(first.Caption ?? "");
|
||||
var caption = StripHashtags(first.Caption ?? "");
|
||||
long chatId = first.ChatId;
|
||||
|
||||
// Сохраняем каждый файл группы как отдельный MediaItem, но с общим MediaGroupId
|
||||
var savedIds = new List<Guid>();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var origin = Enum.Parse<MediaOrigin>(e.Origin);
|
||||
var source = origin == MediaOrigin.Telegram
|
||||
? MediaSource.FromTelegram(e.Reference)
|
||||
: MediaSource.FromS3(e.Reference);
|
||||
|
||||
var mediaType = Enum.Parse<MediaType>(e.MediaType);
|
||||
|
||||
var id = await _mediator.Send(new SaveMediaCommand(
|
||||
e.OwnerTelegramId,
|
||||
source,
|
||||
mediaType,
|
||||
string.IsNullOrWhiteSpace(caption) ? null : caption,
|
||||
tags,
|
||||
MediaGroupId: groupId), ct);
|
||||
|
||||
savedIds.Add(id);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Saved media group {GroupId}: {Count} items", groupId, savedIds.Count);
|
||||
_logger.LogInformation("Ignored media group {GroupId}: {Count} items (unsupported)", groupId, entries.Count);
|
||||
|
||||
await _bot.SendMessage(
|
||||
chatId,
|
||||
$"✅ Альбом сохранён ({savedIds.Count} файлов)" +
|
||||
(tags.Count > 0 ? $"\nТеги: {string.Join(", ", tags.Select(t => "#" + t))}" : ""),
|
||||
entries[0].ChatId,
|
||||
"❌ Альбомы пока не поддерживаются — отправь каждый файл отдельно.",
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
@@ -171,7 +142,6 @@ public sealed class MessageHandler
|
||||
long ownerId, long chatId,
|
||||
MediaSource? source, MediaType mediaType,
|
||||
string? rawText,
|
||||
string? mediaGroupId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var tags = ExtractHashtags(rawText ?? "");
|
||||
@@ -182,8 +152,7 @@ public sealed class MessageHandler
|
||||
source,
|
||||
mediaType,
|
||||
string.IsNullOrWhiteSpace(caption) ? null : caption,
|
||||
tags,
|
||||
mediaGroupId), ct);
|
||||
tags), ct);
|
||||
|
||||
_logger.LogInformation("Saved {Type} for user {UserId}, item {ItemId}", mediaType, ownerId, id);
|
||||
|
||||
@@ -213,7 +182,7 @@ public sealed class MessageHandler
|
||||
"Теги прямо в подписи: #мем #кот\n" +
|
||||
"Поиск в инлайне: @bot #мем #кот -#толстый",
|
||||
"/help" => "📖 Команды:\n/start — приветствие\n/help — помощь\n\n" +
|
||||
"Поддерживаю: фото, видео, GIF, стикеры, текст и альбомы.",
|
||||
"Поддерживаю: фото, видео, GIF, стикеры и текст.",
|
||||
_ => "Неизвестная команда. Попробуй /help"
|
||||
};
|
||||
|
||||
|
||||
@@ -43,28 +43,42 @@ public sealed class InlineQueryHandler
|
||||
{
|
||||
var id = item.Id.ToString();
|
||||
|
||||
var tagsLine = item.Tags.Count > 0
|
||||
? string.Join(" ", item.Tags.Take(5).Select(t => "#" + t))
|
||||
: null;
|
||||
|
||||
return item.MediaType switch
|
||||
{
|
||||
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
MediaType.Video => new InlineQueryResultCachedVideo(id, item.FileId!, item.Caption ?? "Video"),
|
||||
MediaType.Video => new InlineQueryResultCachedVideo(
|
||||
id,
|
||||
item.FileId!,
|
||||
title: item.InlineTitle ?? item.Caption ?? "Video")
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
MediaType.Sticker => new InlineQueryResultCachedSticker(id, item.FileId!),
|
||||
|
||||
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||||
{
|
||||
Caption = item.Caption,
|
||||
Title = item.InlineTitle,
|
||||
},
|
||||
|
||||
MediaType.Text => new InlineQueryResultArticle(
|
||||
id,
|
||||
title: item.Caption?[..Math.Min(60, item.Caption.Length)] ?? "Текст",
|
||||
title: item.InlineTitle ?? item.Caption?[..Math.Min(60, item.Caption.Length)] ?? "Текст",
|
||||
inputMessageContent: new InputTextMessageContent(item.Caption ?? ""))
|
||||
{
|
||||
Description = string.Join(" ", item.Tags.Take(5).Select(t => "#" + t)),
|
||||
Description = item.InlineDescription ?? tagsLine,
|
||||
},
|
||||
|
||||
_ => null
|
||||
|
||||
@@ -29,11 +29,15 @@ public sealed class MediaItem
|
||||
/// <summary>Подпись к медиа или сам текст (для Type == Text).</summary>
|
||||
public string? Caption { get; private set; }
|
||||
|
||||
/// <summary>Заголовок для inline-пикера (не попадает в отправляемое сообщение).</summary>
|
||||
public string? InlineTitle { get; private set; }
|
||||
|
||||
/// <summary>Описание для inline-пикера (не попадает в отправляемое сообщение).</summary>
|
||||
public string? InlineDescription { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор группы сообщений Telegram (album).
|
||||
/// Несколько MediaItem с одинаковым MediaGroupId принадлежат одному альбому.
|
||||
/// </summary>
|
||||
public string? MediaGroupId { get; private set; }
|
||||
|
||||
public IReadOnlyList<Tag> Tags => _tags.AsReadOnly();
|
||||
public DateTimeOffset CreatedAt { get; private set; }
|
||||
@@ -51,7 +55,6 @@ public sealed class MediaItem
|
||||
MediaSource? source,
|
||||
MediaType type,
|
||||
string? caption,
|
||||
string? mediaGroupId,
|
||||
IEnumerable<Tag> tags)
|
||||
{
|
||||
Id = id;
|
||||
@@ -60,7 +63,6 @@ public sealed class MediaItem
|
||||
Source = source;
|
||||
Type = type;
|
||||
Caption = caption;
|
||||
MediaGroupId = mediaGroupId;
|
||||
CreatedAt = DateTimeOffset.UtcNow;
|
||||
_tags.AddRange(tags);
|
||||
}
|
||||
@@ -71,7 +73,6 @@ public sealed class MediaItem
|
||||
MediaSource? source,
|
||||
MediaType type,
|
||||
string? caption,
|
||||
string? mediaGroupId = null,
|
||||
IEnumerable<Tag>? tags = null)
|
||||
{
|
||||
if (type == MediaType.Text && string.IsNullOrWhiteSpace(caption))
|
||||
@@ -87,7 +88,6 @@ public sealed class MediaItem
|
||||
source,
|
||||
type,
|
||||
caption,
|
||||
mediaGroupId,
|
||||
tags ?? []);
|
||||
|
||||
item._domainEvents.Add(new MediaItemSavedEvent(item.Id, ownerTelegramId, type));
|
||||
@@ -100,6 +100,14 @@ public sealed class MediaItem
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Задаёт или очищает поля для inline-пикера.</summary>
|
||||
public void UpdateInlineMeta(string? inlineTitle, string? inlineDescription)
|
||||
{
|
||||
InlineTitle = string.IsNullOrWhiteSpace(inlineTitle) ? null : inlineTitle.Trim();
|
||||
InlineDescription = string.IsNullOrWhiteSpace(inlineDescription) ? null : inlineDescription.Trim();
|
||||
UpdatedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Перемещает элемент в другую коллекцию.</summary>
|
||||
public void MoveToCollection(Guid collectionId)
|
||||
{
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace MemeVault.Domain.Repositories;
|
||||
public interface IMediaItemRepository
|
||||
{
|
||||
Task<MediaItem?> GetByIdAsync(Guid id, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<MediaItem>> GetByOwnerAsync(long ownerTelegramId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<MediaItem>> GetByOwnerAsync(long ownerTelegramId, bool includeNsfw = true, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<MediaItem>> GetByCollectionAsync(Guid collectionId, CancellationToken ct = default);
|
||||
Task<IReadOnlyList<MediaItem>> GetByIdsAsync(IEnumerable<Guid> ids, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -17,6 +17,10 @@ namespace MemeVault.Infrastructure;
|
||||
|
||||
public static class InfrastructureServiceExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Общая инфраструктура: БД, Redis, репозитории, Telegram Bot Client.
|
||||
/// Вызывается и API, и Bot.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddInfrastructure(
|
||||
this IServiceCollection services,
|
||||
IConfiguration config)
|
||||
@@ -43,18 +47,39 @@ public static class InfrastructureServiceExtensions
|
||||
opts.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(multiplexer);
|
||||
});
|
||||
|
||||
// ── Options ───────────────────────────────────────────────────────────
|
||||
services.AddOptions<S3Options>()
|
||||
.BindConfiguration(S3Options.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// ── Telegram API options + Bot Client ─────────────────────────────────
|
||||
services.AddOptions<TelegramApiOptions>()
|
||||
.BindConfiguration(TelegramApiOptions.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
// ── S3 / MinIO ────────────────────────────────────────────────────────
|
||||
services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<TelegramApiOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.BotToken,
|
||||
baseUrl: opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
services.AddScoped<ITelegramQueryAnswerer, TelegramQueryAnswererService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// S3/MinIO — кэш Telegram-файлов и хранилище загрузок.
|
||||
/// Вызывается только из API; Bot в S3 не ходит.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddS3Storage(
|
||||
this IServiceCollection services,
|
||||
IConfiguration config)
|
||||
{
|
||||
services.AddOptions<S3Options>()
|
||||
.BindConfiguration(S3Options.Section)
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddSingleton<IAmazonS3>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<S3Options>>().Value;
|
||||
@@ -69,19 +94,7 @@ public static class InfrastructureServiceExtensions
|
||||
});
|
||||
|
||||
services.AddScoped<IFileStorage, S3FileStorage>();
|
||||
|
||||
// ── Telegram Bot Client ───────────────────────────────────────────────
|
||||
services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var opts = sp.GetRequiredService<IOptions<TelegramApiOptions>>().Value;
|
||||
var clientOptions = new TelegramBotClientOptions(
|
||||
token: opts.BotToken,
|
||||
baseUrl: opts.ApiBaseUrl);
|
||||
return new TelegramBotClient(clientOptions);
|
||||
});
|
||||
|
||||
services.AddScoped<ITelegramFileCacheService, TelegramFileCacheService>();
|
||||
services.AddScoped<ITelegramQueryAnswerer, TelegramQueryAnswererService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261007174037_DropMediaGroupId")]
|
||||
partial class DropMediaGroupId
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<Guid?>("InboxCollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("inbox_collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("InboxCollectionId");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.HasOne("MemeVault.Domain.Aggregates.Collection.Collection", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("InboxCollectionId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class DropMediaGroupId : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "media_group_id",
|
||||
table: "media_items");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "media_group_id",
|
||||
table: "media_items",
|
||||
type: "character varying(64)",
|
||||
maxLength: 64,
|
||||
nullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using MemeVault.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20261008215136_AddMediaInlineMeta")]
|
||||
partial class AddMediaInlineMeta
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.12")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 63);
|
||||
|
||||
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("FirstName")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("first_name");
|
||||
|
||||
b.Property<Guid?>("InboxCollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("inbox_collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("LastSeenAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("last_seen_at");
|
||||
|
||||
b.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("username");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("InboxCollectionId");
|
||||
|
||||
b.HasIndex("TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_bot_users_telegram_id");
|
||||
|
||||
b.ToTable("bot_users", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)")
|
||||
.HasColumnName("description");
|
||||
|
||||
b.Property<bool>("IsNsfw")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("boolean")
|
||||
.HasDefaultValue(false)
|
||||
.HasColumnName("is_nsfw");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)")
|
||||
.HasColumnName("name");
|
||||
|
||||
b.Property<string>("ShareToken")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("share_token");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string>("Visibility")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("visibility");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ShareToken")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collections_share_token")
|
||||
.HasFilter("share_token IS NOT NULL");
|
||||
|
||||
b.ToTable("collections", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.CollectionInvite.CollectionInvite", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<long>("CreatedByTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("created_by_telegram_id");
|
||||
|
||||
b.Property<DateTimeOffset?>("ExpiresAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("expires_at");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean")
|
||||
.HasColumnName("is_revoked");
|
||||
|
||||
b.Property<DateTimeOffset?>("RevokedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("revoked_at");
|
||||
|
||||
b.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasMaxLength(32)
|
||||
.HasColumnType("character varying(32)")
|
||||
.HasColumnName("token");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_collection_invites_collection_id");
|
||||
|
||||
b.HasIndex("Token")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_invites_token");
|
||||
|
||||
b.ToTable("collection_invites", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b.Property<string>("Caption")
|
||||
.HasMaxLength(4096)
|
||||
.HasColumnType("character varying(4096)")
|
||||
.HasColumnName("caption");
|
||||
|
||||
b.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("InlineDescription")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("InlineTitle")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("owner_telegram_id");
|
||||
|
||||
b.Property<string>("Type")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("type");
|
||||
|
||||
b.Property<DateTimeOffset?>("UpdatedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("updated_at");
|
||||
|
||||
b.Property<string[]>("_tags")
|
||||
.IsRequired()
|
||||
.HasColumnType("text[]")
|
||||
.HasColumnName("tags");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("CollectionId")
|
||||
.HasDatabaseName("ix_media_items_collection");
|
||||
|
||||
b.HasIndex("OwnerTelegramId")
|
||||
.HasDatabaseName("ix_media_items_owner");
|
||||
|
||||
b.HasIndex("_tags")
|
||||
.HasDatabaseName("ix_media_items_tags");
|
||||
|
||||
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("_tags"), "gin");
|
||||
|
||||
b.ToTable("media_items", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.BotUser.BotUser", b =>
|
||||
{
|
||||
b.HasOne("MemeVault.Domain.Aggregates.Collection.Collection", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("InboxCollectionId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.Collection.Collection", b =>
|
||||
{
|
||||
b.OwnsMany("MemeVault.Domain.Aggregates.Collection.CollectionMember", "Members", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("id");
|
||||
|
||||
b1.Property<DateTimeOffset>("AddedAt")
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("added_at");
|
||||
|
||||
b1.Property<Guid>("CollectionId")
|
||||
.HasColumnType("uuid")
|
||||
.HasColumnName("collection_id");
|
||||
|
||||
b1.Property<string>("Role")
|
||||
.IsRequired()
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("role");
|
||||
|
||||
b1.Property<long>("TelegramId")
|
||||
.HasColumnType("bigint")
|
||||
.HasColumnName("telegram_id");
|
||||
|
||||
b1.HasKey("Id");
|
||||
|
||||
b1.HasIndex("CollectionId", "TelegramId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("ix_collection_members_unique");
|
||||
|
||||
b1.ToTable("collection_members", (string)null);
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("CollectionId");
|
||||
});
|
||||
|
||||
b.Navigation("Members");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("MemeVault.Domain.Aggregates.MediaItem.MediaItem", b =>
|
||||
{
|
||||
b.OwnsOne("MemeVault.Domain.ValueObjects.MediaSource", "Source", b1 =>
|
||||
{
|
||||
b1.Property<Guid>("MediaItemId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b1.Property<string>("Origin")
|
||||
.HasColumnType("text")
|
||||
.HasColumnName("source_origin");
|
||||
|
||||
b1.Property<string>("Reference")
|
||||
.HasMaxLength(256)
|
||||
.HasColumnType("character varying(256)")
|
||||
.HasColumnName("source_reference");
|
||||
|
||||
b1.HasKey("MediaItemId");
|
||||
|
||||
b1.ToTable("media_items");
|
||||
|
||||
b1.WithOwner()
|
||||
.HasForeignKey("MediaItemId");
|
||||
});
|
||||
|
||||
b.Navigation("Source");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace MemeVault.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddMediaInlineMeta : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InlineDescription",
|
||||
table: "media_items",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<string>(
|
||||
name: "InlineTitle",
|
||||
table: "media_items",
|
||||
type: "text",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InlineDescription",
|
||||
table: "media_items");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "InlineTitle",
|
||||
table: "media_items");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,10 +193,11 @@ namespace MemeVault.Infrastructure.Migrations
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasColumnName("created_at");
|
||||
|
||||
b.Property<string>("MediaGroupId")
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("character varying(64)")
|
||||
.HasColumnName("media_group_id");
|
||||
b.Property<string>("InlineDescription")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("InlineTitle")
|
||||
.HasColumnType("text");
|
||||
|
||||
b.Property<long>("OwnerTelegramId")
|
||||
.HasColumnType("bigint")
|
||||
|
||||
@@ -35,10 +35,6 @@ public sealed class MediaItemConfiguration : IEntityTypeConfiguration<MediaItem>
|
||||
.HasColumnName("caption")
|
||||
.HasMaxLength(4096);
|
||||
|
||||
builder.Property(x => x.MediaGroupId)
|
||||
.HasColumnName("media_group_id")
|
||||
.HasMaxLength(64);
|
||||
|
||||
builder.Property(x => x.CreatedAt)
|
||||
.HasColumnName("created_at");
|
||||
|
||||
|
||||
@@ -14,10 +14,14 @@ public sealed class MediaItemRepository : IMediaItemRepository
|
||||
public Task<MediaItem?> GetByIdAsync(Guid id, CancellationToken ct) =>
|
||||
_db.MediaItems.FirstOrDefaultAsync(x => x.Id == id, ct);
|
||||
|
||||
public async Task<IReadOnlyList<MediaItem>> GetByOwnerAsync(long ownerTelegramId, CancellationToken ct)
|
||||
public async Task<IReadOnlyList<MediaItem>> GetByOwnerAsync(long ownerTelegramId, bool includeNsfw, CancellationToken ct)
|
||||
{
|
||||
return await _db.MediaItems
|
||||
.Where(x => x.OwnerTelegramId == ownerTelegramId)
|
||||
var query = _db.MediaItems.Where(x => x.OwnerTelegramId == ownerTelegramId);
|
||||
|
||||
if (!includeNsfw)
|
||||
query = query.Where(x => !_db.Collections.Any(c => c.Id == x.CollectionId && c.IsNsfw));
|
||||
|
||||
return await query
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.ToListAsync(ct);
|
||||
}
|
||||
|
||||
@@ -123,8 +123,8 @@ public sealed class CloneCollectionCommandHandlerTests
|
||||
.Returns(MakeUser());
|
||||
|
||||
var photo = MediaItem.Create(OwnerId, source.Id,
|
||||
MediaSource.FromTelegram("file1"), MediaType.Photo, "funny", "grp1",
|
||||
[new Tag("meme")]);
|
||||
MediaSource.FromTelegram("file1"), MediaType.Photo, "funny",
|
||||
tags: [new Tag("meme")]);
|
||||
_mediaItems.GetByCollectionAsync(source.Id, Arg.Any<CancellationToken>())
|
||||
.Returns((IReadOnlyList<MediaItem>)[photo]);
|
||||
|
||||
@@ -145,7 +145,6 @@ public sealed class CloneCollectionCommandHandlerTests
|
||||
await _mediaItems.Received(1).AddAsync(
|
||||
Arg.Is<MediaItem>(i =>
|
||||
i.OwnerTelegramId == UserId &&
|
||||
i.MediaGroupId == null &&
|
||||
i.Caption == photo.Caption),
|
||||
Arg.Any<CancellationToken>());
|
||||
|
||||
|
||||
Reference in New Issue
Block a user