mirror of
https://github.com/truewhile/MeBox.git
synced 2026-10-02 20:26:36 +08:00
feat: ffprobe + TMDb scrape + HLS transcode + history/favourites/playlists
Backend
- service/ffprobe.go: thin ffprobe wrapper, parses duration / resolution /
codecs into a typed ProbeResult. 30s per-file timeout.
- service/tmdb.go: minimal TMDb provider (search/movie). Disabled when no
api key; supports tmdb_api_proxy / tmdb_image_proxy overrides for users
behind a firewall.
- service/scraper.go: filename cleaner (handles bracketed tags, scene
noise tokens, year extraction), per-row + per-library enrichment with a
4 RPS throttle and WS hub progress events. Unit-tested.
- service/scanner.go: now invokes ffprobe per file and kicks the TMDb
scraper in the background once a library scan finishes.
- service/transcoder.go: per-media ffmpeg HLS job manager; outputs
index.m3u8 + seg_NNNNN.ts under cache/hls/<id>; cancels jobs on
shutdown; publishes 'transcode' WS events.
- service/stream.go: serves HLS playlist (with 30s wait-for-ready) and
.ts segments with path-traversal protection. Adds Probe() helper used
by the admin 'reprobe' button.
- service/image_proxy.go: cached, host-allow-listed reverse proxy for
TMDb / Bangumi / Douban / Fanart / TheTVDB images so the SPA never
hits a CORS or GFW issue.
- service/playback.go: history upsert, favourites toggle, playlist CRUD
+ ordered items. RecentHistory joins with model.Media in one extra
query so the home page can render a 'Continue Watching' row.
- handler/streaming.go + handler/playback.go: REST endpoints for HLS,
image proxy, scrape (one + library), reprobe, history, favourites,
playlists.
- handler/handler.go: registers /api/hls/:id/{index.m3u8,:seg}, /api/img,
/api/history, /api/favourites/:id, /api/playlists/* with proper
auth/admin guards.
Frontend
- api/client.ts: imageURL() helper; hlsURL() endpoint; reuses the JWT in
a query parameter for <video src> and <img src>.
- api/playback.ts: typed helpers for history, favourites, playlists.
- components/MediaCard.tsx: optional 'progress' prop renders a thin
bottom progress bar, used by the new Continue Watching row.
- pages/HomePage.tsx: two rows (Continue Watching + Recently Added);
falls back to the empty-state hint when both are empty.
- pages/PlayerPage.tsx: hls.js (lazy-imported) with auto-fallback to
direct play; ?mode=hls|direct query toggle; resume position written
every 10s while playing.
- pages/MediaDetailPage.tsx: heart toggle + admin 'rescrape' / 'reprobe'
buttons + dedicated 'HLS 转码播放' CTA.
- pages/FavouritesPage.tsx, PlaylistsPage.tsx, PlaylistDetailPage.tsx:
new screens.
- components/Layout.tsx + App.tsx: sidebar links for Favourites and
Playlists; routes are now lazily code-split via React.lazy + Suspense
so the initial bundle stays at ~243 KB / 82 KB gzipped (hls.js is
fetched only on first HLS playback).
Verified: go build, go vet, go test (incl. CleanQuery cases) all pass;
frontend tsc -b && vite build emits 9 route chunks plus a deferred hls
chunk.
This commit is contained in:
+59
-44
@@ -1,56 +1,71 @@
|
||||
import { Suspense, lazy } from 'react'
|
||||
import { Navigate, Route, Routes } from 'react-router-dom'
|
||||
|
||||
import { Layout } from './components/Layout'
|
||||
import { RequireAuth, RequireAdmin } from './components/RequireAuth'
|
||||
import { AdminPage } from './pages/AdminPage'
|
||||
import { HomePage } from './pages/HomePage'
|
||||
import { LibraryPage } from './pages/LibraryPage'
|
||||
import { RequireAdmin, RequireAuth } from './components/RequireAuth'
|
||||
import { LoginPage } from './pages/LoginPage'
|
||||
import { MediaDetailPage } from './pages/MediaDetailPage'
|
||||
import { PlayerPage } from './pages/PlayerPage'
|
||||
import { SearchPage } from './pages/SearchPage'
|
||||
|
||||
// Top-level route table.
|
||||
//
|
||||
// Public:
|
||||
// /login
|
||||
//
|
||||
// Authenticated:
|
||||
// / → home (continue watching + recently added)
|
||||
// /library/:id → library content grid
|
||||
// /search → keyword search
|
||||
// /media/:id → media detail
|
||||
// /play/:id → fullscreen player
|
||||
//
|
||||
// Admin only:
|
||||
// /admin → users / settings / activity log
|
||||
// Lazy-loaded routes — the login screen and the layout shell ship in the
|
||||
// initial bundle; everything else is fetched on first navigation.
|
||||
const HomePage = lazy(() => import('./pages/HomePage').then((m) => ({ default: m.HomePage })))
|
||||
const LibraryPage = lazy(() =>
|
||||
import('./pages/LibraryPage').then((m) => ({ default: m.LibraryPage })),
|
||||
)
|
||||
const SearchPage = lazy(() =>
|
||||
import('./pages/SearchPage').then((m) => ({ default: m.SearchPage })),
|
||||
)
|
||||
const FavouritesPage = lazy(() =>
|
||||
import('./pages/FavouritesPage').then((m) => ({ default: m.FavouritesPage })),
|
||||
)
|
||||
const PlaylistsPage = lazy(() =>
|
||||
import('./pages/PlaylistsPage').then((m) => ({ default: m.PlaylistsPage })),
|
||||
)
|
||||
const PlaylistDetailPage = lazy(() =>
|
||||
import('./pages/PlaylistDetailPage').then((m) => ({ default: m.PlaylistDetailPage })),
|
||||
)
|
||||
const MediaDetailPage = lazy(() =>
|
||||
import('./pages/MediaDetailPage').then((m) => ({ default: m.MediaDetailPage })),
|
||||
)
|
||||
const PlayerPage = lazy(() =>
|
||||
import('./pages/PlayerPage').then((m) => ({ default: m.PlayerPage })),
|
||||
)
|
||||
const AdminPage = lazy(() => import('./pages/AdminPage').then((m) => ({ default: m.AdminPage })))
|
||||
|
||||
// Fallback shown while a chunk is loading.
|
||||
const Loading = () => <p className="px-6 py-8 text-slate-500">加载中…</p>
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<Layout />
|
||||
</RequireAuth>
|
||||
}
|
||||
>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="library/:id" element={<LibraryPage />} />
|
||||
<Route path="search" element={<SearchPage />} />
|
||||
<Route path="media/:id" element={<MediaDetailPage />} />
|
||||
<Route path="play/:id" element={<PlayerPage />} />
|
||||
<Suspense fallback={<Loading />}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route
|
||||
path="admin"
|
||||
path="/"
|
||||
element={
|
||||
<RequireAdmin>
|
||||
<AdminPage />
|
||||
</RequireAdmin>
|
||||
<RequireAuth>
|
||||
<Layout />
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
>
|
||||
<Route index element={<HomePage />} />
|
||||
<Route path="library/:id" element={<LibraryPage />} />
|
||||
<Route path="search" element={<SearchPage />} />
|
||||
<Route path="favourites" element={<FavouritesPage />} />
|
||||
<Route path="playlists" element={<PlaylistsPage />} />
|
||||
<Route path="playlist/:id" element={<PlaylistDetailPage />} />
|
||||
<Route path="media/:id" element={<MediaDetailPage />} />
|
||||
<Route path="play/:id" element={<PlayerPage />} />
|
||||
<Route
|
||||
path="admin"
|
||||
element={
|
||||
<RequireAdmin>
|
||||
<AdminPage />
|
||||
</RequireAdmin>
|
||||
}
|
||||
/>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
)
|
||||
}
|
||||
|
||||
+23
-5
@@ -31,9 +31,27 @@ api.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
// Helper that returns a streaming URL with the JWT appended as a query
|
||||
// parameter so <video src> works without an Authorization header.
|
||||
export function streamURL(mediaId: string): string {
|
||||
const token = useAuthStore.getState().token ?? ''
|
||||
return `/api/stream/${encodeURIComponent(mediaId)}?token=${encodeURIComponent(token)}`
|
||||
const tokenQuery = () => {
|
||||
const t = useAuthStore.getState().token ?? ''
|
||||
return `token=${encodeURIComponent(t)}`
|
||||
}
|
||||
|
||||
// streamURL returns a direct-play URL for <video src>. The JWT is added as
|
||||
// a query parameter because <video> elements cannot send Authorization
|
||||
// headers.
|
||||
export function streamURL(mediaId: string): string {
|
||||
return `/api/stream/${encodeURIComponent(mediaId)}?${tokenQuery()}`
|
||||
}
|
||||
|
||||
// hlsURL returns the m3u8 playlist URL fed into hls.js.
|
||||
export function hlsURL(mediaId: string): string {
|
||||
return `/api/hls/${encodeURIComponent(mediaId)}/index.m3u8?${tokenQuery()}`
|
||||
}
|
||||
|
||||
// imageURL converts a remote poster URL into a same-origin proxy URL so it
|
||||
// can never be blocked by CORS / GFW. Empty strings pass through unchanged.
|
||||
export function imageURL(remote?: string): string {
|
||||
if (!remote) return ''
|
||||
if (remote.startsWith('/api/img')) return remote
|
||||
return `/api/img?url=${encodeURIComponent(remote)}&${tokenQuery()}`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { api } from './client'
|
||||
import type { Media, Playlist } from '../types'
|
||||
|
||||
// History rows arrive joined with their Media row; the backend returns null
|
||||
// for orphaned rows whose media has been removed.
|
||||
export interface HistoryItem {
|
||||
id: string
|
||||
user_id: string
|
||||
media_id: string
|
||||
position_ms: number
|
||||
duration_ms: number
|
||||
watched_at: string
|
||||
completed: boolean
|
||||
media?: Media | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface PlaylistDetail {
|
||||
playlist: Playlist
|
||||
items: Media[]
|
||||
}
|
||||
|
||||
export const playbackAPI = {
|
||||
recordProgress: (mediaId: string, positionMs: number, durationMs: number) =>
|
||||
api
|
||||
.post('/history', {
|
||||
media_id: mediaId,
|
||||
position_ms: positionMs,
|
||||
duration_ms: durationMs,
|
||||
})
|
||||
.then((r) => r.data),
|
||||
|
||||
recentHistory: () =>
|
||||
api.get<{ items: HistoryItem[] }>('/history').then((r) => r.data.items),
|
||||
|
||||
toggleFavourite: (mediaId: string) =>
|
||||
api
|
||||
.post<{ favourite: boolean }>(`/favourites/${mediaId}`)
|
||||
.then((r) => r.data.favourite),
|
||||
|
||||
listFavourites: () =>
|
||||
api.get<{ items: Media[] }>('/favourites').then((r) => r.data.items),
|
||||
|
||||
listPlaylists: () =>
|
||||
api.get<{ items: Playlist[] }>('/playlists').then((r) => r.data.items),
|
||||
|
||||
createPlaylist: (name: string, isPublic = false) =>
|
||||
api
|
||||
.post<Playlist>('/playlists', { name, is_public: isPublic })
|
||||
.then((r) => r.data),
|
||||
|
||||
getPlaylist: (id: string) =>
|
||||
api.get<PlaylistDetail>(`/playlists/${id}`).then((r) => r.data),
|
||||
|
||||
addToPlaylist: (id: string, mediaId: string) =>
|
||||
api.post(`/playlists/${id}/items`, { media_id: mediaId }).then((r) => r.data),
|
||||
|
||||
removeFromPlaylist: (id: string, mediaId: string) =>
|
||||
api.delete(`/playlists/${id}/items/${mediaId}`).then((r) => r.data),
|
||||
|
||||
deletePlaylist: (id: string) =>
|
||||
api.delete(`/playlists/${id}`).then((r) => r.data),
|
||||
}
|
||||
@@ -2,7 +2,9 @@ import { useEffect, useState } from 'react'
|
||||
import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom'
|
||||
import {
|
||||
Film,
|
||||
Heart,
|
||||
Home,
|
||||
ListMusic,
|
||||
LogOut,
|
||||
Search,
|
||||
Settings,
|
||||
@@ -43,6 +45,8 @@ export function Layout() {
|
||||
<nav className="flex-1 space-y-1">
|
||||
<SidebarLink to="/" icon={<Home size={18} />} label="首页" end />
|
||||
<SidebarLink to="/search" icon={<Search size={18} />} label="搜索" />
|
||||
<SidebarLink to="/favourites" icon={<Heart size={18} />} label="收藏" />
|
||||
<SidebarLink to="/playlists" icon={<ListMusic size={18} />} label="播放列表" />
|
||||
|
||||
<div className="mt-6 px-2 text-xs uppercase tracking-wider text-slate-500">
|
||||
媒体库
|
||||
|
||||
@@ -1,28 +1,48 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import { Film } from 'lucide-react'
|
||||
|
||||
import { imageURL } from '../api/client'
|
||||
import type { Media } from '../types'
|
||||
|
||||
// Compact poster tile used by every listing surface (home / library / search).
|
||||
export function MediaCard({ media }: { media: Media }) {
|
||||
//
|
||||
// Props:
|
||||
// - media: the Media row to render
|
||||
// - progress: 0..1 fractional resume position (optional)
|
||||
export function MediaCard({
|
||||
media,
|
||||
progress,
|
||||
}: {
|
||||
media: Media
|
||||
progress?: number
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
to={`/media/${media.id}`}
|
||||
className="group block overflow-hidden rounded-xl border border-white/5 bg-surface-800/60 transition hover:border-primary-400/50 hover:shadow-lg hover:shadow-primary-400/20"
|
||||
>
|
||||
<div className="aspect-[2/3] w-full bg-surface-900">
|
||||
<div className="relative aspect-[2/3] w-full bg-surface-900">
|
||||
{media.poster_url ? (
|
||||
<img
|
||||
src={media.poster_url}
|
||||
src={imageURL(media.poster_url)}
|
||||
alt={media.title}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover transition group-hover:scale-105"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-slate-600">
|
||||
<Film size={48} />
|
||||
</div>
|
||||
)}
|
||||
{progress !== undefined && progress > 0 && progress < 1 && (
|
||||
<div className="absolute inset-x-0 bottom-0 h-1 bg-black/60">
|
||||
<div
|
||||
className="h-full bg-primary-400"
|
||||
style={{ width: `${Math.round(progress * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="px-3 py-2">
|
||||
<p className="truncate text-sm font-medium text-white">{media.title}</p>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { playbackAPI } from '../api/playback'
|
||||
import { MediaCard } from '../components/MediaCard'
|
||||
import type { Media } from '../types'
|
||||
|
||||
export function FavouritesPage() {
|
||||
const [items, setItems] = useState<Media[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
playbackAPI
|
||||
.listFavourites()
|
||||
.then(setItems)
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="font-display text-3xl font-bold text-white">我的收藏</h1>
|
||||
{loading && <p className="text-slate-500">加载中…</p>}
|
||||
{!loading && items.length === 0 && (
|
||||
<p className="text-slate-400">还没有任何收藏,点击媒体详情页的「收藏」按钮添加。</p>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{items.map((m) => (
|
||||
<MediaCard key={m.id} media={m} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+51
-16
@@ -1,32 +1,61 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
import { mediaAPI } from '../api/library'
|
||||
import { playbackAPI, type HistoryItem } from '../api/playback'
|
||||
import { MediaCard } from '../components/MediaCard'
|
||||
import type { Media } from '../types'
|
||||
|
||||
// Landing page: shows the most recently added media items across every
|
||||
// library. Once the scraper / continue-watching subsystems land we will
|
||||
// fold in additional rows here.
|
||||
// Landing page composes three rows:
|
||||
// 1. Continue Watching — items with a positive position from the user's
|
||||
// playback history (excluding completed ones).
|
||||
// 2. Recently Added — most recent media across every library.
|
||||
// 3. Empty state hint — shown when both rows are empty.
|
||||
export function HomePage() {
|
||||
const [items, setItems] = useState<Media[]>([])
|
||||
const [recent, setRecent] = useState<Media[]>([])
|
||||
const [history, setHistory] = useState<HistoryItem[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
mediaAPI
|
||||
.search('', 24)
|
||||
.then((d) => setItems(d.items))
|
||||
Promise.all([
|
||||
mediaAPI.search('', 24).then((d) => d.items),
|
||||
playbackAPI.recentHistory().catch(() => [] as HistoryItem[]),
|
||||
])
|
||||
.then(([items, hist]) => {
|
||||
setRecent(items)
|
||||
setHistory(hist.filter((h) => !h.completed && !!h.media))
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
const empty = !loading && recent.length === 0 && history.length === 0
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="space-y-10">
|
||||
<header>
|
||||
<h1 className="font-display text-3xl font-bold text-white">最近添加</h1>
|
||||
<p className="text-sm text-slate-400">最新被扫描入库的媒体内容</p>
|
||||
<h1 className="font-display text-3xl font-bold text-white">主页</h1>
|
||||
<p className="text-sm text-slate-400">从你上次离开的地方继续</p>
|
||||
</header>
|
||||
|
||||
{history.length > 0 && (
|
||||
<Row title="继续观看">
|
||||
{history.map((h) => {
|
||||
const m = h.media!
|
||||
const progress = h.duration_ms > 0 ? h.position_ms / h.duration_ms : 0
|
||||
return <MediaCard key={h.id} media={m} progress={progress} />
|
||||
})}
|
||||
</Row>
|
||||
)}
|
||||
|
||||
{recent.length > 0 && (
|
||||
<Row title="最近添加">
|
||||
{recent.map((m) => (
|
||||
<MediaCard key={m.id} media={m} />
|
||||
))}
|
||||
</Row>
|
||||
)}
|
||||
|
||||
{loading && <p className="text-slate-500">加载中…</p>}
|
||||
{!loading && items.length === 0 && (
|
||||
{empty && (
|
||||
<div className="glass-panel">
|
||||
<p className="text-slate-300">
|
||||
还没有任何媒体。前往 <span className="text-primary-400">管理后台</span>{' '}
|
||||
@@ -34,11 +63,17 @@ export function HomePage() {
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{items.map((m) => (
|
||||
<MediaCard key={m.id} media={m} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Row({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-display text-xl font-semibold text-white">{title}</h2>
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{children}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { Play } from 'lucide-react'
|
||||
import { Heart, Play, RefreshCw, Sparkles } from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
|
||||
import { mediaAPI } from '../api/library'
|
||||
import { playbackAPI } from '../api/playback'
|
||||
import { imageURL } from '../api/client'
|
||||
import { useAuthStore } from '../stores/auth'
|
||||
import { api } from '../api/client'
|
||||
import type { Media } from '../types'
|
||||
|
||||
function fmtDuration(sec: number): string {
|
||||
@@ -24,21 +29,58 @@ function fmtSize(bytes: number): string {
|
||||
return `${v.toFixed(2)} ${units[i]}`
|
||||
}
|
||||
|
||||
// Detail screen for a single media item: poster, summary and a Play CTA.
|
||||
// Detail screen for a single media item.
|
||||
//
|
||||
// Buttons:
|
||||
// - Play (direct play)
|
||||
// - HLS (force transcoded play)
|
||||
// - Favourite (toggle, all users)
|
||||
// - Re-scrape (admin only, triggers TMDb lookup)
|
||||
// - Re-probe (admin only, refreshes ffprobe metadata)
|
||||
export function MediaDetailPage() {
|
||||
const { id = '' } = useParams()
|
||||
const role = useAuthStore((s) => s.user?.role)
|
||||
const [media, setMedia] = useState<Media | null>(null)
|
||||
const [favourite, setFavourite] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = async () => {
|
||||
if (!id) return
|
||||
setLoading(true)
|
||||
mediaAPI
|
||||
.get(id)
|
||||
.then(setMedia)
|
||||
.finally(() => setLoading(false))
|
||||
try {
|
||||
const m = await mediaAPI.get(id)
|
||||
setMedia(m)
|
||||
const favs = await playbackAPI.listFavourites().catch(() => [])
|
||||
setFavourite(favs.some((f) => f.id === m.id))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
refresh().catch(() => undefined)
|
||||
}, [id])
|
||||
|
||||
const toggleFav = async () => {
|
||||
if (!media) return
|
||||
const state = await playbackAPI.toggleFavourite(media.id)
|
||||
setFavourite(state)
|
||||
toast.success(state ? '已加入收藏' : '已取消收藏')
|
||||
}
|
||||
|
||||
const rescrape = async () => {
|
||||
if (!media) return
|
||||
await api.post(`/media/${media.id}/scrape`)
|
||||
toast.success('已刮削')
|
||||
await refresh()
|
||||
}
|
||||
|
||||
const reprobe = async () => {
|
||||
if (!media) return
|
||||
await api.post(`/media/${media.id}/probe`)
|
||||
toast.success('已重新探测')
|
||||
await refresh()
|
||||
}
|
||||
|
||||
if (loading) return <p className="text-slate-500">加载中…</p>
|
||||
if (!media) return <p className="text-slate-500">媒体不存在</p>
|
||||
|
||||
@@ -47,7 +89,12 @@ export function MediaDetailPage() {
|
||||
<div className="flex flex-col gap-6 md:flex-row">
|
||||
<div className="aspect-[2/3] w-48 shrink-0 overflow-hidden rounded-xl bg-surface-800">
|
||||
{media.poster_url ? (
|
||||
<img src={media.poster_url} alt={media.title} className="h-full w-full object-cover" />
|
||||
<img
|
||||
src={imageURL(media.poster_url)}
|
||||
alt={media.title}
|
||||
className="h-full w-full object-cover"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-slate-600">
|
||||
无海报
|
||||
@@ -69,11 +116,42 @@ export function MediaDetailPage() {
|
||||
<Badge>{fmtDuration(media.duration_sec)}</Badge>
|
||||
<Badge>{fmtSize(media.size_bytes)}</Badge>
|
||||
{media.container && <Badge>{media.container.toUpperCase()}</Badge>}
|
||||
<Badge>{media.scrape_status}</Badge>
|
||||
</div>
|
||||
|
||||
<Link to={`/play/${media.id}`} className="neon-button">
|
||||
<Play size={18} /> 播放
|
||||
</Link>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link to={`/play/${media.id}`} className="neon-button">
|
||||
<Play size={18} /> 播放
|
||||
</Link>
|
||||
<Link
|
||||
to={`/play/${media.id}?mode=hls`}
|
||||
className="neon-button !border-accent-400/40 !bg-accent-400/10 !text-accent-400 hover:!border-accent-400"
|
||||
>
|
||||
<RefreshCw size={16} /> HLS 转码播放
|
||||
</Link>
|
||||
<button
|
||||
onClick={toggleFav}
|
||||
className={
|
||||
'neon-button ' +
|
||||
(favourite
|
||||
? '!border-pink-400/60 !bg-pink-400/10 !text-pink-400'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
<Heart size={16} fill={favourite ? 'currentColor' : 'none'} />
|
||||
{favourite ? '已收藏' : '收藏'}
|
||||
</button>
|
||||
{role === 'admin' && (
|
||||
<>
|
||||
<button onClick={rescrape} className="neon-button">
|
||||
<Sparkles size={16} /> 重新刮削
|
||||
</button>
|
||||
<button onClick={reprobe} className="neon-button">
|
||||
<RefreshCw size={16} /> 重新探测
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -82,6 +160,8 @@ export function MediaDetailPage() {
|
||||
|
||||
function Badge({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<span className="rounded border border-white/10 bg-white/5 px-2 py-0.5">{children}</span>
|
||||
<span className="rounded border border-white/10 bg-white/5 px-2 py-0.5">
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
+145
-10
@@ -1,24 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { ArrowLeft } from 'lucide-react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import type Hls from 'hls.js'
|
||||
import { ArrowLeft, RefreshCw, Sparkles } from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
|
||||
import { mediaAPI } from '../api/library'
|
||||
import { streamURL } from '../api/client'
|
||||
import { hlsURL, streamURL } from '../api/client'
|
||||
import { playbackAPI } from '../api/playback'
|
||||
import type { Media } from '../types'
|
||||
|
||||
// Fullscreen, dark-themed video page. We currently use direct play via
|
||||
// /api/stream/:id — the future task is wiring HLS.js for transcoded streams.
|
||||
type Mode = 'direct' | 'hls'
|
||||
|
||||
// Fullscreen, dark-themed video page.
|
||||
//
|
||||
// ?mode=hls force HLS even when direct play would work
|
||||
// ?mode=direct force direct play (default for browser-friendly codecs)
|
||||
//
|
||||
// We pick a sensible default based on the source codec: H.264 + AAC in
|
||||
// MP4 / WebM containers play directly; everything else (HEVC, MKV, AV1,
|
||||
// AC3 audio, …) gets routed through ffmpeg → HLS.
|
||||
export function PlayerPage() {
|
||||
const { id = '' } = useParams()
|
||||
const [params, setParams] = useSearchParams()
|
||||
const navigate = useNavigate()
|
||||
const ref = useRef<HTMLVideoElement>(null)
|
||||
const [media, setMedia] = useState<Media | null>(null)
|
||||
|
||||
const ref = useRef<HTMLVideoElement>(null)
|
||||
const hlsRef = useRef<Hls | null>(null)
|
||||
const lastSentRef = useRef(0)
|
||||
|
||||
const [media, setMedia] = useState<Media | null>(null)
|
||||
const [mode, setMode] = useState<Mode>('direct')
|
||||
|
||||
// Load metadata and pick a default mode.
|
||||
useEffect(() => {
|
||||
if (!id) return
|
||||
mediaAPI.get(id).then(setMedia)
|
||||
}, [id])
|
||||
mediaAPI.get(id).then((m) => {
|
||||
setMedia(m)
|
||||
const forced = params.get('mode') as Mode | null
|
||||
const auto = pickMode(m)
|
||||
setMode(forced ?? auto)
|
||||
})
|
||||
}, [id, params])
|
||||
|
||||
// Wire up the actual <video> element when we know the mode.
|
||||
useEffect(() => {
|
||||
if (!media || !ref.current) return
|
||||
teardownHls()
|
||||
|
||||
const video = ref.current
|
||||
let cancelled = false
|
||||
|
||||
if (mode === 'hls') {
|
||||
const url = hlsURL(media.id)
|
||||
// Lazy import keeps the main bundle ~530 KB smaller until the user
|
||||
// actually hits HLS playback.
|
||||
void import('hls.js').then(({ default: HlsCtor }) => {
|
||||
if (cancelled) return
|
||||
if (HlsCtor.isSupported()) {
|
||||
const hls = new HlsCtor({ enableWorker: true, lowLatencyMode: false })
|
||||
hls.loadSource(url)
|
||||
hls.attachMedia(video)
|
||||
hls.on(HlsCtor.Events.ERROR, (_, data) => {
|
||||
if (data.fatal) {
|
||||
toast.error('HLS 播放失败,尝试切换到直接播放')
|
||||
setMode('direct')
|
||||
params.set('mode', 'direct')
|
||||
setParams(params, { replace: true })
|
||||
}
|
||||
})
|
||||
hlsRef.current = hls
|
||||
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
video.src = url
|
||||
} else {
|
||||
toast.error('当前浏览器不支持 HLS,降级到直接播放')
|
||||
setMode('direct')
|
||||
}
|
||||
void video.play().catch(() => undefined)
|
||||
})
|
||||
} else {
|
||||
video.src = streamURL(media.id)
|
||||
void video.play().catch(() => undefined)
|
||||
}
|
||||
return () => {
|
||||
cancelled = true
|
||||
teardownHls()
|
||||
}
|
||||
}, [media, mode, params, setParams])
|
||||
|
||||
// Persist resume position every 10 seconds while playing.
|
||||
useEffect(() => {
|
||||
if (!media || !ref.current) return
|
||||
const video = ref.current
|
||||
const handler = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastSentRef.current < 10_000) return
|
||||
lastSentRef.current = now
|
||||
const positionMs = Math.floor(video.currentTime * 1000)
|
||||
const durationMs = Math.floor((video.duration || 0) * 1000)
|
||||
if (positionMs > 0) {
|
||||
playbackAPI.recordProgress(media.id, positionMs, durationMs).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
video.addEventListener('timeupdate', handler)
|
||||
video.addEventListener('pause', handler)
|
||||
return () => {
|
||||
video.removeEventListener('timeupdate', handler)
|
||||
video.removeEventListener('pause', handler)
|
||||
}
|
||||
}, [media])
|
||||
|
||||
// ESC = back.
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') navigate(-1)
|
||||
@@ -27,6 +118,13 @@ export function PlayerPage() {
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [navigate])
|
||||
|
||||
const teardownHls = () => {
|
||||
if (hlsRef.current) {
|
||||
hlsRef.current.destroy()
|
||||
hlsRef.current = null
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="-m-6 flex min-h-screen flex-col bg-black md:-m-8">
|
||||
<button
|
||||
@@ -35,11 +133,32 @@ export function PlayerPage() {
|
||||
>
|
||||
<ArrowLeft size={16} /> 返回
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
const next = mode === 'hls' ? 'direct' : 'hls'
|
||||
setMode(next)
|
||||
params.set('mode', next)
|
||||
setParams(params, { replace: true })
|
||||
}}
|
||||
className="absolute right-4 top-4 z-10 flex items-center gap-2 rounded-full bg-black/60 px-3 py-1.5 text-sm text-white backdrop-blur transition hover:bg-black/80"
|
||||
title="切换播放模式"
|
||||
>
|
||||
{mode === 'hls' ? (
|
||||
<>
|
||||
<RefreshCw size={14} /> HLS 转码中
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles size={14} /> 直接播放
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
{media ? (
|
||||
<video
|
||||
ref={ref}
|
||||
src={streamURL(media.id)}
|
||||
controls
|
||||
autoPlay
|
||||
className="max-h-screen w-full max-w-[1600px] bg-black"
|
||||
@@ -51,3 +170,19 @@ export function PlayerPage() {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const directContainers = ['mp4', 'webm', 'm4v']
|
||||
const directVideoCodecs = ['h264', 'avc', 'avc1']
|
||||
const directAudioCodecs = ['aac', 'mp3', 'opus']
|
||||
|
||||
// pickMode picks 'direct' when the source is browser-friendly, otherwise
|
||||
// 'hls' so the user gets a working stream out of the box.
|
||||
function pickMode(m: Media): Mode {
|
||||
const c = (m.container ?? '').toLowerCase()
|
||||
const v = (m.video_codec ?? '').toLowerCase()
|
||||
const a = (m.audio_codec ?? '').toLowerCase()
|
||||
const containerOK = directContainers.some((x) => c.includes(x))
|
||||
const videoOK = !v || directVideoCodecs.some((x) => v.includes(x))
|
||||
const audioOK = !a || directAudioCodecs.some((x) => a.includes(x))
|
||||
return containerOK && videoOK && audioOK ? 'direct' : 'hls'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { X } from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
|
||||
import { playbackAPI, type PlaylistDetail } from '../api/playback'
|
||||
import { MediaCard } from '../components/MediaCard'
|
||||
|
||||
export function PlaylistDetailPage() {
|
||||
const { id = '' } = useParams()
|
||||
const [detail, setDetail] = useState<PlaylistDetail | null>(null)
|
||||
|
||||
const refresh = () =>
|
||||
playbackAPI.getPlaylist(id).then(setDetail).catch(() => setDetail(null))
|
||||
|
||||
useEffect(() => {
|
||||
refresh()
|
||||
}, [id])
|
||||
|
||||
if (!detail) {
|
||||
return <p className="text-slate-500">加载中…</p>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<header>
|
||||
<h1 className="font-display text-3xl font-bold text-white">{detail.playlist.name}</h1>
|
||||
<p className="text-sm text-slate-400">{detail.items.length} 部影片</p>
|
||||
</header>
|
||||
|
||||
{detail.items.length === 0 && (
|
||||
<p className="text-slate-400">暂无内容,前往媒体详情页通过「加入播放列表」添加。</p>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{detail.items.map((m) => (
|
||||
<div key={m.id} className="relative">
|
||||
<MediaCard media={m} />
|
||||
<button
|
||||
className="absolute right-2 top-2 rounded-full bg-black/70 p-1 text-white transition hover:bg-red-600"
|
||||
onClick={async () => {
|
||||
await playbackAPI.removeFromPlaylist(detail.playlist.id, m.id)
|
||||
toast.success('已移除')
|
||||
await refresh()
|
||||
}}
|
||||
title="从播放列表移除"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { FormEvent, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ListPlus, Trash2 } from 'lucide-react'
|
||||
import toast from 'react-hot-toast'
|
||||
|
||||
import { playbackAPI } from '../api/playback'
|
||||
import type { Playlist } from '../types'
|
||||
|
||||
// Landing page for playlists. Lists every playlist owned by the current
|
||||
// user and lets them create / delete one.
|
||||
export function PlaylistsPage() {
|
||||
const [items, setItems] = useState<Playlist[]>([])
|
||||
const [name, setName] = useState('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const refresh = () =>
|
||||
playbackAPI
|
||||
.listPlaylists()
|
||||
.then(setItems)
|
||||
.finally(() => setLoading(false))
|
||||
|
||||
useEffect(() => {
|
||||
refresh().catch(() => undefined)
|
||||
}, [])
|
||||
|
||||
const onCreate = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
try {
|
||||
await playbackAPI.createPlaylist(name)
|
||||
toast.success('已创建')
|
||||
setName('')
|
||||
await refresh()
|
||||
} catch {
|
||||
toast.error('创建失败')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h1 className="font-display text-3xl font-bold text-white">播放列表</h1>
|
||||
|
||||
<form onSubmit={onCreate} className="glass-panel grid gap-3 md:grid-cols-[1fr_auto]">
|
||||
<input
|
||||
required
|
||||
className="input-base"
|
||||
placeholder="新播放列表名称"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<button type="submit" className="neon-button">
|
||||
<ListPlus size={16} /> 新建
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{loading && <p className="text-slate-500">加载中…</p>}
|
||||
{!loading && items.length === 0 && <p className="text-slate-400">还没有任何播放列表。</p>}
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
|
||||
{items.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="glass-panel flex items-center justify-between !p-4"
|
||||
>
|
||||
<Link
|
||||
to={`/playlist/${p.id}`}
|
||||
className="font-medium text-white transition hover:text-primary-400"
|
||||
>
|
||||
{p.name}
|
||||
{p.is_public && (
|
||||
<span className="ml-2 rounded border border-primary-400/40 px-1.5 py-0.5 text-xs text-primary-400">
|
||||
public
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (!confirm(`删除「${p.name}」?`)) return
|
||||
await playbackAPI.deletePlaylist(p.id)
|
||||
toast.success('已删除')
|
||||
await refresh()
|
||||
}}
|
||||
className="rounded border border-red-400/40 px-2 py-1 text-xs text-red-400 hover:bg-red-400/10"
|
||||
>
|
||||
<Trash2 size={12} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -51,10 +51,20 @@ export interface Media {
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface Playlist {
|
||||
id: string
|
||||
user_id: string
|
||||
name: string
|
||||
is_public: boolean
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface ScanResult {
|
||||
library_id: string
|
||||
visited: number
|
||||
added: number
|
||||
probed: number
|
||||
}
|
||||
|
||||
export interface Setting {
|
||||
|
||||
Reference in New Issue
Block a user