Refactor media asset handling: update ListMediaAssetsQuery to accept an array of statuses, modify MediaEndpoints to handle multiple statuses, and enhance MediaProcessingQueue for improved signal handling. Update frontend components to support new status filtering and improve user experience with asset selection.
This commit is contained in:
@@ -1,21 +1,37 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query'
|
||||
import { Link } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ChevronLeft } from 'lucide-react'
|
||||
import { HttpError } from '@/shared/api/client'
|
||||
import type { MediaAssetDto } from '@/shared/api/types'
|
||||
import { Badge } from '@/shared/ui/badge'
|
||||
import { Button } from '@/shared/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
|
||||
import { Input } from '@/shared/ui/input'
|
||||
import { toast } from '@/shared/ui/toast-store'
|
||||
import { listMedia } from '@/features/admin/media/api'
|
||||
import { formatDuration } from '@/features/admin/media/MediaPanel'
|
||||
import { addEpisode, getShow, removeEpisode } from './api'
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, '0')
|
||||
|
||||
/** Достаёт сезон/серию из имени файла: SxxEyy либо NxNN. Нужно для сортировки в правильный порядок. */
|
||||
function parseEpisode(name: string): { season: number; episode: number } | null {
|
||||
const m1 = name.match(/[Ss](\d{1,2})[ ._-]*[Ee](\d{1,3})/)
|
||||
if (m1) return { season: Number(m1[1]), episode: Number(m1[2]) }
|
||||
const m2 = name.match(/(?:^|[^\d])(\d{1,2})x(\d{1,3})(?:[^\d]|$)/i)
|
||||
if (m2) return { season: Number(m2[1]), episode: Number(m2[2]) }
|
||||
return null
|
||||
}
|
||||
|
||||
type Candidate = { asset: MediaAssetDto; se: { season: number; episode: number } | null }
|
||||
|
||||
export function ShowDetail({ showId }: { showId: string }) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const [assetId, setAssetId] = useState('')
|
||||
const [filter, setFilter] = useState('')
|
||||
const [deselected, setDeselected] = useState<Set<string>>(new Set())
|
||||
const [adding, setAdding] = useState<{ current: number; total: number } | null>(null)
|
||||
|
||||
const { data: show, isLoading } = useQuery({
|
||||
queryKey: ['admin', 'shows', showId],
|
||||
@@ -23,30 +39,70 @@ export function ShowDetail({ showId }: { showId: string }) {
|
||||
})
|
||||
const { data: ready } = useQuery({
|
||||
queryKey: ['admin', 'media', 'ready'],
|
||||
queryFn: () => listMedia({ page: 1, pageSize: 100, status: 'Ready' }),
|
||||
queryFn: () => listMedia({ page: 1, pageSize: 500, statuses: ['Ready'] }),
|
||||
})
|
||||
|
||||
const invalidate = () => queryClient.invalidateQueries({ queryKey: ['admin', 'shows', showId] })
|
||||
const onError = (error: unknown) =>
|
||||
toast.error(error instanceof HttpError ? error.detail : t('common.error'))
|
||||
|
||||
const addMutation = useMutation({
|
||||
mutationFn: () => addEpisode(showId, assetId),
|
||||
onSuccess: () => {
|
||||
setAssetId('')
|
||||
invalidate()
|
||||
},
|
||||
onError,
|
||||
})
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (episodeId: string) => removeEpisode(showId, episodeId),
|
||||
onSuccess: invalidate,
|
||||
onError,
|
||||
})
|
||||
|
||||
// Кандидаты: готовые ассеты, ещё не добавленные в шоу, отфильтрованные по строке и упорядоченные
|
||||
// по распознанному номеру сезона/серии (нераспознанные — в конец по имени).
|
||||
const candidates = useMemo<Candidate[]>(() => {
|
||||
if (!show) return []
|
||||
const existing = new Set(show.episodes.map((e) => e.mediaAssetId))
|
||||
const term = filter.trim().toLowerCase()
|
||||
return (ready?.items ?? [])
|
||||
.filter((a) => !existing.has(a.id))
|
||||
.filter((a) => !term || a.originalFileName.toLowerCase().includes(term))
|
||||
.map((asset) => ({ asset, se: parseEpisode(asset.originalFileName) }))
|
||||
.sort((a, b) => {
|
||||
if (a.se && b.se)
|
||||
return a.se.season - b.se.season || a.se.episode - b.se.episode
|
||||
if (a.se) return -1
|
||||
if (b.se) return 1
|
||||
return a.asset.originalFileName.localeCompare(b.asset.originalFileName)
|
||||
})
|
||||
}, [show, ready, filter])
|
||||
|
||||
const selected = candidates.filter((c) => !deselected.has(c.asset.id))
|
||||
|
||||
if (isLoading || !show) return <p className="text-muted-foreground">{t('common.loading')}</p>
|
||||
|
||||
const canAdd = show.kind !== 'Single' || show.episodes.length === 0
|
||||
const isSingle = show.kind === 'Single'
|
||||
const canAdd = !isSingle || show.episodes.length === 0
|
||||
const toggle = (id: string) =>
|
||||
setDeselected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
|
||||
const bulkAdd = async () => {
|
||||
// Полнометражке — максимум одна серия.
|
||||
const items = isSingle ? selected.slice(0, 1) : selected
|
||||
let added = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
setAdding({ current: i + 1, total: items.length })
|
||||
try {
|
||||
await addEpisode(showId, items[i].asset.id)
|
||||
added++
|
||||
} catch (error) {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
setAdding(null)
|
||||
setDeselected(new Set())
|
||||
void invalidate()
|
||||
if (added > 0) toast.success(t('admin.shows.addedCount', { count: added }))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
@@ -65,22 +121,58 @@ export function ShowDetail({ showId }: { showId: string }) {
|
||||
</div>
|
||||
|
||||
{canAdd && (
|
||||
<div className="flex flex-wrap items-end gap-2">
|
||||
<Select value={assetId} onValueChange={setAssetId}>
|
||||
<SelectTrigger className="max-w-md">
|
||||
<SelectValue placeholder={t('admin.shows.pickAsset')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ready?.items.map((asset) => (
|
||||
<SelectItem key={asset.id} value={asset.id}>
|
||||
{asset.originalFileName}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button size="sm" disabled={!assetId || addMutation.isPending} onClick={() => addMutation.mutate()}>
|
||||
{t('admin.shows.addEpisode')}
|
||||
</Button>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="max-w-md"
|
||||
placeholder={t('admin.shows.filterAssets')}
|
||||
value={filter}
|
||||
onChange={(e) => setFilter(e.target.value)}
|
||||
/>
|
||||
<Button size="sm" variant="outline" onClick={() => setDeselected(new Set())}>
|
||||
{t('admin.shows.selectAll')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setDeselected(new Set(candidates.map((c) => c.asset.id)))}
|
||||
>
|
||||
{t('admin.shows.deselectAll')}
|
||||
</Button>
|
||||
<Button size="sm" disabled={selected.length === 0 || adding != null} onClick={() => void bulkAdd()}>
|
||||
{adding
|
||||
? `${adding.current}/${adding.total}`
|
||||
: `${t('admin.shows.addSelected')} (${isSingle ? Math.min(1, selected.length) : selected.length})`}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="crt-panel max-h-72 overflow-y-auto rounded-md">
|
||||
{candidates.length === 0 ? (
|
||||
<p className="px-4 py-3 text-sm text-muted-foreground">{t('admin.shows.noMatches')}</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-border text-sm">
|
||||
{candidates.map(({ asset, se }) => (
|
||||
<li key={asset.id}>
|
||||
<label className="flex cursor-pointer items-center gap-3 px-4 py-2 hover:bg-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={!deselected.has(asset.id)}
|
||||
onChange={() => toggle(asset.id)}
|
||||
/>
|
||||
{se ? (
|
||||
<Badge>
|
||||
S{pad2(se.season)}E{pad2(se.episode)}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="muted">—</Badge>
|
||||
)}
|
||||
<span className="truncate">{asset.originalFileName}</span>
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user