feat(spa): S6b — Plex/Jellyfin/Emby Remote media-source screens (#202)

Build the Remote media-source SPA screens over the S5 foundation, replacing
the MediaSourceEditorPlaceholder for the plex/jellyfin/emby dispatch branches
only (Local branches left for S6a):

- PlexSourceScreen: pin-flow sign-in / fix-credentials / sign-out with the
  §C1 poll state machine — polls GET /api/media-sources/plex every 2s up to
  150s and keeps polling while authorized-but-locked ("finalizing"); the
  terminal success is the lock releasing. Popup-blocked fallback link. Server
  table (Refresh disabled while locked / Edit Libraries / Edit Path
  Replacements) + sign-out content-removal confirm dialog.
- RemoteSourceScreen (shared Jellyfin/Emby): connect / edit-connection /
  disconnect (warning dialog) + server table.
- RemoteConnectionEditScreen (shared): secure key affordance (§C3/finding 1)
  — address prefilled, "leave blank to keep" when hasApiKey, required on first
  connect; stored key never rendered or requested.
- RemoteLibrariesEditScreen (shared): client-side sortable Name + MediaKind
  columns, per-library sync Switch, one Save; draft keyed by (name,mediaKind)
  not id, refetch after save (ids change on disable, §C4a).
- PathReplacementsEditScreen (shared): row list + selected-row edit form,
  add/remove, one Save; both fields required; family remote-path column label.

All editors use the ChannelEditScreen draft/save model + a shared useDirtyGuard
(registerNavigationGuard + beforeunload), Save gated !valid||!dirty||saving,
draft retained on 422/network, destructive actions gated on saving, 409 →
refetch. Colocated tests cover the poll (waiting→finalizing→success asserting
it does NOT stop at authorized&locked, timeout, budget-exhausted), the secure
key affordance, sortable columns, draft-retained-on-422, dirty-guard veto, and
the disconnect/sign-out dialogs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-11 16:33:41 +02:00
co-authored by Claude Opus 4.8
parent 6ce448d265
commit edbecc01d7
12 changed files with 1740 additions and 2 deletions
+12 -2
View File
@@ -64,6 +64,11 @@ import { PlaylistsScreen } from './screens/PlaylistsScreen';
import { RerunCollectionsScreen } from './screens/RerunCollectionsScreen';
import { ChannelsScreen } from './screens/ChannelsScreen';
import { LibrariesScreen } from './screens/LibrariesScreen';
import { PlexSourceScreen } from './screens/PlexSourceScreen';
import { RemoteSourceScreen } from './screens/RemoteSourceScreen';
import { RemoteConnectionEditScreen } from './screens/RemoteConnectionEditScreen';
import { RemoteLibrariesEditScreen } from './screens/RemoteLibrariesEditScreen';
import { PathReplacementsEditScreen } from './screens/PathReplacementsEditScreen';
import { SchedulesScreen } from './screens/SchedulesScreen';
import { canLeaveCurrentScreen } from './navigationGuard';
import {
@@ -2579,12 +2584,17 @@ function LibrariesRouteScreen({ subPath }: { subPath: string }) {
case 'local-new':
case 'local-edit':
return <MediaSourceEditorPlaceholder key={subPath} route={sub} />;
// --- Remote (slice S6b replaces these with the Plex/Remote source + editor screens) ---
// --- Remote (slice S6b) — Plex uses the pin flow, Jellyfin/Emby share the remote screens ---
case 'remote-source':
return sub.family === 'plex'
? <PlexSourceScreen key={subPath} />
: <RemoteSourceScreen key={subPath} family={sub.family} />;
case 'remote-connection':
return <RemoteConnectionEditScreen key={subPath} family={sub.family} />;
case 'remote-libraries':
return <RemoteLibrariesEditScreen key={subPath} family={sub.family} sourceId={sub.id} />;
case 'remote-path-replacements':
return <MediaSourceEditorPlaceholder key={subPath} route={sub} />;
return <PathReplacementsEditScreen key={subPath} family={sub.family} sourceId={sub.id} />;
}
}
+35
View File
@@ -0,0 +1,35 @@
// Shared dirty-guard wiring for the media-source editor screens (design §D.2). Mirrors the
// SchedulesScreen convention (registerNavigationGuard on the current dirty state + a `beforeunload`
// listener while dirty) so an editor with unsaved changes vetoes both in-app navigation (App's
// popstate owner consults canLeaveCurrentScreen) and full-page unloads (reload / close tab).
//
// The guard predicate reads the LATEST dirty value via a ref updated on every render, so App's
// synchronous popstate handler sees the current state without the effect having to re-register on
// each keystroke. A single hook keeps the three editors (connection / libraries / path-replacements)
// consistent instead of copy-pasting the guard block into each.
import { useEffect, useRef } from 'react';
import { registerNavigationGuard } from '../navigationGuard';
export function useDirtyGuard(dirty: boolean, prompt: string): void {
const dirtyRef = useRef(dirty);
// Keep the ref current for the synchronous guard predicate. Updated in an effect (committed before
// any user pop/nav gesture can fire) rather than during render.
useEffect(() => {
dirtyRef.current = dirty;
}, [dirty]);
useEffect(() => registerNavigationGuard(() => !dirtyRef.current || window.confirm(prompt)), [prompt]);
useEffect(() => {
if (!dirty) {
return undefined;
}
const handler = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [dirty]);
}
@@ -0,0 +1,144 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PathReplacementsEditScreen } from './PathReplacementsEditScreen';
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
interface Row {
id: number;
remotePath: string;
localPath: string;
}
interface Options {
rows: Row[];
saveStatus?: number;
saveBody?: Row[];
}
function installFetch(family: string, id: number, options: Options) {
const putBodies: string[] = [];
const spy = vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const method = (init?.method ?? 'GET').toUpperCase();
const base = `/api/media-sources/${family}/${id}/path-replacements`;
if (url.endsWith(base) && method === 'GET') {
return Promise.resolve(json(options.rows));
}
if (url.endsWith(base) && method === 'PUT') {
putBodies.push(String(init?.body ?? ''));
const status = options.saveStatus ?? 200;
if (status >= 400) {
return Promise.resolve(json({ title: 'Save failed', detail: 'Bad path' }, status));
}
return Promise.resolve(json(options.saveBody ?? options.rows));
}
return Promise.resolve(json({}, 404));
});
return { spy, putBodies };
}
describe('PathReplacementsEditScreen', () => {
beforeEach(() => {
vi.restoreAllMocks();
window.history.replaceState(null, '', '/app/libraries/jellyfin/4/path-replacements');
});
afterEach(() => {
cleanup();
});
it('uses the family-specific remote-path column label', async () => {
installFetch('jellyfin', 4, { rows: [{ id: 1, remotePath: '/media', localPath: '/mnt/media' }] });
render(<PathReplacementsEditScreen family="jellyfin" sourceId={4} />);
expect(await screen.findByText('Jellyfin Path')).toBeTruthy();
expect(screen.getByText('Local Path')).toBeTruthy();
});
it('adds a row and requires both fields before Save enables', async () => {
installFetch('jellyfin', 4, { rows: [] });
render(<PathReplacementsEditScreen family="jellyfin" sourceId={4} />);
await screen.findByRole('button', { name: /Add/i });
fireEvent.click(screen.getByRole('button', { name: /Add/i }));
const save = () => screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement;
// New blank row: invalid, Save disabled.
expect(save().disabled).toBe(true);
const [remote, local] = screen.getAllByRole('textbox') as HTMLInputElement[];
fireEvent.change(remote, { target: { value: '/media' } });
// Only one field filled → still invalid.
expect(save().disabled).toBe(true);
fireEvent.change(local, { target: { value: '/mnt/media' } });
expect(save().disabled).toBe(false);
});
it('saves the rows and resets the baseline from the reloaded response', async () => {
const { putBodies } = installFetch('jellyfin', 4, {
rows: [{ id: 1, remotePath: '/media', localPath: '/mnt/media' }],
saveBody: [{ id: 1, remotePath: '/movies', localPath: '/mnt/media' }]
});
render(<PathReplacementsEditScreen family="jellyfin" sourceId={4} />);
await screen.findByText('Jellyfin Path');
const [remote] = screen.getAllByRole('textbox') as HTMLInputElement[];
fireEvent.change(remote, { target: { value: '/movies' } });
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await vi.waitFor(() => expect(putBodies.length).toBe(1));
const body = JSON.parse(putBodies[0]);
expect(body.items).toEqual([{ id: 1, remotePath: '/movies', localPath: '/mnt/media' }]);
// After the refetch the baseline is clean.
await vi.waitFor(() => expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true));
});
it('retains the draft on a 422 save failure', async () => {
const { putBodies } = installFetch('jellyfin', 4, {
rows: [{ id: 1, remotePath: '/media', localPath: '/mnt/media' }],
saveStatus: 422
});
render(<PathReplacementsEditScreen family="jellyfin" sourceId={4} />);
await screen.findByText('Jellyfin Path');
const [remote] = screen.getAllByRole('textbox') as HTMLInputElement[];
fireEvent.change(remote, { target: { value: '/movies' } });
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await vi.waitFor(() => expect(putBodies.length).toBe(1));
expect(await screen.findByText(/Bad path/i)).toBeTruthy();
// Draft retained.
expect((screen.getAllByRole('textbox')[0] as HTMLInputElement).value).toBe('/movies');
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
});
it('removes a row', async () => {
installFetch('jellyfin', 4, {
rows: [
{ id: 1, remotePath: '/media', localPath: '/mnt/media' },
{ id: 2, remotePath: '/music', localPath: '/mnt/music' }
]
});
render(<PathReplacementsEditScreen family="jellyfin" sourceId={4} />);
await screen.findByText('/media');
expect(screen.getByText('/music')).toBeTruthy();
// Two Remove buttons; remove the second row.
const removes = screen.getAllByRole('button', { name: /Remove/i });
fireEvent.click(removes[1]);
expect(screen.queryByText('/music')).toBeNull();
// Removal makes the draft dirty → Save enabled.
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
});
});
@@ -0,0 +1,274 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, Check, Plus, Trash2, TriangleAlert } from 'lucide-react';
import { Button, Card, Input, Spinner } from '../components';
import {
ApiError,
getPathReplacements,
messageFromMediaSourcesError,
replacePathReplacements,
type PathReplacement,
type RemoteFamily
} from '../api';
import { navigateToPath } from '../routing';
import { familyMeta, familyRoute } from '../mediaSources/familyMeta';
import { useDirtyGuard } from '../mediaSources/useDirtyGuard';
const DIRTY_PROMPT = 'You have unsaved path replacement changes. Discard them?';
interface DraftRow {
_key: string;
id: number;
remotePath: string;
localPath: string;
}
let keySeq = 0;
function nextKey(): string {
keySeq += 1;
return `row-${keySeq}`;
}
function fromResponse(rows: PathReplacement[]): DraftRow[] {
return rows.map((row) => ({ _key: nextKey(), id: row.id, remotePath: row.remotePath ?? '', localPath: row.localPath ?? '' }));
}
// Compare by (remotePath, localPath) — ids are assigned by the server on save, so the dirty flag and
// baseline reset must ignore them (design §C4b round-trip identity).
function toComparable(rows: DraftRow[]): string {
return JSON.stringify(rows.map((row) => ({ remotePath: row.remotePath, localPath: row.localPath })));
}
// Shared path-replacements editor for Plex / Jellyfin / Emby
// (RemoteMediaSourcePathReplacementsEditor). A row list + a selected-row edit form; the remote-path
// column label comes from familyMeta ("Plex Path" / "Jellyfin Path" / "Emby Path"). Both fields are
// required per row. Saved as one PUT; the response (reloaded list) becomes the new baseline.
export function PathReplacementsEditScreen({ family, sourceId }: { family: RemoteFamily; sourceId: number }) {
const meta = familyMeta(family);
const [loaded, setLoaded] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [notFound, setNotFound] = useState(false);
const [draft, setDraft] = useState<DraftRow[]>([]);
const [saved, setSaved] = useState<DraftRow[]>([]);
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
const ingest = useCallback((rows: PathReplacement[]) => {
const drafted = fromResponse(rows);
setDraft(drafted);
setSaved(drafted.map((row) => ({ ...row })));
setSelectedKey(drafted[0]?._key ?? null);
setLoaded(true);
}, []);
const load = useCallback(() => {
getPathReplacements(family, sourceId)
.then((rows) => {
if (activeRef.current) {
ingest(rows);
}
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
if (error instanceof ApiError && error.status === 404) {
setNotFound(true);
} else {
setLoadError(messageFromMediaSourcesError(error, `Unable to load ${meta.label} path replacements`));
}
});
}, [family, sourceId, meta.label, ingest]);
useEffect(() => {
load();
}, [load]);
const dirty = toComparable(draft) !== toComparable(saved);
useDirtyGuard(dirty, DIRTY_PROMPT);
if (notFound) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>That {meta.label} server no longer exists.</span>
<Button onClick={() => navigateToPath(familyRoute(family))} size="sm" variant="secondary">Back to {meta.label}</Button>
</div>
);
}
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>{loadError}</span>
<Button onClick={() => navigateToPath(familyRoute(family))} size="sm" variant="secondary">Back to {meta.label}</Button>
</div>
);
}
if (!loaded) {
return (
<div className="ctv-settings-loading">
<Spinner size={16} tone="muted" />
<span>Loading {meta.label} path replacements…</span>
</div>
);
}
const selected = draft.find((row) => row._key === selectedKey) ?? null;
// Every row must have a non-blank remote and local path (Blazor required both).
const valid = draft.every((row) => row.remotePath.trim().length > 0 && row.localPath.trim().length > 0);
const updateSelected = (patch: Partial<Pick<DraftRow, 'remotePath' | 'localPath'>>) => {
if (!selected || saving) {
return;
}
setDraft((current) => current.map((row) => (row._key === selected._key ? { ...row, ...patch } : row)));
};
const addRow = () => {
if (saving) {
return;
}
const row: DraftRow = { _key: nextKey(), id: 0, remotePath: '', localPath: '' };
setDraft((current) => [...current, row]);
setSelectedKey(row._key);
};
const removeRow = (key: string) => {
if (saving) {
return;
}
setDraft((current) => {
const index = current.findIndex((row) => row._key === key);
const next = current.filter((row) => row._key !== key);
setSelectedKey(next[Math.min(index, next.length - 1)]?._key ?? null);
return next;
});
};
const discard = () => {
if (!dirty || window.confirm(DIRTY_PROMPT)) {
const restored = saved.map((row) => ({ ...row }));
setDraft(restored);
setSelectedKey(restored[0]?._key ?? null);
setSaveError(null);
}
};
const save = () => {
if (!valid || !dirty || saving) {
return;
}
setSaving(true);
setSaveError(null);
replacePathReplacements(family, sourceId, {
items: draft.map((row) => ({ id: row.id, remotePath: row.remotePath.trim(), localPath: row.localPath.trim() }))
})
.then((rows) => {
if (!activeRef.current) {
return;
}
ingest(rows);
setSaving(false);
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setSaving(false);
setSaveError(messageFromMediaSourcesError(error, `Unable to save ${meta.label} path replacements`));
if (error instanceof ApiError && error.status === 409) {
load();
}
});
};
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">{meta.label} path replacements</span>
<h2>Edit path replacements</h2>
<p>Map {meta.label} media paths onto the paths ErsatzTV can reach.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button onClick={() => navigateToPath(familyRoute(family))} startIcon={<ArrowLeft aria-hidden="true" size={14} />} variant="ghost">Back to {meta.label}</Button>
</div>
</section>
{saveError && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{saveError}</span>
</div>
)}
<div className="ctv-schedule-grid">
<section className="ctv-schedule-lineup-panel" aria-label="Path replacements">
<div className="ctv-schedule-panel-head">
<span>Replacements</span>
<Button disabled={saving} onClick={addRow} size="sm" startIcon={<Plus aria-hidden="true" size={14} />} variant="ghost">Add</Button>
</div>
{draft.length === 0 ? (
<div className="ctv-schedule-empty">No path replacements</div>
) : (
<div className="ctv-library-list" role="list" aria-label="Path replacement rows">
{draft.map((row) => (
<div className={`ctv-library-row${row._key === selectedKey ? ' ctv-library-row-active' : ''}`} role="listitem" key={row._key}>
<button className="ctv-library-row-main" onClick={() => setSelectedKey(row._key)} type="button" style={{ textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer' }}>
<strong>{row.remotePath || '(new)'}</strong>
<span>→ {row.localPath || '(unset)'}</span>
</button>
<div className="ctv-library-row-status">
<Button disabled={saving} onClick={() => removeRow(row._key)} size="sm" startIcon={<Trash2 aria-hidden="true" size={14} />} variant="ghost">Remove</Button>
</div>
</div>
))}
</div>
)}
</section>
<section className="ctv-schedule-inspector" aria-label="Path replacement editor">
{selected ? (
<Card title={<h3>Edit replacement</h3>}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<Input
label={meta.remotePathColumnLabel}
value={selected.remotePath}
disabled={saving}
onChange={(event) => updateSelected({ remotePath: event.target.value })}
error={selected.remotePath.trim() ? null : `${meta.remotePathColumnLabel} is required`}
/>
<Input
label="Local Path"
value={selected.localPath}
disabled={saving}
onChange={(event) => updateSelected({ localPath: event.target.value })}
error={selected.localPath.trim() ? null : 'Local Path is required'}
/>
</div>
</Card>
) : (
<div className="ctv-schedule-empty">Select or add a path replacement</div>
)}
</section>
</div>
<div className="ctv-schedule-toolbar">
<div className="ctv-schedule-toolbar-spacer" />
<Button disabled={!dirty || saving} onClick={discard} variant="ghost">Discard</Button>
<Button disabled={!valid || !dirty || saving} loading={saving} onClick={save} startIcon={<Check aria-hidden="true" size={14} />}>Save</Button>
</div>
</div>
);
}
+173
View File
@@ -0,0 +1,173 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PlexSourceScreen } from './PlexSourceScreen';
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
interface PlexState {
isAuthorized: boolean;
isLocked: boolean;
servers: Array<{ id: number; name: string; address: string }>;
}
// A URL-keyed fetch stub. `stateRef.current` lets a test flip the polled Plex state over time; the
// counter proves the poll kept running (a stop would freeze the count).
function installFetch(stateRef: { current: PlexState }, counter: { state: number }) {
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const method = (init?.method ?? 'GET').toUpperCase();
if (url.endsWith('/api/media-sources/plex/pin-flow') && method === 'POST') {
return Promise.resolve(json({ authUrl: 'https://plex.tv/link?code=ABCD' }));
}
if (url.endsWith('/api/media-sources/plex/sign-out') && method === 'POST') {
return Promise.resolve(new Response(null, { status: 204 }));
}
if (url.includes('/refresh-libraries') && method === 'POST') {
return Promise.resolve(new Response(null, { status: 204 }));
}
if (url.endsWith('/api/media-sources/plex') && method === 'GET') {
counter.state += 1;
return Promise.resolve(json(stateRef.current));
}
return Promise.resolve(json({}, 404));
});
}
describe('PlexSourceScreen', () => {
beforeEach(() => {
vi.restoreAllMocks();
});
afterEach(() => {
cleanup();
vi.useRealTimers();
});
it('pin flow: waiting → finalizing → success, and keeps polling at authorized&locked (does NOT stop)', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue({} as Window);
vi.useFakeTimers();
render(<PlexSourceScreen />);
await vi.waitFor(() => expect(screen.getByRole('button', { name: 'Sign in to Plex' })).toBeTruthy());
// Polls now read "locked, not authorized" = waiting.
stateRef.current = { isAuthorized: false, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
await vi.waitFor(() => expect(screen.getByText(/Waiting for you to authorize/i)).toBeTruthy());
await vi.advanceTimersByTimeAsync(2000);
expect(screen.getByText(/Waiting for you to authorize/i)).toBeTruthy();
// Authorized but STILL LOCKED = finalizing. The terminal signal is the lock releasing, so the
// screen must keep polling here (design §C1 / finding 5): no servers shown, count keeps rising.
stateRef.current = { isAuthorized: true, isLocked: true, servers: [] };
await vi.advanceTimersByTimeAsync(2000);
expect(screen.getByText(/discovering your Plex servers/i)).toBeTruthy();
expect(screen.queryByRole('heading', { name: 'Servers' })).toBeNull();
const callsAtFinalizing = counter.state;
await vi.advanceTimersByTimeAsync(2000);
// Still finalizing after another interval — proves it did NOT stop at authorized&locked.
expect(counter.state).toBeGreaterThan(callsAtFinalizing);
expect(screen.getByText(/discovering your Plex servers/i)).toBeTruthy();
// Lock releases while authorized = terminal success; servers appear and polling stops.
stateRef.current = { isAuthorized: true, isLocked: false, servers: [{ id: 5, name: 'Home Server', address: 'http://plex:32400' }] };
await vi.advanceTimersByTimeAsync(2000);
await vi.waitFor(() => expect(screen.getByRole('heading', { name: 'Servers' })).toBeTruthy());
expect(screen.getByText('Home Server')).toBeTruthy();
const callsAfterSuccess = counter.state;
await vi.advanceTimersByTimeAsync(6000);
expect(counter.state).toBe(callsAfterSuccess); // polling stopped on success
});
it('pin flow: an ended flow without auth reports a timeout and stops polling', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue({} as Window);
vi.useFakeTimers();
render(<PlexSourceScreen />);
await vi.waitFor(() => expect(screen.getByRole('button', { name: 'Sign in to Plex' })).toBeTruthy());
stateRef.current = { isAuthorized: false, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
await vi.waitFor(() => expect(screen.getByText(/Waiting for you to authorize/i)).toBeTruthy());
// Flow ends without authorization (tab closed / plex.tv timed out).
stateRef.current = { isAuthorized: false, isLocked: false, servers: [] };
await vi.advanceTimersByTimeAsync(2000);
await vi.waitFor(() => expect(screen.getByText(/Plex sign-in timed out/i)).toBeTruthy());
const callsAfterTimeout = counter.state;
await vi.advanceTimersByTimeAsync(6000);
expect(counter.state).toBe(callsAfterTimeout); // stopped
});
it('pin flow: budget exhausted while still locked shows "still working" and stops', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue({} as Window);
vi.useFakeTimers();
render(<PlexSourceScreen />);
await vi.waitFor(() => expect(screen.getByRole('button', { name: 'Sign in to Plex' })).toBeTruthy());
// Stay authorized-but-locked forever (a very large first sync legitimately holds the lock).
stateRef.current = { isAuthorized: true, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
await vi.waitFor(() => expect(screen.getByText(/discovering your Plex servers|Waiting/i)).toBeTruthy());
// Consume the whole 150s budget.
await vi.advanceTimersByTimeAsync(152_000);
await vi.waitFor(() => expect(screen.getByText(/Still working/i)).toBeTruthy());
const callsAtBudget = counter.state;
await vi.advanceTimersByTimeAsync(6000);
expect(counter.state).toBe(callsAtBudget); // stopped, not a failure loop
});
it('renders a clickable fallback link when the popup is blocked', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as PlexState };
const counter = { state: 0 };
installFetch(stateRef, counter);
vi.spyOn(window, 'open').mockReturnValue(null);
render(<PlexSourceScreen />);
await screen.findByRole('button', { name: 'Sign in to Plex' });
stateRef.current = { isAuthorized: false, isLocked: true, servers: [] };
fireEvent.click(screen.getByRole('button', { name: 'Sign in to Plex' }));
const link = await screen.findByRole('link', { name: /Open the Plex sign-in page/i });
expect(link).toHaveAttribute('href', 'https://plex.tv/link?code=ABCD');
});
it('sign out shows the content-removal warning dialog and posts on confirm', async () => {
const stateRef = {
current: { isAuthorized: true, isLocked: false, servers: [{ id: 9, name: 'Living Room', address: 'http://plex:32400' }] } as PlexState
};
const counter = { state: 0 };
const fetchSpy = installFetch(stateRef, counter);
render(<PlexSourceScreen />);
await screen.findByRole('heading', { name: 'Servers' });
fireEvent.click(screen.getByRole('button', { name: 'Sign out of Plex' }));
expect(await screen.findByText(/removes all synced Plex servers/i)).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Sign out' }));
await vi.waitFor(() =>
expect(fetchSpy.mock.calls.some(([input, init]) => String(input).endsWith('/sign-out') && (init?.method ?? '').toUpperCase() === 'POST')).toBe(true)
);
});
});
+315
View File
@@ -0,0 +1,315 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { KeyRound, LogIn, LogOut, RefreshCw, Server, TriangleAlert } from 'lucide-react';
import { Badge, Button, Card, ConfirmDialog, IconButton, Spinner, StatusDot } from '../components';
import {
getPlexState,
messageFromMediaSourcesError,
refreshRemoteLibraries,
signOutOfPlex,
startPlexPinFlow,
type RemoteMediaSourceState
} from '../api';
import { navigateToPath } from '../routing';
import { pathReplacementsRoute, remoteLibrariesRoute } from '../mediaSources/familyMeta';
import {
evaluatePinFlow,
initialPinFlowState,
isPinFlowBudgetExhausted,
PIN_FLOW_POLL_INTERVAL_MS,
type PinFlowState
} from '../mediaSources/pinFlowPoll';
type BootState =
| { status: 'loading' }
| { status: 'error'; error: string }
| { status: 'ready'; state: RemoteMediaSourceState };
// The Plex source screen: mirrors PlexMediaSources.razor. It drives the OAuth pin flow (design §C1)
// — the poll runs against GET /api/media-sources/plex every 2s and, crucially, keeps polling while
// authorized-but-still-locked ("finalizing / discovering servers"); the terminal success signal is
// the lock RELEASING (see pinFlowPoll.ts). Server rows offer Refresh / Edit Libraries / Edit Path
// Replacements. Refresh is disabled while the Plex lock is held.
export function PlexSourceScreen() {
const [boot, setBoot] = useState<BootState>({ status: 'loading' });
const [actionError, setActionError] = useState<string | null>(null);
const [confirmSignOut, setConfirmSignOut] = useState(false);
const [signingOut, setSigningOut] = useState(false);
const [refreshingId, setRefreshingId] = useState<number | null>(null);
// Pin-flow UI state.
const [pinState, setPinState] = useState<PinFlowState | null>(null);
const [polling, setPolling] = useState(false);
const [authUrl, setAuthUrl] = useState<string | null>(null);
const [popupBlocked, setPopupBlocked] = useState(false);
const [starting, setStarting] = useState(false);
const startedAtRef = useRef(0);
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
const load = useCallback(() => {
getPlexState()
.then((state) => {
if (activeRef.current) {
setBoot({ status: 'ready', state });
}
})
.catch((error: unknown) => {
if (activeRef.current) {
setBoot({ status: 'error', error: messageFromMediaSourcesError(error, 'Unable to load Plex') });
}
});
}, []);
useEffect(() => {
load();
}, [load]);
// The poll loop. A single interval, armed only while `polling` is true (flipped off on any
// terminal state), so the 2s cadence is stable rather than re-armed on every observation.
useEffect(() => {
if (!polling) {
return undefined;
}
const id = window.setInterval(() => {
getPlexState()
.then((state) => {
if (!activeRef.current) {
return;
}
setBoot({ status: 'ready', state });
const elapsed = Date.now() - startedAtRef.current;
const next = evaluatePinFlow(state, { budgetExhausted: isPinFlowBudgetExhausted(elapsed) });
setPinState(next);
if (next.done) {
setPolling(false);
}
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setActionError(messageFromMediaSourcesError(error, 'Plex sign-in polling failed'));
setPolling(false);
});
}, PIN_FLOW_POLL_INTERVAL_MS);
return () => window.clearInterval(id);
}, [polling]);
const startPinFlow = () => {
if (starting || polling) {
return;
}
setStarting(true);
setActionError(null);
setPopupBlocked(false);
startPlexPinFlow()
.then((flow) => {
if (!activeRef.current) {
return;
}
const url = flow.authUrl ?? '';
setAuthUrl(url);
// Open the Plex auth page in a new tab (design §C1 step 3). window.open initiated from the
// click gesture; if the browser blocks the popup it returns null and we surface a clickable
// link fallback so the user can still reach plex.tv.
const popup = url ? window.open(url, '_blank') : null;
setPopupBlocked(url !== '' && !popup);
startedAtRef.current = Date.now();
setPinState(initialPinFlowState());
setPolling(true);
setStarting(false);
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setActionError(messageFromMediaSourcesError(error, 'Unable to start Plex sign-in'));
setStarting(false);
});
};
const doSignOut = () => {
setSigningOut(true);
setActionError(null);
signOutOfPlex()
.then(() => {
if (!activeRef.current) {
return;
}
setConfirmSignOut(false);
setSigningOut(false);
setPinState(null);
setPolling(false);
setAuthUrl(null);
load();
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setSigningOut(false);
setActionError(messageFromMediaSourcesError(error, 'Unable to sign out of Plex'));
load();
});
};
const refresh = (serverId: number) => {
setRefreshingId(serverId);
setActionError(null);
refreshRemoteLibraries('plex', serverId)
.then(() => {
if (activeRef.current) {
setRefreshingId(null);
}
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setRefreshingId(null);
setActionError(messageFromMediaSourcesError(error, 'Unable to refresh Plex libraries'));
load();
});
};
if (boot.status === 'loading') {
return (
<Card title={<h2>Loading Plex</h2>} subtitle="Fetching Plex connection state.">
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading Plex</span>
</div>
</Card>
);
}
if (boot.status === 'error') {
return (
<Card
title={<h2>Plex unavailable</h2>}
subtitle="The API returned an error while loading Plex."
actions={
<Button onClick={() => { setBoot({ status: 'loading' }); load(); }} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">
Retry
</Button>
}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{boot.error}</span>
</div>
</Card>
);
}
const { isAuthorized, isLocked, servers } = boot.state;
const serverList = servers ?? [];
const connected = serverList.length > 0;
const needsFix = connected && !isAuthorized;
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">Media source</span>
<h2>Plex</h2>
<p>Sign in to Plex to discover servers and choose which libraries to sync.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button onClick={() => navigateToPath('/app/libraries')} variant="ghost">Back to libraries</Button>
</div>
</section>
{actionError && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{actionError}</span>
</div>
)}
<Card
title={<h3>Connection</h3>}
subtitle={connected ? (isAuthorized ? 'Signed in to Plex.' : 'Signed in, but credentials need attention.') : 'Not signed in.'}
actions={
<div style={{ display: 'flex', gap: 8 }}>
{!connected && (
<Button disabled={starting || polling} loading={starting} onClick={startPinFlow} startIcon={<LogIn aria-hidden="true" size={14} />}>
Sign in to Plex
</Button>
)}
{needsFix && (
<Button disabled={starting || polling} loading={starting} onClick={startPinFlow} startIcon={<KeyRound aria-hidden="true" size={14} />}>
Fix Plex Credentials
</Button>
)}
{connected && (
<Button disabled={signingOut || polling} onClick={() => setConfirmSignOut(true)} startIcon={<LogOut aria-hidden="true" size={14} />} variant="secondary">
Sign out of Plex
</Button>
)}
</div>
}
>
{(polling || pinState) && (
<div className="ctv-dashboard-state" role="status">
{polling && <Spinner size={16} tone="accent" />}
<span>{pinState?.message}</span>
{(popupBlocked || (polling && authUrl)) && authUrl && (
<a href={authUrl} target="_blank" rel="noreferrer noopener">Open the Plex sign-in page</a>
)}
</div>
)}
{!polling && !pinState && !connected && (
<div className="ctv-schedule-empty">Sign in to Plex to connect a server.</div>
)}
</Card>
{connected && (
<Card title={<h3>Servers</h3>} subtitle={`${serverList.length} server${serverList.length === 1 ? '' : 's'} discovered.`} padded={false}>
<div className="ctv-library-list" role="list" aria-label="Plex servers">
{serverList.map((server) => (
<div className="ctv-library-row" role="listitem" key={server.id}>
<span className="ctv-library-media-icon"><Server aria-hidden="true" size={14} /></span>
<div className="ctv-library-row-main">
<strong>{server.name}</strong>
<span>{server.address ?? 'Unknown address'}</span>
</div>
<div className="ctv-library-row-status">
<StatusDot status={isLocked ? 'live' : 'ok'} label={isLocked ? 'Busy' : 'Ready'} size={7} />
<IconButton disabled={isLocked || refreshingId === server.id} onClick={() => refresh(server.id)} size="sm" title={`Refresh ${server.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
<Button onClick={() => navigateToPath(remoteLibrariesRoute('plex', server.id))} size="sm" variant="ghost">Edit Libraries</Button>
<Button onClick={() => navigateToPath(pathReplacementsRoute('plex', server.id))} size="sm" variant="ghost">Edit Path Replacements</Button>
</div>
</div>
))}
</div>
</Card>
)}
{needsFix && (
<div className="ctv-libraries-summary">
<span><Badge tone="neutral">Action needed</Badge> Plex reported servers but the stored credentials are not authorized. Use Fix Plex Credentials.</span>
</div>
)}
<ConfirmDialog
open={confirmSignOut}
tone="danger"
title="Sign out of Plex"
message="Signing out removes all synced Plex servers, libraries, and content from ErsatzTV. This cannot be undone. Continue?"
confirmLabel="Sign out"
busy={signingOut}
onConfirm={doSignOut}
onCancel={() => setConfirmSignOut(false)}
/>
</div>
);
}
@@ -0,0 +1,137 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RemoteConnectionEditScreen } from './RemoteConnectionEditScreen';
import { canLeaveCurrentScreen } from '../navigationGuard';
function json(body: unknown, status = 200): Response {
const contentType = status === 204 ? undefined : 'application/json';
return new Response(status === 204 ? null : JSON.stringify(body), {
headers: contentType ? { 'Content-Type': contentType } : undefined,
status
});
}
interface Options {
connection: { address: string | null; hasApiKey: boolean };
saveStatus?: number;
saveBody?: unknown;
}
function installFetch(family: string, options: Options) {
const putBodies: string[] = [];
const spy = vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const method = (init?.method ?? 'GET').toUpperCase();
if (url.endsWith(`/api/media-sources/${family}/connection`) && method === 'GET') {
return Promise.resolve(json(options.connection));
}
if (url.endsWith(`/api/media-sources/${family}/connection`) && method === 'PUT') {
putBodies.push(String(init?.body ?? ''));
const status = options.saveStatus ?? 200;
if (status >= 400) {
return Promise.resolve(json({ title: 'Invalid', detail: 'Connection failed' }, status));
}
return Promise.resolve(json(options.saveBody ?? { address: options.connection.address, hasApiKey: true }));
}
return Promise.resolve(json({}, 404));
});
return { spy, putBodies };
}
describe('RemoteConnectionEditScreen', () => {
beforeEach(() => {
vi.restoreAllMocks();
window.history.replaceState(null, '', '/app/libraries/jellyfin/connection');
});
afterEach(() => {
cleanup();
});
it('secure key affordance: shows "leave blank to keep" and NEVER renders the stored key', async () => {
installFetch('jellyfin', { connection: { address: 'http://jf:8096', hasApiKey: true } });
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
expect(address.value).toBe('http://jf:8096');
const keyField = screen.getByPlaceholderText(/leave blank to keep/i) as HTMLInputElement;
// The stored key is never sent to the client, so the field is empty and there is no secret in the DOM.
expect(keyField.value).toBe('');
expect(document.body.textContent).not.toMatch(/secret|apikey-value/i);
});
it('blank key is retained on save (PUT body carries an empty apiKey)', async () => {
const { putBodies } = installFetch('jellyfin', {
connection: { address: 'http://jf:8096', hasApiKey: true },
saveBody: { address: 'http://jf:9000', hasApiKey: true }
});
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
// Change only the address, leave the key blank.
fireEvent.change(address, { target: { value: 'http://jf:9000' } });
fireEvent.click(screen.getByRole('button', { name: 'Save connection' }));
await vi.waitFor(() => expect(putBodies.length).toBe(1));
const body = JSON.parse(putBodies[0]);
expect(body.address).toBe('http://jf:9000');
expect(body.apiKey).toBe(''); // blank = retain existing key server-side
});
it('first connect (no stored key) requires an api key before Save enables', async () => {
installFetch('jellyfin', { connection: { address: '', hasApiKey: false } });
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
fireEvent.change(address, { target: { value: 'http://jf:8096' } });
// Address valid but no key yet: Connect stays disabled.
const connect = screen.getByRole('button', { name: 'Connect' }) as HTMLButtonElement;
expect(connect.disabled).toBe(true);
fireEvent.change(screen.getByPlaceholderText(/Enter an API key/i), { target: { value: 'newkey123' } });
expect((screen.getByRole('button', { name: 'Connect' }) as HTMLButtonElement).disabled).toBe(false);
});
it('retains the draft on a 422 save failure', async () => {
const { putBodies } = installFetch('jellyfin', {
connection: { address: 'http://jf:8096', hasApiKey: true },
saveStatus: 422
});
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
fireEvent.change(address, { target: { value: 'http://jf:9999' } });
fireEvent.click(screen.getByRole('button', { name: 'Save connection' }));
await vi.waitFor(() => expect(putBodies.length).toBe(1));
// Draft not reset: the edited address is still present and the error is surfaced.
expect((screen.getByPlaceholderText(/192.168/i) as HTMLInputElement).value).toBe('http://jf:9999');
expect(await screen.findByText(/Connection failed/i)).toBeTruthy();
});
it('dirty guard vetoes navigation until confirmed', async () => {
installFetch('jellyfin', { connection: { address: 'http://jf:8096', hasApiKey: true } });
render(<RemoteConnectionEditScreen family="jellyfin" />);
const address = (await screen.findByPlaceholderText(/192.168/i)) as HTMLInputElement;
// Clean: guard allows leaving.
expect(canLeaveCurrentScreen()).toBe(true);
fireEvent.change(address, { target: { value: 'http://jf:changed' } });
// Let the dirty effect commit.
await vi.waitFor(() => expect((screen.getByPlaceholderText(/192.168/i) as HTMLInputElement).value).toBe('http://jf:changed'));
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
expect(canLeaveCurrentScreen()).toBe(false); // dirty + confirm=false → vetoed
confirmSpy.mockReturnValue(true);
expect(canLeaveCurrentScreen()).toBe(true); // confirm=true → allowed
confirmSpy.mockRestore();
});
});
@@ -0,0 +1,196 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowLeft, Check, TriangleAlert } from 'lucide-react';
import { Button, Card, Input, Spinner } from '../components';
import {
getRemoteConnection,
messageFromMediaSourcesError,
saveRemoteConnection
} from '../api';
import { navigateToPath } from '../routing';
import { familyMeta, familyRoute } from '../mediaSources/familyMeta';
import { useDirtyGuard } from '../mediaSources/useDirtyGuard';
type RemoteFamilyWithConnection = 'jellyfin' | 'emby';
interface Draft {
address: string;
apiKey: string;
}
interface LoadedState {
hasApiKey: boolean;
}
const DIRTY_PROMPT = 'You have unsaved connection changes. Discard them?';
// Absolute-URL validation matching RemoteMediaSourceEditViewModelValidator (non-empty absolute URI).
function isValidAddress(value: string): boolean {
const trimmed = value.trim();
if (!trimmed) {
return false;
}
try {
const url = new URL(trimmed);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
// Shared connection editor for the api-key families (Jellyfin / Emby), mirroring
// RemoteMediaSourceEditor. SECURE KEY AFFORDANCE (design §C3 / finding 1): the stored api key NEVER
// crosses the wire — GET returns only { address, hasApiKey }. When a key is already set the field
// shows "leave blank to keep" and is optional (blank retains the existing key server-side); on first
// connect the key is required. The stored key is never displayed.
export function RemoteConnectionEditScreen({ family }: { family: RemoteFamilyWithConnection }) {
const meta = familyMeta(family);
const [loaded, setLoaded] = useState<LoadedState | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft>({ address: '', apiKey: '' });
const [saved, setSaved] = useState<Draft>({ address: '', apiKey: '' });
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
useEffect(() => {
getRemoteConnection(family)
.then((connection) => {
if (!activeRef.current) {
return;
}
const initial: Draft = { address: connection.address ?? '', apiKey: '' };
setDraft(initial);
setSaved(initial);
setLoaded({ hasApiKey: connection.hasApiKey });
})
.catch((error: unknown) => {
if (activeRef.current) {
setLoadError(messageFromMediaSourcesError(error, `Unable to load ${meta.label} connection`));
}
});
}, [family, meta.label]);
const hasApiKey = loaded?.hasApiKey ?? false;
const addressValid = isValidAddress(draft.address);
// First connect (no stored key) requires a key; when a key is already set, blank means "retain".
const apiKeyValid = hasApiKey || draft.apiKey.trim().length > 0;
const valid = addressValid && apiKeyValid;
const dirty = JSON.stringify(draft) !== JSON.stringify(saved);
useDirtyGuard(dirty, DIRTY_PROMPT);
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>{loadError}</span>
<Button onClick={() => navigateToPath(familyRoute(family))} size="sm" variant="secondary">Back to {meta.label}</Button>
</div>
);
}
if (loaded === null) {
return (
<div className="ctv-settings-loading">
<Spinner size={16} tone="muted" />
<span>Loading {meta.label} connection…</span>
</div>
);
}
const discard = () => {
if (!dirty || window.confirm(DIRTY_PROMPT)) {
setDraft(saved);
setSaveError(null);
}
};
const save = () => {
if (!valid || !dirty || saving) {
return;
}
setSaving(true);
setSaveError(null);
saveRemoteConnection(family, { address: draft.address.trim(), apiKey: draft.apiKey })
.then((connection) => {
if (!activeRef.current) {
return;
}
// Reset the baseline from the reloaded connection; the key is intentionally not returned.
const next: Draft = { address: connection.address ?? '', apiKey: '' };
setDraft(next);
setSaved(next);
setLoaded({ hasApiKey: connection.hasApiKey });
setSaving(false);
navigateToPath(familyRoute(family));
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
// Draft retained on 422 / network / 409 so the user's input is not lost.
setSaving(false);
setSaveError(messageFromMediaSourcesError(error, `Unable to save ${meta.label} connection`));
});
};
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">Media source</span>
<h2>{hasApiKey ? `Edit ${meta.label} connection` : `Connect ${meta.label}`}</h2>
<p>Point ErsatzTV at your {meta.label} server and authenticate with an API key.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button onClick={() => navigateToPath(familyRoute(family))} startIcon={<ArrowLeft aria-hidden="true" size={14} />} variant="ghost">Back to {meta.label}</Button>
</div>
</section>
<Card title={<h3>Connection</h3>} subtitle={`${meta.label} server address and API key.`}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 480 }}>
<Input
label="Address"
value={draft.address}
onChange={(event) => setDraft((current) => ({ ...current, address: event.target.value }))}
placeholder="http://192.168.1.50:8096"
error={draft.address.trim() && !addressValid ? 'Enter a valid absolute http(s) URL' : null}
/>
<Input
label="API key"
type="password"
value={draft.apiKey}
onChange={(event) => setDraft((current) => ({ ...current, apiKey: event.target.value }))}
placeholder={hasApiKey ? 'Key is set — leave blank to keep, or enter a new key' : 'Enter an API key'}
error={!apiKeyValid && draft.apiKey.length === 0 && !hasApiKey ? 'API key is required' : null}
/>
{hasApiKey && (
<span className="ctv-settings-row-help">Key is set — leave blank to keep the existing key, or enter a new key to replace it.</span>
)}
</div>
</Card>
{saveError && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{saveError}</span>
</div>
)}
<div className="ctv-schedule-toolbar">
<div className="ctv-schedule-toolbar-spacer" />
<Button disabled={!dirty || saving} onClick={discard} variant="ghost">Discard</Button>
<Button disabled={!valid || !dirty || saving} loading={saving} onClick={save} startIcon={<Check aria-hidden="true" size={14} />}>
{hasApiKey ? 'Save connection' : 'Connect'}
</Button>
</div>
</div>
);
}
@@ -0,0 +1,148 @@
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RemoteLibrariesEditScreen } from './RemoteLibrariesEditScreen';
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
interface Library {
id: number;
name: string;
mediaKind: string;
shouldSyncItems: boolean;
}
interface Options {
libraries: Library[];
saveStatus?: number;
saveBody?: Library[];
}
function installFetch(family: string, id: number, options: Options) {
const putBodies: string[] = [];
const spy = vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const method = (init?.method ?? 'GET').toUpperCase();
const base = `/api/media-sources/${family}/${id}/libraries`;
if (url.endsWith(base) && method === 'GET') {
return Promise.resolve(json(options.libraries));
}
if (url.endsWith(base) && method === 'PUT') {
putBodies.push(String(init?.body ?? ''));
const status = options.saveStatus ?? 200;
if (status >= 400) {
return Promise.resolve(json({ title: 'Save failed', detail: 'Nope' }, status));
}
return Promise.resolve(json(options.saveBody ?? options.libraries));
}
return Promise.resolve(json({}, 404));
});
return { spy, putBodies };
}
function bodyRowNames(): string[] {
const rows = screen.getAllByRole('row').slice(1); // skip header
return rows.map((row) => within(row).getAllByRole('cell')[0]?.textContent ?? '');
}
describe('RemoteLibrariesEditScreen', () => {
beforeEach(() => {
vi.restoreAllMocks();
window.history.replaceState(null, '', '/app/libraries/plex/7/sync');
});
afterEach(() => {
cleanup();
});
it('sorts by Name and toggles direction on repeat click', async () => {
installFetch('plex', 7, {
libraries: [
{ id: 1, name: 'Movies', mediaKind: 'Movies', shouldSyncItems: true },
{ id: 2, name: 'Anime', mediaKind: 'Shows', shouldSyncItems: false },
{ id: 3, name: 'Zed', mediaKind: 'Shows', shouldSyncItems: false }
]
});
render(<RemoteLibrariesEditScreen family="plex" sourceId={7} />);
await screen.findByRole('switch', { name: /Sync Movies/i });
// Default ascending by name.
expect(bodyRowNames()).toEqual(['Anime', 'Movies', 'Zed']);
// Click Name → toggles to descending.
fireEvent.click(screen.getByRole('button', { name: /Name/i }));
expect(bodyRowNames()).toEqual(['Zed', 'Movies', 'Anime']);
});
it('sorts by Media Kind', async () => {
installFetch('plex', 7, {
libraries: [
{ id: 1, name: 'Movies', mediaKind: 'Movies', shouldSyncItems: true },
{ id: 2, name: 'Anime', mediaKind: 'Shows', shouldSyncItems: false }
]
});
render(<RemoteLibrariesEditScreen family="plex" sourceId={7} />);
await screen.findByRole('switch', { name: /Sync Movies/i });
fireEvent.click(screen.getByRole('button', { name: /Media Kind/i }));
// Movies < Shows ascending, so Movies row first.
expect(bodyRowNames()).toEqual(['Movies', 'Anime']);
});
it('toggling a sync switch enables Save, and Save PUTs the preferences and refetches', async () => {
const { putBodies } = installFetch('plex', 7, {
libraries: [{ id: 1, name: 'Movies', mediaKind: 'Movies', shouldSyncItems: false }],
// Reloaded list: id CHANGES on a toggle (design §C4a) — the SPA keys by name/mediaKind, so it copes.
saveBody: [{ id: 99, name: 'Movies', mediaKind: 'Movies', shouldSyncItems: true }]
});
render(<RemoteLibrariesEditScreen family="plex" sourceId={7} />);
await screen.findByRole('switch', { name: /Sync Movies/i });
const save = () => screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement;
expect(save().disabled).toBe(true); // clean
fireEvent.click(screen.getByRole('switch', { name: /Sync Movies/i }));
expect(save().disabled).toBe(false); // dirty
fireEvent.click(save());
await vi.waitFor(() => expect(putBodies.length).toBe(1));
const body = JSON.parse(putBodies[0]);
expect(body.libraries).toEqual([{ id: 1, shouldSyncItems: true }]);
// After the refetch the new baseline is clean again despite the id change.
await vi.waitFor(() => expect(save().disabled).toBe(true));
});
it('retains the draft on a 422 save failure', async () => {
const { putBodies } = installFetch('plex', 7, {
libraries: [{ id: 1, name: 'Movies', mediaKind: 'Movies', shouldSyncItems: false }],
saveStatus: 422
});
render(<RemoteLibrariesEditScreen family="plex" sourceId={7} />);
await screen.findByRole('switch', { name: /Sync Movies/i });
fireEvent.click(screen.getByRole('switch', { name: /Sync Movies/i }));
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await vi.waitFor(() => expect(putBodies.length).toBe(1));
// Wait for the failure to settle (saving clears in the catch).
expect(await screen.findByText(/Nope/i)).toBeTruthy();
// Still dirty (draft retained) and the switch stays on.
expect((screen.getByRole('switch', { name: /Sync Movies/i })).getAttribute('aria-checked')).toBe('true');
expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(false);
});
it('renders a not-found state on a 404', async () => {
vi.spyOn(window, 'fetch').mockResolvedValue(json({ title: 'Not found' }, 404));
render(<RemoteLibrariesEditScreen family="plex" sourceId={7} />);
expect(await screen.findByText(/no longer exists/i)).toBeTruthy();
});
});
Binary file not shown.
@@ -0,0 +1,92 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RemoteSourceScreen } from './RemoteSourceScreen';
function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
interface RemoteState {
isAuthorized: boolean;
isLocked: boolean;
servers: Array<{ id: number; name: string; address: string }>;
}
function installFetch(family: string, stateRef: { current: RemoteState }) {
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
const method = (init?.method ?? 'GET').toUpperCase();
if (url.endsWith(`/api/media-sources/${family}/disconnect`) && method === 'POST') {
return Promise.resolve(new Response(null, { status: 204 }));
}
if (url.includes('/refresh-libraries') && method === 'POST') {
return Promise.resolve(new Response(null, { status: 204 }));
}
if (url.endsWith(`/api/media-sources/${family}`) && method === 'GET') {
return Promise.resolve(json(stateRef.current));
}
return Promise.resolve(json({}, 404));
});
}
describe('RemoteSourceScreen', () => {
beforeEach(() => {
vi.restoreAllMocks();
window.history.replaceState(null, '', '/app/libraries/jellyfin');
});
afterEach(() => {
cleanup();
});
it('shows a Connect action when no server is connected', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as RemoteState };
installFetch('jellyfin', stateRef);
render(<RemoteSourceScreen family="jellyfin" />);
expect(await screen.findByRole('button', { name: 'Connect' })).toBeTruthy();
expect(screen.getByText(/Connect a Jellyfin server to sync/i)).toBeTruthy();
});
it('lists servers with Refresh disabled while the family lock is held', async () => {
const stateRef = { current: { isAuthorized: true, isLocked: true, servers: [{ id: 3, name: 'Media Box', address: 'http://jf:8096' }] } as RemoteState };
installFetch('jellyfin', stateRef);
render(<RemoteSourceScreen family="jellyfin" />);
await screen.findByRole('heading', { name: 'Servers' });
expect(screen.getByText('Media Box')).toBeTruthy();
const refresh = screen.getByRole('button', { name: /Refresh Media Box/i }) as HTMLButtonElement;
expect(refresh.disabled).toBe(true);
});
it('disconnect shows the content-removal warning and posts on confirm', async () => {
const stateRef = { current: { isAuthorized: true, isLocked: false, servers: [{ id: 3, name: 'Media Box', address: 'http://jf:8096' }] } as RemoteState };
const fetchSpy = installFetch('jellyfin', stateRef);
render(<RemoteSourceScreen family="jellyfin" />);
await screen.findByRole('heading', { name: 'Servers' });
fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }));
expect(await screen.findByText(/removes all synced Jellyfin libraries/i)).toBeTruthy();
// The header button and the dialog confirm share the label; the dialog's is the last one.
const disconnects = screen.getAllByRole('button', { name: 'Disconnect' });
fireEvent.click(disconnects[disconnects.length - 1]);
await vi.waitFor(() =>
expect(fetchSpy.mock.calls.some(([input, init]) => String(input).endsWith('/disconnect') && (init?.method ?? '').toUpperCase() === 'POST')).toBe(true)
);
});
it('uses the family label for Emby', async () => {
const stateRef = { current: { isAuthorized: false, isLocked: false, servers: [] } as RemoteState };
installFetch('emby', stateRef);
render(<RemoteSourceScreen family="emby" />);
expect(await screen.findByRole('heading', { name: 'Emby' })).toBeTruthy();
expect(screen.getByText(/Connect a Emby server to sync/i)).toBeTruthy();
});
});
+214
View File
@@ -0,0 +1,214 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Plug, RefreshCw, Server, Unplug, TriangleAlert } from 'lucide-react';
import { Button, Card, ConfirmDialog, IconButton, Spinner, StatusDot } from '../components';
import {
disconnectRemote,
getRemoteState,
messageFromMediaSourcesError,
refreshRemoteLibraries,
type RemoteMediaSourceState
} from '../api';
import { navigateToPath } from '../routing';
import {
familyMeta,
pathReplacementsRoute,
remoteConnectionRoute,
remoteLibrariesRoute
} from '../mediaSources/familyMeta';
type RemoteFamilyWithConnection = 'jellyfin' | 'emby';
type BootState =
| { status: 'loading' }
| { status: 'error'; error: string }
| { status: 'ready'; state: RemoteMediaSourceState };
// Shared source screen for the api-key families (Jellyfin / Emby), mirroring
// {Jellyfin,Emby}MediaSources.razor. Connect / edit-connection navigate to the shared connection
// editor; Disconnect purges all synced content (confirm dialog). Server rows offer Refresh (disabled
// while the family lock is held) / Edit Libraries / Edit Path Replacements.
export function RemoteSourceScreen({ family }: { family: RemoteFamilyWithConnection }) {
const meta = familyMeta(family);
const [boot, setBoot] = useState<BootState>({ status: 'loading' });
const [actionError, setActionError] = useState<string | null>(null);
const [confirmDisconnect, setConfirmDisconnect] = useState(false);
const [disconnecting, setDisconnecting] = useState(false);
const [refreshingId, setRefreshingId] = useState<number | null>(null);
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
const load = useCallback(() => {
getRemoteState(family)
.then((state) => {
if (activeRef.current) {
setBoot({ status: 'ready', state });
}
})
.catch((error: unknown) => {
if (activeRef.current) {
setBoot({ status: 'error', error: messageFromMediaSourcesError(error, `Unable to load ${meta.label}`) });
}
});
}, [family, meta.label]);
useEffect(() => {
load();
}, [load]);
const doDisconnect = () => {
setDisconnecting(true);
setActionError(null);
disconnectRemote(family)
.then(() => {
if (!activeRef.current) {
return;
}
setConfirmDisconnect(false);
setDisconnecting(false);
load();
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setDisconnecting(false);
setActionError(messageFromMediaSourcesError(error, `Unable to disconnect ${meta.label}`));
load();
});
};
const refresh = (serverId: number) => {
setRefreshingId(serverId);
setActionError(null);
refreshRemoteLibraries(family, serverId)
.then(() => {
if (activeRef.current) {
setRefreshingId(null);
}
})
.catch((error: unknown) => {
if (!activeRef.current) {
return;
}
setRefreshingId(null);
setActionError(messageFromMediaSourcesError(error, `Unable to refresh ${meta.label} libraries`));
load();
});
};
if (boot.status === 'loading') {
return (
<Card title={<h2>Loading {meta.label}</h2>} subtitle={`Fetching ${meta.label} connection state.`}>
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading {meta.label}</span>
</div>
</Card>
);
}
if (boot.status === 'error') {
return (
<Card
title={<h2>{meta.label} unavailable</h2>}
subtitle={`The API returned an error while loading ${meta.label}.`}
actions={
<Button onClick={() => { setBoot({ status: 'loading' }); load(); }} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">
Retry
</Button>
}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{boot.error}</span>
</div>
</Card>
);
}
const { isLocked, servers } = boot.state;
const serverList = servers ?? [];
const connected = serverList.length > 0;
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">Media source</span>
<h2>{meta.label}</h2>
<p>Connect a {meta.label} server and choose which libraries to sync.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button onClick={() => navigateToPath('/app/libraries')} variant="ghost">Back to libraries</Button>
</div>
</section>
{actionError && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{actionError}</span>
</div>
)}
<Card
title={<h3>Connection</h3>}
subtitle={connected ? `Connected to ${meta.label}.` : `No ${meta.label} server connected.`}
actions={
<div style={{ display: 'flex', gap: 8 }}>
<Button onClick={() => navigateToPath(remoteConnectionRoute(family))} startIcon={<Plug aria-hidden="true" size={14} />} variant={connected ? 'secondary' : 'primary'}>
{connected ? 'Edit connection' : 'Connect'}
</Button>
{connected && (
<Button disabled={disconnecting} onClick={() => setConfirmDisconnect(true)} startIcon={<Unplug aria-hidden="true" size={14} />} variant="secondary">
Disconnect
</Button>
)}
</div>
}
>
{!connected && <div className="ctv-schedule-empty">Connect a {meta.label} server to sync libraries.</div>}
</Card>
{connected && (
<Card title={<h3>Servers</h3>} subtitle={`${serverList.length} server${serverList.length === 1 ? '' : 's'}.`} padded={false}>
<div className="ctv-library-list" role="list" aria-label={`${meta.label} servers`}>
{serverList.map((server) => (
<div className="ctv-library-row" role="listitem" key={server.id}>
<span className="ctv-library-media-icon"><Server aria-hidden="true" size={14} /></span>
<div className="ctv-library-row-main">
<strong>{server.name}</strong>
<span>{server.address ?? 'Unknown address'}</span>
</div>
<div className="ctv-library-row-status">
<StatusDot status={isLocked ? 'live' : 'ok'} label={isLocked ? 'Busy' : 'Ready'} size={7} />
<IconButton disabled={isLocked || refreshingId === server.id} onClick={() => refresh(server.id)} size="sm" title={`Refresh ${server.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
<Button onClick={() => navigateToPath(remoteLibrariesRoute(family, server.id))} size="sm" variant="ghost">Edit Libraries</Button>
<Button onClick={() => navigateToPath(pathReplacementsRoute(family, server.id))} size="sm" variant="ghost">Edit Path Replacements</Button>
</div>
</div>
))}
</div>
</Card>
)}
<ConfirmDialog
open={confirmDisconnect}
tone="danger"
title={`Disconnect ${meta.label}`}
message={`Disconnecting removes all synced ${meta.label} libraries and content from ErsatzTV. This cannot be undone. Continue?`}
confirmLabel="Disconnect"
busy={disconnecting}
onConfirm={doDisconnect}
onCancel={() => setConfirmDisconnect(false)}
/>
</div>
);
}