Files
MeBox/web/src/pages/ProfileManagementPage.tsx
T

521 lines
18 KiB
TypeScript

import { FormEvent, useEffect, useMemo, useState } from 'react'
import { Loader2, Pencil, Plus, Trash2, UserCog } from 'lucide-react'
import toast from 'react-hot-toast'
import { libraryAPI } from '../api/library'
import { playProfilesAPI, type PlayProfileInput } from '../api/play_profiles'
import { useAuthStore } from '../stores/auth'
import { usePlayProfileStore } from '../stores/playProfile'
import { confirmAction } from '../components/ConfirmDialog'
import { requestPassword } from '../components/PasswordDialog'
import { requestPIN } from '../components/PinDialog'
import type { Library, PlayProfile } from '../types'
const MAX_PLAY_PROFILES = 3
// ProfileManagementPage replicates the Vue ProfileManagementView. It
// lets each user define private "viewing personas" with
// different content-rating gates, library access, and player defaults.
//
// All persistence is real: data is written to /api/play-profiles which
// is backed by the Go PlayProfileService.
export function ProfileManagementPage() {
const userID = useAuthStore((s) => s.user?.id ?? '')
const activeProfileId = usePlayProfileStore((s) => s.activeProfileId)
const setActiveProfile = usePlayProfileStore((s) => s.setActiveProfile)
const [profiles, setProfiles] = useState<PlayProfile[]>([])
const [libraries, setLibraries] = useState<Library[]>([])
const [loading, setLoading] = useState(true)
const [editing, setEditing] = useState<PlayProfile | null>(null)
const [showForm, setShowForm] = useState(false)
const refresh = async () => {
setLoading(true)
try {
const [p, l] = await Promise.all([
playProfilesAPI.list(),
libraryAPI.list().catch(() => [] as Library[]),
])
setProfiles(p)
setLibraries(l)
} finally {
setLoading(false)
}
}
useEffect(() => {
refresh().catch(() => undefined)
}, [])
const onDelete = async (p: PlayProfile) => {
if (!(await confirmAction({ title: '删除播放档案', message: `确定删除 Profile「${p.name}」? 删除前需要再次验证。`, confirmText: '继续删除' }))) return
try {
const proof: { pin?: string; password?: string } = {}
if (p.require_pin) {
const pin = await requestPIN({
title: '删除 Profile 需要 PIN',
message: `请输入「${p.name}」的 PIN;也可以取消后改用账号密码删除。`,
profileName: p.name,
})
if (!pin) return
proof.pin = pin
} else {
const password = await requestPassword({
title: '删除 Profile 需要密码',
message: `请输入当前账号密码以删除「${p.name}」。`,
confirmText: '删除',
})
if (!password) return
proof.password = password
}
await playProfilesAPI.remove(p.id, proof)
toast.success('已删除')
await refresh()
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ?? '删除失败'
toast.error(msg)
}
}
const openCreate = () => {
if (profiles.length >= MAX_PLAY_PROFILES) {
toast.error(`每个用户最多只能创建 ${MAX_PLAY_PROFILES} 个观影 Profile`)
return
}
setEditing(null)
setShowForm(true)
}
const openEdit = (p: PlayProfile) => {
setEditing(p)
setShowForm(true)
}
const selectProfile = async (profile: PlayProfile) => {
if (profile.user_id !== userID) {
toast.error('只能切换当前账号自己的 Profile')
return
}
try {
let pinToken: string | null = null
if (profile.require_pin) {
const pin = await requestPIN({ profileName: profile.name })
if (!pin) return
const verified = await playProfilesAPI.verifyPin(profile.id, pin)
pinToken = verified.token
}
setActiveProfile(profile.id, pinToken)
toast.success(`已切换到「${profile.name}」`)
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ?? 'PIN 验证失败'
toast.error(msg)
}
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-xl bg-purple-400/10 text-purple-400">
<UserCog size={20} />
</div>
<div>
<h1 className="font-display text-3xl font-bold text-ink-600">观影 Profile</h1>
<p className="text-sm text-ink-50">
为不同场景(儿童 / 影院 / 成人)定义独立的内容分级和媒体库访问规则
</p>
</div>
</div>
<button
onClick={openCreate}
disabled={profiles.length >= MAX_PLAY_PROFILES}
className="neon-button disabled:cursor-not-allowed disabled:opacity-50"
title={`每个用户最多 ${MAX_PLAY_PROFILES} 个 Profile`}
>
<Plus size={16} /> 创建 Profile
</button>
</div>
<div className="rounded-2xl border border-primary-400/15 bg-primary-400/5 px-4 py-3 text-sm text-ink-100">
当前账号已创建 {profiles.length}/{MAX_PLAY_PROFILES} 个 Profile。Profile 仅当前用户可见,不会与其他用户共享。
</div>
{loading && (
<div className="flex justify-center py-12 text-ink-50">
<Loader2 className="animate-spin" />
</div>
)}
{!loading && profiles.length === 0 && (
<div className="glass-panel py-12 text-center">
<div className="mb-2 text-4xl">👤</div>
<p className="font-medium text-ink-600">暂无 Profile</p>
<p className="text-sm text-ink-50">点击右上角"创建 Profile"开始</p>
</div>
)}
{!loading && profiles.length > 0 && (
<div className="grid gap-3">
{profiles.map((p) => (
<ProfileCard
key={p.id}
profile={p}
libraries={libraries}
active={activeProfileId === p.id || (!activeProfileId && p.is_default)}
onSelect={() => selectProfile(p)}
onEdit={() => openEdit(p)}
onDelete={() => onDelete(p)}
/>
))}
</div>
)}
{showForm && (
<ProfileFormModal
editing={editing}
libraries={libraries}
defaultUserID={userID}
onClose={() => setShowForm(false)}
onSaved={async () => {
setShowForm(false)
await refresh()
}}
/>
)}
</div>
)
}
function ProfileCard({
profile,
libraries,
active,
onSelect,
onEdit,
onDelete,
}: {
profile: PlayProfile
libraries: Library[]
active: boolean
onSelect: () => void
onEdit: () => void
onDelete: () => void
}) {
const libNames = useMemo(() => {
if (!profile.allowed_library_ids?.length) return '全部'
const idx = new Map(libraries.map((l) => [l.id, l.name]))
return profile.allowed_library_ids.map((id) => idx.get(id) ?? id).join(', ')
}, [profile, libraries])
return (
<div className="glass-panel flex items-start justify-between gap-4">
<div className="flex min-w-0 items-start gap-3">
<div
className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full text-lg font-bold text-ink-600"
style={{
background: `hsl(${(profile.name.charCodeAt(0) * 47) % 360}, 60%, 35%)`,
}}
>
{profile.name[0]?.toUpperCase()}
</div>
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold text-ink-600">{profile.name}</span>
{profile.is_default && (
<span className="rounded-lg bg-primary-400/20 px-2 py-0.5 text-xs text-brand-500">
默认
</span>
)}
{active && (
<span className="rounded-lg bg-gray-950 px-2 py-0.5 text-xs text-white">
当前使用
</span>
)}
{profile.allow_adult && (
<span className="rounded-lg bg-red-400/20 px-2 py-0.5 text-xs text-red-400">
成人内容
</span>
)}
{profile.require_pin && (
<span className="rounded-lg bg-amber-400/20 px-2 py-0.5 text-xs text-amber-400">
🔒 PIN
</span>
)}
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-50">
{profile.content_rating_limit && <span>分级: {profile.content_rating_limit}</span>}
<span>媒体库: {libNames}</span>
</div>
<div className="text-xs text-sand-500">
观看时长 {Math.round(profile.total_watch_time / 3600)} 小时
{profile.last_active_at && ` · 最近活跃 ${new Date(profile.last_active_at).toLocaleDateString()}`}
</div>
</div>
</div>
<div className="flex shrink-0 gap-2">
<button
onClick={onSelect}
className="rounded-lg border border-primary-400/40 px-2 py-1 text-xs text-brand-500 hover:bg-primary-400/10"
>
设为当前
</button>
<button
onClick={onEdit}
className="rounded-lg border border-gray-200 px-2 py-1 text-xs text-ink-100 hover:border-primary-400/40 hover:text-brand-500"
>
<Pencil size={12} className="inline" /> 编辑
</button>
<button
onClick={onDelete}
className="rounded-lg border border-red-400/40 px-2 py-1 text-xs text-red-400 hover:bg-red-400/10"
>
<Trash2 size={12} className="inline" /> 删除
</button>
</div>
</div>
)
}
function ProfileFormModal({
editing,
libraries,
defaultUserID,
onClose,
onSaved,
}: {
editing: PlayProfile | null
libraries: Library[]
defaultUserID: string
onClose: () => void
onSaved: () => void | Promise<void>
}) {
const [form, setForm] = useState<PlayProfileInput>(() => ({
user_id: editing?.user_id ?? defaultUserID,
name: editing?.name ?? '',
is_default: editing?.is_default ?? false,
content_rating_limit: editing?.content_rating_limit ?? '',
allow_adult: editing?.allow_adult ?? false,
require_pin: editing?.require_pin ?? false,
pin: '',
preferred_subtitle_lang: editing?.preferred_subtitle_lang ?? '',
preferred_audio_lang: editing?.preferred_audio_lang ?? '',
autoplay_next: editing?.autoplay_next ?? true,
skip_intro: editing?.skip_intro ?? false,
allowed_library_ids: editing?.allowed_library_ids ?? [],
}))
const [saving, setSaving] = useState(false)
const update = (patch: Partial<PlayProfileInput>) => setForm((f) => ({ ...f, ...patch }))
const toggleLib = (id: string) => {
const next = form.allowed_library_ids.includes(id)
? form.allowed_library_ids.filter((x) => x !== id)
: [...form.allowed_library_ids, id]
update({ allowed_library_ids: next })
}
const onSubmit = async (e: FormEvent) => {
e.preventDefault()
setSaving(true)
try {
if (editing) {
await playProfilesAPI.update(editing.id, form)
} else {
await playProfilesAPI.create(form)
}
toast.success('已保存')
await onSaved()
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error ?? '保存失败'
toast.error(msg)
} finally {
setSaving(false)
}
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm">
<div className="glass-panel w-full max-w-lg max-h-[90vh] overflow-y-auto">
<h2 className="mb-4 font-display text-xl font-semibold text-ink-600">
{editing ? '编辑 Profile' : '创建 Profile'}
</h2>
<form onSubmit={onSubmit} className="space-y-4">
<Field label="名称">
<input
required
className="input-base"
maxLength={50}
placeholder="如:儿童模式、影院模式"
value={form.name}
onChange={(e) => update({ name: e.target.value })}
/>
</Field>
<Toggle
label="设为默认 Profile"
hint="登录后默认使用"
checked={form.is_default}
onChange={(v) => update({ is_default: v })}
/>
<Field label="内容分级限制">
<select
className="input-base"
value={form.content_rating_limit ?? ''}
onChange={(e) => update({ content_rating_limit: e.target.value })}
>
<option value="">不限制</option>
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NC-17">NC-17</option>
</select>
</Field>
<Toggle
label="允许成人内容"
hint="开启后可访问 NSFW 媒体"
checked={form.allow_adult}
onChange={(v) => update({ allow_adult: v })}
/>
<Toggle
label="切换时需要 PIN"
hint="切换到此 Profile 需输入 PIN 码"
checked={form.require_pin}
onChange={(v) => update({ require_pin: v })}
/>
{form.require_pin && (
<Field label="PIN 码 (4-8 位)">
<input
type="password"
className="input-base"
maxLength={8}
placeholder={editing ? '留空保持不变' : '设置 PIN'}
value={form.pin ?? ''}
onChange={(e) => update({ pin: e.target.value })}
/>
</Field>
)}
<div className="grid grid-cols-2 gap-3">
<Field label="首选字幕">
<select
className="input-base"
value={form.preferred_subtitle_lang ?? ''}
onChange={(e) => update({ preferred_subtitle_lang: e.target.value })}
>
<option value="">跟随系统</option>
<option value="zh">中文</option>
<option value="zh-CN">简体中文</option>
<option value="en">English</option>
<option value="ja">日语</option>
</select>
</Field>
<Field label="首选音轨">
<select
className="input-base"
value={form.preferred_audio_lang ?? ''}
onChange={(e) => update({ preferred_audio_lang: e.target.value })}
>
<option value="">跟随系统</option>
<option value="zh">中文</option>
<option value="ja">日语</option>
<option value="en">English</option>
</select>
</Field>
</div>
<Toggle
label="自动播放下一集"
checked={form.autoplay_next}
onChange={(v) => update({ autoplay_next: v })}
/>
<Toggle
label="自动跳过片头"
checked={form.skip_intro}
onChange={(v) => update({ skip_intro: v })}
/>
<Field label="允许访问的媒体库 (空 = 全部)">
<div className="flex flex-wrap gap-2">
{libraries.map((l) => (
<button
key={l.id}
type="button"
onClick={() => toggleLib(l.id)}
className={
'rounded-full border px-3 py-1 text-xs ' +
(form.allowed_library_ids.includes(l.id)
? 'border-primary-400/60 bg-primary-400/10 text-brand-500'
: 'border-gray-200 text-ink-50 hover:text-white')
}
>
{l.name}
</button>
))}
{libraries.length === 0 && (
<span className="text-xs text-sand-500">暂无媒体库</span>
)}
</div>
</Field>
<div className="flex justify-end gap-2 pt-2">
<button
type="button"
onClick={onClose}
className="rounded-lg border border-gray-200 px-4 py-2 text-sm text-ink-100 hover:bg-gray-50"
>
取消
</button>
<button type="submit" disabled={saving} className="neon-button">
{saving && <Loader2 size={16} className="animate-spin" />}
保存
</button>
</div>
</form>
</div>
</div>
)
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="block">
<span className="mb-1 block text-sm text-ink-100">{label}</span>
{children}
</label>
)
}
function Toggle({
label,
hint,
checked,
onChange,
}: {
label: string
hint?: string
checked: boolean
onChange: (v: boolean) => void
}) {
return (
<label className="flex cursor-pointer items-center justify-between gap-3 rounded-xl border border-gray-200 bg-gray-50 px-3 py-2">
<div>
<div className="text-sm text-ink-600">{label}</div>
{hint && <div className="text-xs text-ink-50">{hint}</div>}
</div>
<input
type="checkbox"
checked={checked}
onChange={(e) => onChange(e.target.checked)}
className="h-4 w-4 accent-primary-400"
/>
</label>
)
}