feat: add identification page

This commit is contained in:
2025-12-18 05:58:08 +09:00
parent e3d3df9ecb
commit d848cf193c
15 changed files with 719 additions and 75 deletions
+177 -57
View File
@@ -15,8 +15,9 @@ import { SYNC_BANNER_PADDING_X, SYNC_BANNER_PADDING_Y, SYNC_BANNER_MIN_WIDTH } f
import ServerPanel from './components/ServerPanel';
import StrategySelector from './components/StrategySelector';
import ConnectionModal from './components/ConnectionModal';
import LoginScreen from './components/LoginScreen';
import OverflowMarquee from './components/OverflowMarquee';
import { ArrowLeftRight, ShieldCheck, X, Server, ServerOff, Clock, Eye, EyeOff, Type, Code2, Archive, Languages } from 'lucide-react';
import { ArrowLeftRight, ShieldCheck, X, Server, ServerOff, Clock, Eye, EyeOff, Type, Code2, Archive, Languages, LogOut } from 'lucide-react';
import { useLanguage } from './LanguageContext';
interface Toast {
@@ -115,6 +116,12 @@ const useStripeAnimation = (syncState: SyncState) => {
const App: React.FC = () => {
const { t, language, setLanguage } = useLanguage();
// Auth (optional; controlled by backend /api/auth/config)
const [authReady, setAuthReady] = useState(false);
const [authEnabled, setAuthEnabled] = useState(false);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [currentUser, setCurrentUser] = useState('');
const [localPlaylists, setLocalPlaylists] = useState<Playlist[]>([]);
const [cloudPlaylists, setCloudPlaylists] = useState<Playlist[]>([]);
const [cloudServerInfo, setCloudServerInfo] = useState<PlexServerConnection | undefined>(undefined);
@@ -171,6 +178,75 @@ const App: React.FC = () => {
retentionCount: 5
});
useEffect(() => {
let cancelled = false;
const initAuth = async () => {
try {
const cfg = await apiService.getAuthConfig();
const enabled = cfg.status === 'success' ? !!cfg.data.enabled : false;
if (cancelled) return;
setAuthEnabled(enabled);
if (!enabled) {
setIsAuthenticated(true);
setAuthReady(true);
return;
}
const savedToken = localStorage.getItem('plexsync-token');
const savedUser = localStorage.getItem('plexsync-username');
if (!savedToken || !savedUser) {
setIsAuthenticated(false);
setCurrentUser('');
setAuthReady(true);
return;
}
const me = await apiService.me();
if (me.status === 'success') {
setIsAuthenticated(true);
setCurrentUser(me.data.username || savedUser);
} else {
localStorage.removeItem('plexsync-token');
localStorage.removeItem('plexsync-username');
setIsAuthenticated(false);
setCurrentUser('');
}
} catch {
// If auth discovery fails, fall back to no-auth to keep local dev workable.
setAuthEnabled(false);
setIsAuthenticated(true);
} finally {
if (!cancelled) setAuthReady(true);
}
};
initAuth();
return () => {
cancelled = true;
};
}, []);
const handleLoginSuccess = (token: string, username: string) => {
localStorage.setItem('plexsync-token', token);
localStorage.setItem('plexsync-username', username);
setCurrentUser(username);
setIsAuthenticated(true);
};
const handleLogout = async () => {
try {
await apiService.logout();
} catch {
// ignore
}
localStorage.removeItem('plexsync-token');
localStorage.removeItem('plexsync-username');
setIsAuthenticated(false);
setCurrentUser('');
};
// Toast Notification System
const [toasts, setToasts] = useState<Toast[]>([]);
const timeoutsRef = useRef<{[key: number]: ReturnType<typeof setTimeout>}>({});
@@ -299,6 +375,7 @@ const App: React.FC = () => {
// Fetch Local Playlists
const refreshLocal = useCallback(async () => {
if (!authReady || !isAuthenticated) return;
if (localAbortRef.current) localAbortRef.current.abort();
const abortController = new AbortController();
localAbortRef.current = abortController;
@@ -310,7 +387,7 @@ const App: React.FC = () => {
}
setLoadingLocal(false);
localAbortRef.current = null;
}, [localPath]);
}, [authReady, isAuthenticated, localPath]);
const cancelLocalRefresh = () => {
if (localAbortRef.current) {
@@ -323,6 +400,7 @@ const App: React.FC = () => {
// Fetch Cloud Playlists and Info
const refreshCloud = useCallback(async () => {
if (!authReady || !isAuthenticated) return;
if (cloudAbortRef.current) cloudAbortRef.current.abort();
const abortController = new AbortController();
cloudAbortRef.current = abortController;
@@ -344,7 +422,7 @@ const App: React.FC = () => {
setLoadingCloud(false);
cloudAbortRef.current = null;
}
}, []);
}, [authReady, isAuthenticated]);
const cancelCloudRefresh = () => {
if (cloudAbortRef.current) {
@@ -357,13 +435,15 @@ const App: React.FC = () => {
// Load persisted configuration
useEffect(() => {
if (!authReady || !isAuthenticated) return;
loadSettings();
loadSchedule();
loadBackupSettings();
}, [loadSettings, loadSchedule, loadBackupSettings]);
}, [authReady, isAuthenticated, loadSettings, loadSchedule, loadBackupSettings]);
// Initial Load
useEffect(() => {
if (!authReady || !isAuthenticated) return;
refreshLocal();
refreshCloud();
return () => {
@@ -371,7 +451,7 @@ const App: React.FC = () => {
if (localAbortRef.current) localAbortRef.current.abort();
if (cloudAbortRef.current) cloudAbortRef.current.abort();
}
}, [refreshLocal, refreshCloud]);
}, [authReady, isAuthenticated, refreshLocal, refreshCloud]);
// Handle Strategy Change
const handleStrategyChange = async (strategy: SyncStrategy, label: string) => {
@@ -397,6 +477,7 @@ const App: React.FC = () => {
// Handle Sync Trigger
const handleSyncTrigger = async () => {
if (!authReady || !isAuthenticated) return;
if (syncState !== SyncState.IDLE) return;
setSyncState(SyncState.SYNCING);
@@ -423,7 +504,16 @@ const App: React.FC = () => {
// SSE for sync status
useEffect(() => {
const eventSource = new EventSource(`${import.meta.env.VITE_API_BASE_URL || ''}/api/sync/events`);
if (!authReady || !isAuthenticated) return;
const base = `${import.meta.env.VITE_API_BASE_URL || ''}/api/sync/events`;
const url = new URL(base, window.location.origin);
if (authEnabled) {
const token = localStorage.getItem('plexsync-token');
if (!token) return;
url.searchParams.set('access_token', token);
}
const eventSource = new EventSource(url.toString());
eventSource.onmessage = (event) => {
try {
@@ -490,7 +580,24 @@ const App: React.FC = () => {
return () => {
eventSource.close();
};
}, [syncState, refreshLocal, refreshCloud, addToast]);
}, [authReady, isAuthenticated, authEnabled, syncState, refreshLocal, refreshCloud, addToast]);
if (!authReady) {
return (
<div className="min-h-screen flex items-center justify-center bg-gray-900 text-gray-200">
{t('common.loading')}
</div>
);
}
if (authEnabled && !isAuthenticated) {
return (
<LoginScreen
onLoginSuccess={handleLoginSuccess}
onLoginError={(msg) => addToast(msg)}
/>
);
}
const handleConnectSuccess = async (serverInfo: PlexServerConnection) => {
setCloudServerInfo(serverInfo);
@@ -725,60 +832,73 @@ const App: React.FC = () => {
</div>
</div>
{/* Language Switcher */}
<div className="relative">
<button
onClick={() => setIsLangMenuOpen(!isLangMenuOpen)}
className="flex items-center justify-center w-9 h-9 rounded-full border border-gray-700 bg-gray-800/50 text-gray-400 hover:text-white hover:bg-gray-700 transition-all"
title={t('common.switchLanguage')}
<div className="flex items-center gap-4">
{/* Language Switcher */}
<div className="relative">
<button
onClick={() => setIsLangMenuOpen(!isLangMenuOpen)}
className="flex items-center justify-center w-9 h-9 rounded-full border border-gray-700 bg-gray-800/50 text-gray-400 hover:text-white hover:bg-gray-700 transition-all"
title={t('common.switchLanguage')}
>
<Languages size={18} />
</button>
{isLangMenuOpen && (
<>
<div className="fixed inset-0 z-40" onClick={() => setIsLangMenuOpen(false)}></div>
<div className="absolute right-0 top-full mt-2 w-32 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-50 overflow-hidden">
<button
onClick={() => { setLanguage('en'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'en' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
English
</button>
<button
onClick={() => { setLanguage('es'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'es' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
Español
</button>
<button
onClick={() => { setLanguage('chs'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'chs' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
<button
onClick={() => { setLanguage('cht'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'cht' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
</div>
</>
)}
</div>
{/* Connection Status Button */}
<button
onClick={() => setIsConnectionModalOpen(true)}
className={`flex items-center justify-center w-9 h-9 rounded-full border transition-all duration-300 hover:scale-105 active:scale-95 shadow-md
${isConnected
? "bg-green-500/10 border-green-500/50 text-green-400 hover:bg-green-500/20 hover:shadow-green-500/20"
: "bg-red-500/10 border-red-500/50 text-red-400 hover:bg-red-500/20 hover:shadow-red-500/20"
}`}
title={isConnected ? t('dashboard.connected') : t('dashboard.disconnected')}
>
<Languages size={18} />
{isConnected ? <Server size={18} /> : <ServerOff size={18} />}
</button>
{isLangMenuOpen && (
<>
<div className="fixed inset-0 z-40" onClick={() => setIsLangMenuOpen(false)}></div>
<div className="absolute right-0 top-full mt-2 w-32 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-50 overflow-hidden">
<button
onClick={() => { setLanguage('en'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'en' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
English
</button>
<button
onClick={() => { setLanguage('es'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'es' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
Español
</button>
<button
onClick={() => { setLanguage('chs'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'chs' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
<button
onClick={() => { setLanguage('cht'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'cht' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
</div>
</>
{/* Logout (rightmost) */}
{authEnabled && isAuthenticated && (
<button
onClick={handleLogout}
className="flex items-center justify-center w-9 h-9 rounded-full border border-gray-700 bg-gray-800/50 text-gray-400 hover:text-white hover:bg-gray-700 transition-all"
title={t('auth.logout')}
>
<LogOut size={18} />
</button>
)}
</div>
{/* Connection Status Button */}
<button
onClick={() => setIsConnectionModalOpen(true)}
className={`flex items-center justify-center w-9 h-9 rounded-full border transition-all duration-300 hover:scale-105 active:scale-95 shadow-md
${isConnected
? "bg-green-500/10 border-green-500/50 text-green-400 hover:bg-green-500/20 hover:shadow-green-500/20"
: "bg-red-500/10 border-red-500/50 text-red-400 hover:bg-red-500/20 hover:shadow-red-500/20"
}`}
title={isConnected ? t('dashboard.connected') : t('dashboard.disconnected')}
>
{isConnected ? <Server size={18} /> : <ServerOff size={18} />}
</button>
</div>
</>
) : (
+182
View File
@@ -0,0 +1,182 @@
import React, { useState } from 'react';
import { useLanguage } from '../LanguageContext';
import { apiService } from '../services/api';
import { Lock, User, Loader2, Languages, ArrowRight, ArrowLeftRight } from 'lucide-react';
import type { LoginCredentials } from '../types';
interface LoginScreenProps {
onLoginSuccess: (token: string, username: string) => void;
onLoginError: (msg: string) => void;
}
const LoginScreen: React.FC<LoginScreenProps> = ({ onLoginSuccess, onLoginError }) => {
const { t, language, setLanguage } = useLanguage();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [localError, setLocalError] = useState<string | null>(null);
const [isLangMenuOpen, setIsLangMenuOpen] = useState(false);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
setLocalError(null);
try {
const creds: LoginCredentials = { username, password };
const response = await apiService.login(creds);
if (response.status === 'success') {
onLoginSuccess(response.data.token, response.data.username);
} else {
const errorMsg = response.message || t('auth.invalidCredentials');
setLocalError(errorMsg);
onLoginError(errorMsg);
}
} catch {
setLocalError(t('auth.invalidCredentials'));
} finally {
setIsLoading(false);
}
};
const currentLangLabel =
language === 'en' ? 'English'
: language === 'es' ? 'Español'
: language === 'chs' ? '简体中文'
: '繁體中文';
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-gray-800 via-gray-900 to-black p-4">
<div className="absolute top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
<div className="absolute top-0 left-1/4 w-96 h-96 bg-plex-orange/10 rounded-full blur-[100px] opacity-20"></div>
<div className="absolute bottom-0 right-1/4 w-96 h-96 bg-blue-500/10 rounded-full blur-[100px] opacity-20"></div>
</div>
{/* Language Switcher (Top Right) */}
<div className="absolute top-6 right-6 z-20">
<div className="relative">
<button
onClick={() => setIsLangMenuOpen(!isLangMenuOpen)}
className="flex items-center space-x-2 px-3 py-2 rounded-lg bg-gray-800/50 hover:bg-gray-700/50 border border-gray-700 hover:border-gray-600 text-gray-300 transition-all backdrop-blur-sm"
>
<Languages size={16} />
<span className="text-sm font-medium">{currentLangLabel}</span>
</button>
{isLangMenuOpen && (
<>
<div className="fixed inset-0 z-10" onClick={() => setIsLangMenuOpen(false)}></div>
<div className="absolute right-0 top-full mt-2 w-32 bg-gray-800 border border-gray-700 rounded-lg shadow-xl z-20 overflow-hidden">
<button
onClick={() => { setLanguage('en'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'en' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
English
</button>
<button
onClick={() => { setLanguage('es'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'es' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
Español
</button>
<button
onClick={() => { setLanguage('chs'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'chs' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
<button
onClick={() => { setLanguage('cht'); setIsLangMenuOpen(false); }}
className={`w-full px-4 py-2 text-sm text-left hover:bg-gray-700 transition-colors ${language === 'cht' ? 'text-plex-orange font-bold' : 'text-gray-300'}`}
>
</button>
</div>
</>
)}
</div>
</div>
{/* Main Card */}
<div className="w-full max-w-md bg-gray-900/60 backdrop-blur-xl border border-gray-700/50 rounded-2xl shadow-2xl p-8 z-10">
<div className="text-center mb-8 flex flex-col items-center">
<div className="inline-flex items-center justify-center p-3 rounded-xl bg-gradient-to-br from-plex-orange to-yellow-600 shadow-lg shadow-plex-orange/20 mb-4">
<ArrowLeftRight size={32} strokeWidth={2.5} className="text-gray-900" />
</div>
<h1 className="text-2xl font-bold tracking-tight text-white">
<span className="text-plex-orange">PMS</span> Playlist Sync
</h1>
</div>
<form onSubmit={handleLogin} className="space-y-4">
{localError && (
<div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-xs flex items-center justify-center">
{localError}
</div>
)}
<div className="space-y-1">
<label className="text-xs font-semibold text-gray-500 uppercase tracking-wider ml-1">{t('auth.username')}</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<User size={16} className="text-gray-500 group-focus-within:text-plex-orange transition-colors" />
</div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full h-11 pl-10 pr-4 bg-gray-800/50 border border-gray-600 rounded-lg text-white placeholder-gray-500 focus:border-plex-orange focus:ring-1 focus:ring-plex-orange focus:outline-none transition-all"
placeholder="username"
/>
</div>
</div>
<div className="space-y-1">
<label className="text-xs font-semibold text-gray-500 uppercase tracking-wider ml-1">{t('auth.password')}</label>
<div className="relative group">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock size={16} className="text-gray-500 group-focus-within:text-plex-orange transition-colors" />
</div>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full h-11 pl-10 pr-4 bg-gray-800/50 border border-gray-600 rounded-lg text-white placeholder-gray-500 focus:border-plex-orange focus:ring-1 focus:ring-plex-orange focus:outline-none transition-all"
placeholder="password"
/>
</div>
</div>
<button
type="submit"
disabled={isLoading || !username || !password}
className={`w-full h-12 mt-6 rounded-lg text-sm font-bold flex items-center justify-center gap-2 transition-all shadow-lg
${isLoading
? 'bg-gray-700 text-gray-400 cursor-not-allowed'
: 'bg-plex-orange text-gray-900 hover:bg-yellow-500 active:scale-[0.98]'
}`}
>
{isLoading ? (
<>
<Loader2 size={18} className="animate-spin" />
<span>{t('auth.loggingIn')}</span>
</>
) : (
<>
<span>{t('auth.loginBtn')}</span>
<ArrowRight size={18} />
</>
)}
</button>
</form>
<div className="mt-8 pt-6 border-t border-gray-700/50 text-center">
<p className="text-[10px] text-gray-600">© PMS Playlist Sync</p>
</div>
</div>
</div>
);
};
export default LoginScreen;
+11
View File
@@ -4,6 +4,17 @@ export const cht = {
manager: '管理',
footer: '© {year} PMS Playlist Sync。已連線至 Docker 後端。',
},
auth: {
title: '登入',
subtitle: '登入後管理播放清單同步',
username: '使用者名稱',
password: '密碼',
loginBtn: '登入',
logout: '登出',
loggingIn: '驗證中…',
invalidCredentials: '使用者名稱或密碼錯誤',
welcome: '歡迎,{user}',
},
common: {
save: '儲存',
cancel: '取消',
+11
View File
@@ -4,6 +4,17 @@ export const en = {
manager: 'Manager',
footer: '© {year} PMS Playlist Sync. Connected to Docker backend.',
},
auth: {
title: 'Login',
subtitle: 'Sign in to manage your playlist syncs',
username: 'Username',
password: 'Password',
loginBtn: 'Sign In',
logout: 'Logout',
loggingIn: 'Verifying...',
invalidCredentials: 'Invalid username or password',
welcome: 'Welcome, {user}',
},
common: {
save: 'Save',
cancel: 'Cancel',
+11
View File
@@ -4,6 +4,17 @@ export const es = {
manager: 'Gestor',
footer: '© {year} PMS Playlist Sync. Conectado al backend Docker.',
},
auth: {
title: 'Iniciar Sesión',
subtitle: 'Ingrese para gestionar sus sincronizaciones',
username: 'Usuario',
password: 'Password',
loginBtn: 'Entrar',
logout: 'Salir',
loggingIn: 'Verificando...',
invalidCredentials: 'Usuario o contraseña incorrectos',
welcome: 'Bienvenido, {user}',
},
common: {
save: 'Guardar',
cancel: 'Cancelar',
+11
View File
@@ -4,6 +4,17 @@ export const zh = {
manager: '管理',
footer: '© {year} PMS Playlist Sync。已连接到 Docker 后端。',
},
auth: {
title: '登录',
subtitle: '登录后管理播放列表同步',
username: '用户名',
password: '密码',
loginBtn: '登录',
logout: '登出',
loggingIn: '验证中...',
invalidCredentials: '用户名或密码错误',
welcome: '欢迎,{user}',
},
common: {
save: '保存',
cancel: '取消',
+58 -14
View File
@@ -1,7 +1,24 @@
import { Playlist, ServerType, ApiResponse, PlexServerConnection, PlexConnectionSettings, PlexLibrary, ReplacementRule, PathMappingConfig, PathMappingMode, PathMappingRules, SyncStrategy, ScheduleSettings, BackupSettings } from '../types';
import { Playlist, ServerType, ApiResponse, PlexServerConnection, PlexConnectionSettings, PlexLibrary, ReplacementRule, PathMappingConfig, PathMappingMode, PathMappingRules, SyncStrategy, ScheduleSettings, BackupSettings, LoginCredentials, AuthResponse } from '../types';
const API_BASE = import.meta.env.VITE_API_BASE_URL || '';
const getAuthToken = (): string | null => {
try {
return localStorage.getItem('plexsync-token');
} catch {
return null;
}
};
const authFetch = (input: RequestInfo | URL, init: RequestInit = {}) => {
const token = getAuthToken();
const headers = new Headers(init.headers || {});
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
return fetch(input, { ...init, headers });
};
const MODE_TO_STRATEGY: Record<string, SyncStrategy> = {
local_force: SyncStrategy.LOCAL_OVERWRITE,
remote_force: SyncStrategy.CLOUD_OVERWRITE,
@@ -20,6 +37,9 @@ const handleResponse = async <T>(response: Response): Promise<ApiResponse<T>> =>
try {
const data = await response.json();
if (!response.ok) {
if (response.status === 401) {
return { data: data as T, status: 'error', message: 'Unauthorized' };
}
return { data: data as T, status: 'error', message: (data as any)?.detail || response.statusText };
}
return { data, status: 'success' };
@@ -97,8 +117,32 @@ const pathMappingToApi = (config: PathMappingConfig) => {
};
export const apiService = {
async getAuthConfig(): Promise<ApiResponse<{ enabled: boolean }>> {
const response = await fetch(`${API_BASE}/api/auth/config`);
return handleResponse(response);
},
async login(creds: LoginCredentials): Promise<ApiResponse<AuthResponse>> {
const response = await fetch(`${API_BASE}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(creds),
});
return handleResponse(response);
},
async me(): Promise<ApiResponse<{ username: string }>> {
const response = await authFetch(`${API_BASE}/api/auth/me`);
return handleResponse(response);
},
async logout(): Promise<ApiResponse<{ status: string }>> {
const response = await authFetch(`${API_BASE}/api/auth/logout`, { method: 'POST' });
return handleResponse(response);
},
async getSettings(): Promise<ApiResponse<{ strategy: SyncStrategy; pathMapping: PathMappingConfig; connection: PlexConnectionSettings; localPath: string }>> {
const response = await fetch(`${API_BASE}/api/settings`);
const response = await authFetch(`${API_BASE}/api/settings`);
const result = await handleResponse<any>(response);
if (result.status === 'success') {
const mode = result.data.sync_mode as string;
@@ -118,7 +162,7 @@ export const apiService = {
async updateSyncStrategy(strategy: SyncStrategy): Promise<ApiResponse<{ sync_mode: string }>> {
const payload = { mode: STRATEGY_TO_MODE[strategy] };
const response = await fetch(`${API_BASE}/api/settings/sync-mode`, {
const response = await authFetch(`${API_BASE}/api/settings/sync-mode`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
@@ -128,7 +172,7 @@ export const apiService = {
async savePathMapping(config: PathMappingConfig): Promise<ApiResponse<null>> {
const payload = pathMappingToApi(config);
const response = await fetch(`${API_BASE}/api/settings/path-mapping`, {
const response = await authFetch(`${API_BASE}/api/settings/path-mapping`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
@@ -137,7 +181,7 @@ export const apiService = {
},
async updateLibrary(libraryName: string): Promise<ApiResponse<{ library_name: string }>> {
const response = await fetch(`${API_BASE}/api/settings/library`, {
const response = await authFetch(`${API_BASE}/api/settings/library`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ library_name: libraryName }),
@@ -146,12 +190,12 @@ export const apiService = {
},
async getScheduleSettings(): Promise<ApiResponse<ScheduleSettings & { nextRun?: string }>> {
const response = await fetch(`${API_BASE}/api/schedule`);
const response = await authFetch(`${API_BASE}/api/schedule`);
return handleResponse(response);
},
async saveScheduleSettings(settings: ScheduleSettings): Promise<ApiResponse<null>> {
const response = await fetch(`${API_BASE}/api/schedule`, {
const response = await authFetch(`${API_BASE}/api/schedule`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings),
@@ -164,7 +208,7 @@ export const apiService = {
if (serverType === ServerType.LOCAL && localPath) {
params.append('local_path', localPath);
}
const response = await fetch(`${API_BASE}/api/playlists?${params.toString()}`, { signal });
const response = await authFetch(`${API_BASE}/api/playlists?${params.toString()}`, { signal });
const result = await handleResponse<any>(response);
if (result.status === 'success' && (result.data as any)?.playlists) {
return { data: (result.data.playlists as any[]).map(mapPlaylist), status: 'success' };
@@ -173,7 +217,7 @@ export const apiService = {
},
async getServerStatus(signal?: AbortSignal): Promise<ApiResponse<PlexServerConnection>> {
const response = await fetch(`${API_BASE}/api/server`, { signal });
const response = await authFetch(`${API_BASE}/api/server`, { signal });
const result = await handleResponse<any>(response);
if (result.status === 'success') {
const info = result.data.serverInfo || {};
@@ -194,7 +238,7 @@ export const apiService = {
},
async connectToPlex(settings: PlexConnectionSettings, signal?: AbortSignal): Promise<ApiResponse<{ token: string; serverInfo: PlexServerConnection }>> {
const response = await fetch(`${API_BASE}/api/connect`, {
const response = await authFetch(`${API_BASE}/api/connect`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -219,7 +263,7 @@ export const apiService = {
},
async syncPlaylists(strategy: SyncStrategy, _pathMapping: PathMappingConfig, localPath?: string): Promise<ApiResponse<null>> {
const response = await fetch(`${API_BASE}/api/sync`, {
const response = await authFetch(`${API_BASE}/api/sync`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -231,12 +275,12 @@ export const apiService = {
},
async getSyncStatus(): Promise<ApiResponse<{ is_syncing: boolean; last_sync_time: string | null; status: string; error: string | null }>> {
const response = await fetch(`${API_BASE}/api/sync/status`);
const response = await authFetch(`${API_BASE}/api/sync/status`);
return handleResponse(response);
},
async getBackupSettings(): Promise<ApiResponse<BackupSettings>> {
const response = await fetch(`${API_BASE}/api/backup/settings`);
const response = await authFetch(`${API_BASE}/api/backup/settings`);
const result = await handleResponse<any>(response);
if (result.status === 'success') {
return {
@@ -251,7 +295,7 @@ export const apiService = {
},
async saveBackupSettings(settings: BackupSettings): Promise<ApiResponse<null>> {
const response = await fetch(`${API_BASE}/api/backup/settings`, {
const response = await authFetch(`${API_BASE}/api/backup/settings`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
+2 -1
View File
@@ -11,7 +11,8 @@
],
"skipLibCheck": true,
"types": [
"node"
"node",
"vite/client"
],
"moduleResolution": "bundler",
"isolatedModules": true,
+11
View File
@@ -115,4 +115,15 @@ export interface ApiResponse<T> {
data: T;
status: 'success' | 'error';
message?: string;
}
export interface LoginCredentials {
username: string;
password: string;
}
export interface AuthResponse {
token: string;
username: string;
expires_in?: number;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />