Files
Magent/frontend/app/profile/page.tsx
T
Assclaw b0f8c89db7
Magent CI/CD / verify (push) Successful in 10m54s
Magent CI/CD / deploy-prod (push) Skipped
Magent CI/CD / deploy-beta (push) Successful in 1m14s
Add Grizzlyflix newsletters with curated editions and weekly delivery
2026-09-09 23:42:52 +12:00

239 lines
14 KiB
TypeScript

'use client'
import PageHeading from '../ui/PageHeading'
import MonthlyRecapPreference from './MonthlyRecapPreference'
import NewsletterPreference from './NewsletterPreference'
import { useCallback, useEffect, useState, type FormEvent, type KeyboardEvent } from 'react'
import { useRouter } from 'next/navigation'
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'
type ProfileInfo = {
username: string
email?: string | null
role: string
auth_provider: string
password_change_supported?: boolean
password_provider?: 'local' | 'jellyfin' | null
}
type ActivityEntry = {
ip: string
user_agent: string
first_seen_at: string
last_seen_at: string
}
type ProfileResponse = {
user: ProfileInfo
stats?: { total: number; ready: number; in_progress: number }
activity?: { recent: ActivityEntry[] }
}
type Notice = { tone: 'status' | 'error'; message: string } | null
type ProfileTab = 'overview' | 'security' | 'activity'
const TABS: { key: ProfileTab; label: string }[] = [
{ key: 'overview', label: 'Account' },
{ key: 'security', label: 'Security' },
{ key: 'activity', label: 'Activity' },
]
const normalizeTab = (value: string | null): ProfileTab => value === 'security' || value === 'activity' ? value : 'overview'
const formatDate = (value?: string) => {
if (!value) return 'Not recorded'
const date = new Date(value)
return Number.isNaN(date.valueOf()) ? 'Not recorded' : date.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })
}
const deviceName = (agent: string) => {
const value = (agent || '').toLowerCase()
const browser = value.includes('edg/') ? 'Edge' : value.includes('firefox/') || value.includes('fxios/') ? 'Firefox'
: value.includes('chrome/') || value.includes('crios/') ? 'Chrome' : value.includes('safari/') ? 'Safari' : 'Browser'
const device = /iphone|ipad/.test(value) ? 'iOS' : value.includes('android') ? 'Android'
: value.includes('windows') ? 'Windows' : value.includes('macintosh') ? 'Mac' : value.includes('linux') ? 'Linux' : ''
return device ? `${browser} on ${device}` : browser
}
const responseMessage = async (response: Response, fallback: string) => {
const data = await response.json().catch(() => null)
return typeof data?.detail === 'string' && data.detail.trim() ? data.detail : fallback
}
export default function ProfilePage() {
const router = useRouter()
const [data, setData] = useState<ProfileResponse | null>(null)
const [loading, setLoading] = useState(true)
const [loadError, setLoadError] = useState('')
const [activeTab, setActiveTab] = useState<ProfileTab>('overview')
const [email, setEmail] = useState('')
const [emailSaving, setEmailSaving] = useState(false)
const [emailNotice, setEmailNotice] = useState<Notice>(null)
const [currentPassword, setCurrentPassword] = useState('')
const [newPassword, setNewPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [passwordSaving, setPasswordSaving] = useState(false)
const [passwordNotice, setPasswordNotice] = useState<Notice>(null)
const [showAllActivity, setShowAllActivity] = useState(false)
const loadProfile = useCallback(async () => {
if (!getToken()) { router.replace('/login?next=%2Fprofile'); return }
setLoading(true)
setLoadError('')
try {
const response = await authFetch(`${getApiBase()}/auth/profile`)
if (response.status === 401) { clearToken(); router.replace('/login?next=%2Fprofile'); return }
if (!response.ok) throw new Error('Could not load your profile. Please try again.')
const profile = await response.json() as ProfileResponse
setData(profile)
setEmail(profile.user.email ?? '')
} catch {
setLoadError('Could not load your profile. Please try again.')
} finally {
setLoading(false)
}
}, [router])
useEffect(() => { void loadProfile() }, [loadProfile])
useEffect(() => {
const syncTab = () => setActiveTab(normalizeTab(new URLSearchParams(window.location.search).get('tab')))
syncTab()
window.addEventListener('popstate', syncTab)
return () => window.removeEventListener('popstate', syncTab)
}, [])
const selectTab = (tab: ProfileTab) => {
setActiveTab(tab)
router.replace(tab === 'overview' ? '/profile' : `/profile?tab=${tab}`, { scroll: false })
}
const tabKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
let next = index
if (event.key === 'ArrowRight') next = (index + 1) % TABS.length
else if (event.key === 'ArrowLeft') next = (index + TABS.length - 1) % TABS.length
else if (event.key === 'Home') next = 0
else if (event.key === 'End') next = TABS.length - 1
else return
event.preventDefault()
selectTab(TABS[next].key)
document.getElementById(`profile-tab-${TABS[next].key}`)?.focus()
}
const saveEmail = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (emailSaving) return
setEmailSaving(true)
setEmailNotice(null)
try {
const response = await authFetch(`${getApiBase()}/auth/profile/email`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email.trim() || null }),
})
if (response.status === 401) { clearToken(); router.replace('/login?next=%2Fprofile'); return }
if (!response.ok) throw new Error(await responseMessage(response, 'Could not save your email. Please try again.'))
const result = await response.json()
const saved = typeof result.email === 'string' ? result.email : ''
setData((current) => current ? { ...current, user: { ...current.user, email: saved || null } } : current)
setEmail(saved)
setEmailNotice({ tone: 'status', message: saved ? 'Email saved.' : 'Email removed.' })
} catch (error) {
setEmailNotice({ tone: 'error', message: error instanceof Error ? error.message : 'Could not save your email.' })
} finally { setEmailSaving(false) }
}
const savePassword = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
if (passwordSaving) return
setPasswordNotice(null)
if (newPassword.trim().length < 8) {
setPasswordNotice({ tone: 'error', message: 'Use at least 8 characters for your new password.' })
return
}
if (newPassword !== confirmPassword) {
setPasswordNotice({ tone: 'error', message: 'The new passwords do not match.' })
return
}
setPasswordSaving(true)
try {
const response = await authFetch(`${getApiBase()}/auth/password`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
})
if (!response.ok) throw new Error(await responseMessage(response, 'Could not change your password. Please try again.'))
const result = await response.json()
setCurrentPassword(''); setNewPassword(''); setConfirmPassword('')
setPasswordNotice({ tone: 'status', message: result.provider === 'jellyfin'
? 'Password updated for Grizzlyflix and Magent. Seerr uses the same password.'
: 'Password updated.' })
} catch (error) {
setPasswordNotice({ tone: 'error', message: error instanceof Error ? error.message : 'Could not change your password.' })
} finally { setPasswordSaving(false) }
}
const user = data?.user
const passwordProvider = user?.password_provider ?? (user?.auth_provider === 'jellyfin' ? 'jellyfin' : 'local')
const canChangePassword = user?.password_change_supported ?? ['local', 'jellyfin'].includes(user?.auth_provider ?? '')
const emailChanged = email.trim() !== (user?.email ?? '')
const recent = data?.activity?.recent ?? []
const notice = (value: Notice) => value && <p className={`account-notice is-${value.tone}`} role={value.tone === 'error' ? 'alert' : 'status'}>{value.message}</p>
return (
<main className="account-page">
<PageHeading title="My profile" description="Your contact details, security, and activity." actions={
user && <div className="account-identity"><span className="account-avatar" aria-hidden="true">{user.username.slice(0, 1).toUpperCase()}</span><div><strong>{user.username}</strong><span>{user.role === 'admin' ? 'Administrator' : 'Member'}</span></div></div>
} />
{loading ? <p className="account-empty" role="status">Loading your profile</p> : loadError ? (
<div className="account-empty"><p role="alert">{loadError}</p><button type="button" className="account-secondary" onClick={() => void loadProfile()}>Try again</button></div>
) : user && <>
<div className="account-tabs" role="tablist" aria-label="Profile sections">
{TABS.map((tab, index) => <button key={tab.key} id={`profile-tab-${tab.key}`} type="button" role="tab"
aria-selected={activeTab === tab.key} aria-controls={`profile-panel-${tab.key}`} tabIndex={activeTab === tab.key ? 0 : -1}
onKeyDown={(event) => tabKeyDown(event, index)} onClick={() => selectTab(tab.key)}>{tab.label}</button>)}
</div>
<section className="account-panel" id="profile-panel-overview" role="tabpanel" aria-labelledby="profile-tab-overview" hidden={activeTab !== 'overview'}>
<div className="account-section-intro"><h2>Contact email</h2><p>For password recovery and updates on your reported issues.</p></div>
<form className="account-form" onSubmit={saveEmail}>
<label htmlFor="profile-email">Email address</label>
<input id="profile-email" name="email" type="email" autoComplete="email" placeholder="you@example.com" value={email} disabled={emailSaving}
onChange={(event) => { setEmail(event.target.value); setEmailNotice(null) }} />
{!user.email && <p className="account-hint">Add an email so we can let you know when a fix is ready.</p>}
{user.email && !email.trim() && <p className="account-hint">Saving without an email stops account and issue emails.</p>}
{notice(emailNotice)}
<div className="account-form-actions">
<button type="submit" className="account-primary" disabled={emailSaving || !emailChanged}>{emailSaving ? 'Saving…' : 'Save email'}</button>
{emailChanged && <button type="button" className="account-secondary" disabled={emailSaving} onClick={() => { setEmail(user.email ?? ''); setEmailNotice(null) }}>Discard</button>}
</div>
</form>
<div className="account-connected"><span className="account-connection-dot" aria-hidden="true" /><span>{user.auth_provider === 'jellyfin' ? 'Connected with your Grizzlyflix account' : user.auth_provider === 'local' ? 'Signed in with a Magent account' : 'Signed in with your media account'}</span></div>
<MonthlyRecapPreference key={user.email || 'no-email'} />
<NewsletterPreference key={`newsletter-${user.email || 'no-email'}`} />
</section>
<section className="account-panel" id="profile-panel-security" role="tabpanel" aria-labelledby="profile-tab-security" hidden={activeTab !== 'security'}>
<div className="account-section-intro"><h2>Change password</h2><p>{passwordProvider === 'jellyfin' ? 'One password for Grizzlyflix, Seerr and Magent.' : 'Keep your Magent account secure.'}</p></div>
{canChangePassword ? <form className="account-form" onSubmit={savePassword}>
<fieldset disabled={passwordSaving}>
<label htmlFor="profile-current-password">Current password</label>
<input id="profile-current-password" type="password" autoComplete="current-password" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} required />
<label htmlFor="profile-new-password">New password</label>
<input id="profile-new-password" type="password" autoComplete="new-password" aria-describedby="password-length" value={newPassword} onChange={(event) => setNewPassword(event.target.value)} minLength={8} required />
<p id="password-length" className="account-hint">At least 8 characters.</p>
<label htmlFor="profile-confirm-password">Confirm new password</label>
<input id="profile-confirm-password" type="password" autoComplete="new-password" value={confirmPassword} onChange={(event) => setConfirmPassword(event.target.value)} minLength={8} required />
</fieldset>
{notice(passwordNotice)}
<div className="account-form-actions"><button type="submit" className="account-primary" disabled={passwordSaving}>{passwordSaving ? 'Updating…' : 'Update password'}</button></div>
</form> : <p className="account-empty">Password changes are managed by your sign-in provider. Contact an administrator for help.</p>}
</section>
<section className="account-panel" id="profile-panel-activity" role="tabpanel" aria-labelledby="profile-tab-activity" hidden={activeTab !== 'activity'}>
<div className="account-section-intro"><h2>Your activity</h2><p>Your requests and recent account access.</p></div>
{data?.stats && <div className="account-request-summary"><div><strong>{data.stats.total}</strong><span>Requests</span></div><div><strong>{data.stats.ready}</strong><span>Ready to watch</span></div><a href="/">View my requests <span aria-hidden="true"></span></a></div>}
<h3 className="account-list-heading">Recent account access</h3>
{recent.length ? <ul className="account-access-list">
{(showAllActivity ? recent : recent.slice(0, 5)).map((entry, index) => <li key={`${entry.ip}-${entry.last_seen_at}-${index}`}>
<div className="account-access-summary"><strong>{deviceName(entry.user_agent)}</strong><time dateTime={entry.last_seen_at}>{formatDate(entry.last_seen_at)}</time></div>
<details><summary>Connection details</summary><dl><div><dt>IP address</dt><dd>{entry.ip || 'Not recorded'}</dd></div><div><dt>First seen</dt><dd>{formatDate(entry.first_seen_at)}</dd></div></dl></details>
</li>)}
</ul> : <p className="account-empty">No recent activity yet.</p>}
{recent.length > 5 && <button className="account-secondary" type="button" onClick={() => setShowAllActivity(!showAllActivity)}>{showAllActivity ? 'Show less' : 'Show all activity'}</button>}
</section>
</>}
</main>
)
}