refacto: error and types

This commit is contained in:
Julien Froidefond
2025-02-27 21:59:14 +01:00
parent ea51ff53a9
commit 279f6c6e88
37 changed files with 800 additions and 684 deletions

View File

@@ -3,6 +3,7 @@ import { AuthServerService } from "@/lib/services/auth-server.service";
import { ERROR_CODES } from "@/constants/errorCodes";
import { AppError } from "@/utils/errors";
import { UserData } from "@/lib/services/auth-server.service";
import { getErrorMessage } from "@/utils/errors";
export async function POST(request: Request) {
try {
@@ -20,9 +21,7 @@ export async function POST(request: Request) {
if (error instanceof AppError) {
return NextResponse.json(
{
error: {
code: error.code,
},
error: AppError,
},
{ status: 401 }
);
@@ -35,7 +34,9 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.AUTH.INVALID_CREDENTIALS,
},
name: "Invalid credentials",
message: getErrorMessage(ERROR_CODES.AUTH.INVALID_CREDENTIALS),
} as AppError,
},
{ status: 500 }
);

View File

@@ -1,6 +1,8 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { ERROR_CODES } from "@/constants/errorCodes";
import { getErrorMessage } from "@/utils/errors";
import { AppErrorType } from "@/types/global";
export async function POST() {
try {
@@ -13,7 +15,9 @@ export async function POST() {
{
error: {
code: ERROR_CODES.AUTH.LOGOUT_ERROR,
},
name: "Logout error",
message: getErrorMessage(ERROR_CODES.AUTH.LOGOUT_ERROR),
} as AppErrorType,
},
{ status: 500 }
);

View File

@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { AuthServerService, UserData } from "@/lib/services/auth-server.service";
import { ERROR_CODES } from "@/constants/errorCodes";
import { AppError } from "@/utils/errors";
import { getErrorMessage } from "@/utils/errors";
export async function POST(request: Request) {
try {
@@ -24,9 +25,7 @@ export async function POST(request: Request) {
: 500;
return NextResponse.json(
{
error: {
code: error.code,
},
error: AppError,
},
{ status }
);
@@ -39,6 +38,8 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.AUTH.INVALID_USER_DATA,
name: "Invalid user data",
message: getErrorMessage(ERROR_CODES.AUTH.INVALID_USER_DATA),
},
},
{ status: 500 }

View File

@@ -15,8 +15,9 @@ export async function GET() {
{
error: {
code: error.code,
name: "Debug fetch error",
message: getErrorMessage(error.code),
},
} as AppError,
},
{ status: 500 }
);
@@ -25,8 +26,9 @@ export async function GET() {
{
error: {
code: ERROR_CODES.DEBUG.FETCH_ERROR,
name: "Debug fetch error",
message: getErrorMessage(ERROR_CODES.DEBUG.FETCH_ERROR),
},
} as AppError,
},
{ status: 500 }
);
@@ -47,8 +49,9 @@ export async function POST(request: NextRequest) {
{
error: {
code: error.code,
name: "Debug save error",
message: getErrorMessage(error.code),
},
} as AppError,
},
{ status: 500 }
);
@@ -57,8 +60,9 @@ export async function POST(request: NextRequest) {
{
error: {
code: ERROR_CODES.DEBUG.SAVE_ERROR,
name: "Debug save error",
message: getErrorMessage(ERROR_CODES.DEBUG.SAVE_ERROR),
},
} as AppError,
},
{ status: 500 }
);
@@ -78,8 +82,9 @@ export async function DELETE() {
{
error: {
code: error.code,
name: "Debug clear error",
message: getErrorMessage(error.code),
},
} as AppError,
},
{ status: 500 }
);
@@ -88,8 +93,9 @@ export async function DELETE() {
{
error: {
code: ERROR_CODES.DEBUG.CLEAR_ERROR,
name: "Debug clear error",
message: getErrorMessage(ERROR_CODES.DEBUG.CLEAR_ERROR),
},
} as AppError,
},
{ status: 500 }
);

View File

@@ -17,6 +17,7 @@ export async function GET(
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},
@@ -41,6 +42,7 @@ export async function GET(
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -51,6 +53,7 @@ export async function GET(
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -13,6 +13,7 @@ export async function PATCH(request: NextRequest, { params }: { params: { bookId
{
error: {
code: ERROR_CODES.BOOK.PROGRESS_UPDATE_ERROR,
name: "Progress update error",
message: getErrorMessage(ERROR_CODES.BOOK.PROGRESS_UPDATE_ERROR),
},
},
@@ -29,6 +30,7 @@ export async function PATCH(request: NextRequest, { params }: { params: { bookId
{
error: {
code: error.code,
name: "Progress update error",
message: getErrorMessage(error.code),
},
},
@@ -39,6 +41,7 @@ export async function PATCH(request: NextRequest, { params }: { params: { bookId
{
error: {
code: ERROR_CODES.BOOK.PROGRESS_UPDATE_ERROR,
name: "Progress update error",
message: getErrorMessage(ERROR_CODES.BOOK.PROGRESS_UPDATE_ERROR),
},
},
@@ -58,6 +61,7 @@ export async function DELETE(request: NextRequest, { params }: { params: { bookI
{
error: {
code: error.code,
name: "Progress delete error",
message: getErrorMessage(error.code),
},
},
@@ -68,6 +72,7 @@ export async function DELETE(request: NextRequest, { params }: { params: { bookI
{
error: {
code: ERROR_CODES.BOOK.PROGRESS_DELETE_ERROR,
name: "Progress delete error",
message: getErrorMessage(ERROR_CODES.BOOK.PROGRESS_DELETE_ERROR),
},
},

View File

@@ -15,8 +15,9 @@ export async function GET(request: Request, { params }: { params: { bookId: stri
{
error: {
code: error.code,
name: "Book fetch error",
message: getErrorMessage(error.code),
},
} as AppError,
},
{ status: 500 }
);
@@ -25,8 +26,9 @@ export async function GET(request: Request, { params }: { params: { bookId: stri
{
error: {
code: ERROR_CODES.BOOK.NOT_FOUND,
name: "Book fetch error",
message: getErrorMessage(ERROR_CODES.BOOK.NOT_FOUND),
},
} as AppError,
},
{ status: 500 }
);

View File

@@ -14,6 +14,7 @@ export async function POST() {
{
error: {
code: ERROR_CODES.CACHE.CLEAR_ERROR,
name: "Cache clear error",
message: getErrorMessage(ERROR_CODES.CACHE.CLEAR_ERROR),
},
},

View File

@@ -17,6 +17,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.CACHE.MODE_FETCH_ERROR,
name: "Cache mode fetch error",
message: getErrorMessage(ERROR_CODES.CACHE.MODE_FETCH_ERROR),
},
},
@@ -33,6 +34,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.CACHE.INVALID_MODE,
name: "Invalid cache mode",
message: getErrorMessage(ERROR_CODES.CACHE.INVALID_MODE),
},
},
@@ -49,6 +51,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.CACHE.MODE_UPDATE_ERROR,
name: "Cache mode update error",
message: getErrorMessage(ERROR_CODES.CACHE.MODE_UPDATE_ERROR),
},
},

View File

@@ -22,6 +22,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.MIDDLEWARE.UNAUTHORIZED,
name: "Unauthorized",
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED),
},
},
@@ -32,6 +33,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.CONFIG.SAVE_ERROR,
name: "Config save error",
message: getErrorMessage(ERROR_CODES.CONFIG.SAVE_ERROR),
},
},
@@ -53,6 +55,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.MIDDLEWARE.UNAUTHORIZED,
name: "Unauthorized",
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED),
},
},
@@ -64,6 +67,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.KOMGA.MISSING_CONFIG,
name: "Missing config",
message: getErrorMessage(ERROR_CODES.KOMGA.MISSING_CONFIG),
},
},
@@ -75,6 +79,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.CONFIG.FETCH_ERROR,
name: "Config fetch error",
message: getErrorMessage(ERROR_CODES.CONFIG.FETCH_ERROR),
},
},

View File

@@ -15,6 +15,7 @@ export async function GET() {
{
error: {
code: error.code,
name: "Favorite fetch error",
message: getErrorMessage(error.code),
},
},
@@ -25,6 +26,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.FAVORITE.FETCH_ERROR,
name: "Favorite fetch error",
message: getErrorMessage(ERROR_CODES.FAVORITE.FETCH_ERROR),
},
},
@@ -45,6 +47,7 @@ export async function POST(request: Request) {
{
error: {
code: error.code,
name: "Favorite add error",
message: getErrorMessage(error.code),
},
},
@@ -55,6 +58,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.FAVORITE.ADD_ERROR,
name: "Favorite add error",
message: getErrorMessage(ERROR_CODES.FAVORITE.ADD_ERROR),
},
},
@@ -75,6 +79,7 @@ export async function DELETE(request: Request) {
{
error: {
code: error.code,
name: "Favorite delete error",
message: getErrorMessage(error.code),
},
},
@@ -85,6 +90,7 @@ export async function DELETE(request: Request) {
{
error: {
code: ERROR_CODES.FAVORITE.DELETE_ERROR,
name: "Favorite delete error",
message: getErrorMessage(ERROR_CODES.FAVORITE.DELETE_ERROR),
},
},

View File

@@ -20,6 +20,7 @@ export async function GET(
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -30,6 +31,7 @@ export async function GET(
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -18,6 +18,7 @@ export async function GET(
{
error: {
code: ERROR_CODES.BOOK.PAGES_FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.BOOK.PAGES_FETCH_ERROR),
},
},
@@ -34,6 +35,7 @@ export async function GET(
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -44,6 +46,7 @@ export async function GET(
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -15,6 +15,7 @@ export async function GET(request: NextRequest, { params }: { params: { bookId:
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -25,6 +26,7 @@ export async function GET(request: NextRequest, { params }: { params: { bookId:
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -17,6 +17,7 @@ export async function GET(request: NextRequest, { params }: { params: { seriesId
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -27,6 +28,7 @@ export async function GET(request: NextRequest, { params }: { params: { seriesId
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -15,6 +15,7 @@ export async function GET(request: NextRequest, { params }: { params: { seriesId
{
error: {
code: error.code,
name: "Image fetch error",
message: getErrorMessage(error.code),
},
},
@@ -25,6 +26,7 @@ export async function GET(request: NextRequest, { params }: { params: { seriesId
{
error: {
code: ERROR_CODES.IMAGE.FETCH_ERROR,
name: "Image fetch error",
message: getErrorMessage(ERROR_CODES.IMAGE.FETCH_ERROR),
},
},

View File

@@ -17,6 +17,7 @@ export async function GET() {
{
error: {
code: error.code,
name: "Library fetch error",
message: getErrorMessage(error.code),
},
},
@@ -27,6 +28,7 @@ export async function GET() {
{
error: {
code: ERROR_CODES.LIBRARY.FETCH_ERROR,
name: "Library fetch error",
message: getErrorMessage(ERROR_CODES.LIBRARY.FETCH_ERROR),
},
},

View File

@@ -18,6 +18,7 @@ export async function GET(request: Request, { params }: { params: { seriesId: st
{
error: {
code: error.code,
name: "Series fetch error",
message: getErrorMessage(error.code),
},
},
@@ -28,6 +29,7 @@ export async function GET(request: Request, { params }: { params: { seriesId: st
{
error: {
code: ERROR_CODES.SERIES.FETCH_ERROR,
name: "Series fetch error",
message: getErrorMessage(ERROR_CODES.SERIES.FETCH_ERROR),
},
},

View File

@@ -25,6 +25,7 @@ export async function POST(request: Request) {
{
error: {
code: ERROR_CODES.KOMGA.CONNECTION_ERROR,
name: "Connection error",
message: getErrorMessage(ERROR_CODES.KOMGA.CONNECTION_ERROR),
},
},

View File

@@ -11,10 +11,11 @@ export async function GET() {
} catch (error) {
console.error("Erreur lors de la récupération de la configuration TTL:", error);
if (error instanceof Error) {
if (error.message === "Utilisateur non authentifié") {
if (error.message === getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED)) {
return NextResponse.json(
{
error: {
name: "Unauthorized",
code: ERROR_CODES.MIDDLEWARE.UNAUTHORIZED,
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED),
},
@@ -26,6 +27,7 @@ export async function GET() {
return NextResponse.json(
{
error: {
name: "TTL fetch error",
code: ERROR_CODES.CONFIG.TTL_FETCH_ERROR,
message: getErrorMessage(ERROR_CODES.CONFIG.TTL_FETCH_ERROR),
},
@@ -53,10 +55,14 @@ export async function POST(request: Request) {
});
} catch (error) {
console.error("Erreur lors de la sauvegarde de la configuration TTL:", error);
if (error instanceof Error && error.message === "Utilisateur non authentifié") {
if (
error instanceof Error &&
error.message === getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED)
) {
return NextResponse.json(
{
error: {
name: "Unauthorized",
code: ERROR_CODES.MIDDLEWARE.UNAUTHORIZED,
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED),
},
@@ -67,6 +73,7 @@ export async function POST(request: Request) {
return NextResponse.json(
{
error: {
name: "TTL save error",
code: ERROR_CODES.CONFIG.TTL_SAVE_ERROR,
message: getErrorMessage(ERROR_CODES.CONFIG.TTL_SAVE_ERROR),
},

View File

@@ -15,6 +15,7 @@ export async function GET() {
return NextResponse.json(
{
error: {
name: "Preferences fetch error",
code: error.code,
message: getErrorMessage(error.code),
},
@@ -25,6 +26,7 @@ export async function GET() {
return NextResponse.json(
{
error: {
name: "Preferences fetch error",
code: ERROR_CODES.PREFERENCES.FETCH_ERROR,
message: getErrorMessage(ERROR_CODES.PREFERENCES.FETCH_ERROR),
},
@@ -47,6 +49,7 @@ export async function PUT(request: NextRequest) {
return NextResponse.json(
{
error: {
name: "Preferences update error",
code: error.code,
message: getErrorMessage(error.code),
},
@@ -57,6 +60,7 @@ export async function PUT(request: NextRequest) {
return NextResponse.json(
{
error: {
name: "Preferences update error",
code: ERROR_CODES.PREFERENCES.UPDATE_ERROR,
message: getErrorMessage(ERROR_CODES.PREFERENCES.UPDATE_ERROR),
},

View File

@@ -8,7 +8,6 @@ import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { LibraryResponse } from "@/types/library";
import { KomgaSeries, KomgaLibrary } from "@/types/komga";
import { UserPreferences } from "@/types/preferences";
import { ERROR_CODES } from "@/constants/errorCodes";
interface PageProps {
params: { libraryId: string };
@@ -99,13 +98,13 @@ async function LibraryPage({ params, searchParams }: PageProps) {
<h1 className="text-3xl font-bold">Séries</h1>
<RefreshButton libraryId={params.libraryId} refreshLibrary={refreshLibrary} />
</div>
<ErrorMessage errorCode="SERIES_FETCH_ERROR" />
<ErrorMessage error={error as Error} errorCode="SERIES_FETCH_ERROR" />
</div>
);
}
return (
<div className="container py-8 space-y-8">
<ErrorMessage errorCode="SERIES_FETCH_ERROR" />
<ErrorMessage error={error as Error} errorCode="SERIES_FETCH_ERROR" />
</div>
);
}

View File

@@ -5,7 +5,7 @@ import { revalidatePath } from "next/cache";
import { withPageTiming } from "@/lib/hoc/withPageTiming";
import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { HomeData } from "@/lib/services/home.service";
import { ERROR_CODES } from "@/constants/errorCodes";
async function refreshHome() {
"use server";
@@ -32,7 +32,7 @@ async function HomePage() {
return (
<main className="container mx-auto px-4 py-8">
<ErrorMessage errorCode="HOME_FETCH_ERROR" />
<ErrorMessage error={error as Error} errorCode="HOME_FETCH_ERROR" />
</main>
);
}

View File

@@ -78,7 +78,7 @@ async function SeriesPage({ params, searchParams }: PageProps) {
return (
<div className="container py-8 space-y-8">
<h1 className="text-3xl font-bold">Série</h1>
<ErrorMessage errorCode="SERIES_FETCH_ERROR" />
<ErrorMessage error={error as Error} errorCode="SERIES_FETCH_ERROR" />
</div>
);
}

View File

@@ -3,7 +3,7 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { authService } from "@/lib/services/auth.service";
import { AuthError } from "@/types/auth";
import { AppErrorType } from "@/types/global";
import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { useTranslate } from "@/hooks/useTranslate";
@@ -14,7 +14,7 @@ interface LoginFormProps {
export function LoginForm({ from }: LoginFormProps) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<AuthError | null>(null);
const [error, setError] = useState<AppErrorType | null>(null);
const { t } = useTranslate();
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
@@ -32,7 +32,7 @@ export function LoginForm({ from }: LoginFormProps) {
router.push(from || "/");
router.refresh();
} catch (error) {
setError(error as AuthError);
setError(error as AppErrorType);
} finally {
setIsLoading(false);
}
@@ -89,7 +89,7 @@ export function LoginForm({ from }: LoginFormProps) {
{t("login.form.remember")}
</label>
</div>
{error && <ErrorMessage errorCode={error.code} variant="form" />}
{error && <ErrorMessage error={error as Error} errorCode={error.code} variant="form" />}
<button
type="submit"
disabled={isLoading}

View File

@@ -3,10 +3,11 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { authService } from "@/lib/services/auth.service";
import { AuthError } from "@/types/auth";
import { AppErrorType } from "@/types/global";
import { ERROR_CODES } from "@/constants/errorCodes";
import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { useTranslate } from "@/hooks/useTranslate";
import { getErrorMessage } from "@/utils/errors";
interface RegisterFormProps {
from?: string;
@@ -15,7 +16,7 @@ interface RegisterFormProps {
export function RegisterForm({ from }: RegisterFormProps) {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<AuthError | null>(null);
const [error, setError] = useState<AppErrorType | null>(null);
const { t } = useTranslate();
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
@@ -31,6 +32,8 @@ export function RegisterForm({ from }: RegisterFormProps) {
if (password !== confirmPassword) {
setError({
code: ERROR_CODES.AUTH.PASSWORD_MISMATCH,
name: "Password mismatch",
message: getErrorMessage(ERROR_CODES.AUTH.PASSWORD_MISMATCH),
});
setIsLoading(false);
return;
@@ -41,7 +44,7 @@ export function RegisterForm({ from }: RegisterFormProps) {
router.push(from || "/");
router.refresh();
} catch (error) {
setError(error as AuthError);
setError(error as AppErrorType);
} finally {
setIsLoading(false);
}
@@ -97,7 +100,7 @@ export function RegisterForm({ from }: RegisterFormProps) {
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
{error && <ErrorMessage errorCode={error.code} variant="form" />}
{error && <ErrorMessage error={error as Error} errorCode={error.code} variant="form" />}
<button
type="submit"
disabled={isLoading}

View File

@@ -0,0 +1,232 @@
"use client";
import { useState } from "react";
import { useTranslate } from "@/hooks/useTranslate";
import { useToast } from "@/components/ui/use-toast";
import { Trash2, Loader2 } from "lucide-react";
import { CacheModeSwitch } from "@/components/settings/CacheModeSwitch";
import { Label } from "@/components/ui/label";
import { TTLConfigData } from "@/types/komga";
interface CacheSettingsProps {
initialTTLConfig: TTLConfigData | null;
}
export function CacheSettings({ initialTTLConfig }: CacheSettingsProps) {
const { t } = useTranslate();
const { toast } = useToast();
const [isCacheClearing, setIsCacheClearing] = useState(false);
const [ttlConfig, setTTLConfig] = useState<TTLConfigData>(
initialTTLConfig || {
defaultTTL: 5,
homeTTL: 5,
librariesTTL: 1440,
seriesTTL: 5,
booksTTL: 5,
imagesTTL: 1440,
}
);
const handleClearCache = async () => {
setIsCacheClearing(true);
try {
const response = await fetch("/api/komga/cache/clear", {
method: "POST",
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || t("settings.cache.error.message"));
}
toast({
title: t("settings.cache.title"),
description: t("settings.cache.messages.cleared"),
});
} catch (error) {
console.error("Erreur:", error);
toast({
variant: "destructive",
title: t("settings.cache.error.title"),
description: t("settings.cache.error.message"),
});
} finally {
setIsCacheClearing(false);
}
};
const handleTTLChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setTTLConfig((prev) => ({
...prev,
[name]: parseInt(value || "0", 10),
}));
};
const handleSaveTTL = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const response = await fetch("/api/komga/ttl-config", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(ttlConfig),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || t("settings.cache.error.message"));
}
toast({
title: t("settings.cache.title"),
description: t("settings.cache.messages.ttlSaved"),
});
} catch (error) {
console.error("Erreur lors de la sauvegarde:", error);
toast({
variant: "destructive",
title: t("settings.cache.error.title"),
description: t("settings.cache.error.messagettl"),
});
}
};
return (
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
<Trash2 className="h-5 w-5" />
{t("settings.cache.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">{t("settings.cache.description")}</p>
</div>
<div className="flex items-center justify-between mb-4">
<div className="space-y-0.5">
<Label htmlFor="cache-mode">{t("settings.cache.mode.label")}</Label>
<p className="text-sm text-muted-foreground">{t("settings.cache.mode.description")}</p>
</div>
<CacheModeSwitch />
</div>
{/* Formulaire TTL */}
<form onSubmit={handleSaveTTL} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-2">
<label htmlFor="defaultTTL" className="text-sm font-medium">
{t("settings.cache.ttl.default")}
</label>
<input
type="number"
id="defaultTTL"
name="defaultTTL"
min="1"
value={ttlConfig.defaultTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="homeTTL" className="text-sm font-medium">
{t("settings.cache.ttl.home")}
</label>
<input
type="number"
id="homeTTL"
name="homeTTL"
min="1"
value={ttlConfig.homeTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="librariesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.libraries")}
</label>
<input
type="number"
id="librariesTTL"
name="librariesTTL"
min="1"
value={ttlConfig.librariesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="seriesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.series")}
</label>
<input
type="number"
id="seriesTTL"
name="seriesTTL"
min="1"
value={ttlConfig.seriesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="booksTTL" className="text-sm font-medium">
{t("settings.cache.ttl.books")}
</label>
<input
type="number"
id="booksTTL"
name="booksTTL"
min="1"
value={ttlConfig.booksTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="imagesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.images")}
</label>
<input
type="number"
id="imagesTTL"
name="imagesTTL"
min="1"
value={ttlConfig.imagesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="flex gap-3">
<button
type="submit"
className="flex-1 inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{t("settings.cache.buttons.saveTTL")}
</button>
<button
type="button"
onClick={handleClearCache}
disabled={isCacheClearing}
className="flex-1 inline-flex items-center justify-center rounded-md bg-destructive px-3 py-2 text-sm font-medium text-destructive-foreground ring-offset-background transition-colors hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isCacheClearing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.cache.buttons.clearing")}
</>
) : (
t("settings.cache.buttons.clear")
)}
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -1,16 +1,10 @@
"use client";
import { useState } from "react";
import { Loader2, Network, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { AuthError } from "@/types/auth";
import { useToast } from "@/components/ui/use-toast";
import { usePreferences } from "@/contexts/PreferencesContext";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { CacheModeSwitch } from "@/components/settings/CacheModeSwitch";
import { KomgaConfig, TTLConfigData } from "@/types/komga";
import { useTranslate } from "@/hooks/useTranslate";
import { DisplaySettings } from "./DisplaySettings";
import { KomgaSettings } from "./KomgaSettings";
import { CacheSettings } from "./CacheSettings";
interface ClientSettingsProps {
initialConfig: KomgaConfig | null;
@@ -19,633 +13,14 @@ interface ClientSettingsProps {
export function ClientSettings({ initialConfig, initialTTLConfig }: ClientSettingsProps) {
const { t } = useTranslate();
const router = useRouter();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [isCacheClearing, setIsCacheClearing] = useState(false);
const [error, setError] = useState<AuthError | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [config, setConfig] = useState({
serverUrl: initialConfig?.url || "",
username: initialConfig?.username || "",
password: initialConfig?.password || "",
authHeader: initialConfig?.authHeader || "",
});
const [isEditingConfig, setIsEditingConfig] = useState(false);
const [localInitialConfig, setLocalInitialConfig] = useState(initialConfig);
const [ttlConfig, setTTLConfig] = useState<TTLConfigData>(
initialTTLConfig || {
defaultTTL: 5,
homeTTL: 5,
librariesTTL: 1440,
seriesTTL: 5,
booksTTL: 5,
imagesTTL: 1440,
}
);
const { preferences, updatePreferences } = usePreferences();
const hasToShowEditForm =
localInitialConfig && config.serverUrl !== null && config.username !== null;
const shouldShowForm = !hasToShowEditForm || isEditingConfig;
const handleClearCache = async () => {
setIsCacheClearing(true);
setError(null);
setSuccess(null);
try {
const response = await fetch("/api/komga/cache/clear", {
method: "POST",
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la suppression du cache");
}
toast({
title: t("settings.cache.title"),
description: t("settings.cache.messages.cleared"),
});
router.refresh();
} catch (error) {
console.error("Erreur:", error);
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsCacheClearing(false);
}
};
const handleTest = async () => {
setIsLoading(true);
setError(null);
setSuccess(null);
const form = document.querySelector("form") as HTMLFormElement;
const formData = new FormData(form);
const serverUrl = formData.get("serverUrl") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string;
try {
const response = await fetch("/api/komga/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
serverUrl: serverUrl.trim(),
username,
password: password || config.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors du test de connexion");
}
toast({
title: t("settings.komga.title"),
description: t("settings.komga.messages.connectionSuccess"),
});
} catch (error) {
console.error("Erreur:", error);
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
setError(null);
setIsSaving(true);
const formData = new FormData(event.currentTarget);
const serverUrl = formData.get("serverUrl") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string;
const newConfig = {
serverUrl: serverUrl.trim(),
username,
password,
authHeader: config.authHeader,
};
try {
const response = await fetch("/api/komga/config", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
url: newConfig.serverUrl,
username: newConfig.username,
password: newConfig.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la sauvegarde de la configuration");
}
const savedConfig = await response.json();
setConfig(newConfig);
setLocalInitialConfig({
url: newConfig.serverUrl,
username: newConfig.username,
userId: savedConfig.userId,
authHeader: savedConfig.authHeader,
});
setIsEditingConfig(false);
toast({
title: t("settings.komga.title"),
description: t("settings.komga.messages.configSaved"),
});
// Forcer un rechargement complet de la page
window.location.reload();
} catch (error) {
console.error("Erreur lors de la sauvegarde:", error);
toast({
variant: "destructive",
title: "Erreur",
description:
error instanceof Error ? error.message : "Une erreur est survenue lors de la sauvegarde",
});
} finally {
setIsSaving(false);
}
};
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setConfig((prev) => ({
...prev,
[name]: value,
}));
};
const handleTTLChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setTTLConfig((prev) => ({
...prev,
[name]: parseInt(value || "0", 10),
}));
};
const handleSaveTTL = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
try {
const response = await fetch("/api/komga/ttl-config", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(ttlConfig),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la sauvegarde de la configuration TTL");
}
toast({
title: t("settings.cache.title"),
description: t("settings.cache.messages.ttlSaved"),
});
} catch (error) {
console.error("Erreur lors de la sauvegarde:", error);
toast({
variant: "destructive",
title: "Erreur",
description:
error instanceof Error ? error.message : "Une erreur est survenue lors de la sauvegarde",
});
}
};
const handleToggleThumbnails = async (checked: boolean) => {
try {
await updatePreferences({ showThumbnails: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description:
error instanceof Error
? error.message
: "Une erreur est survenue lors de la mise à jour des préférences",
});
}
};
return (
<div className="container max-w-3xl mx-auto py-8 space-y-6">
<div className="flex items-center justify-between">
<div className="container mx-auto px-4 py-8 space-y-8">
<h1 className="text-3xl font-bold">{t("settings.title")}</h1>
</div>
{/* Messages de succès/erreur */}
{error && (
<div className="rounded-md bg-destructive/15 p-4">
<p className="text-sm text-destructive">{t(`errors.${error.code}`)}</p>
</div>
)}
{success && (
<div className="rounded-md bg-green-500/15 p-4">
<p className="text-sm text-green-500">{success}</p>
</div>
)}
<div className="grid gap-6">
{/* Section Préférences d'affichage */}
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
{t("settings.display.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{t("settings.display.description")}
</p>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="thumbnails">{t("settings.display.thumbnails.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.thumbnails.description")}
</p>
</div>
<Switch
id="thumbnails"
checked={preferences.showThumbnails}
onCheckedChange={handleToggleThumbnails}
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="unread-filter">{t("settings.display.unreadFilter.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.unreadFilter.description")}
</p>
</div>
<Switch
id="unread-filter"
checked={preferences.showOnlyUnread}
onCheckedChange={async (checked) => {
try {
await updatePreferences({ showOnlyUnread: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
console.error("Erreur détaillée:", error);
toast({
variant: "destructive",
title: "Erreur",
description:
error instanceof Error
? error.message
: "Une erreur est survenue lors de la mise à jour des préférences",
});
}
}}
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="debug-mode">{t("settings.display.debugMode.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.debugMode.description")}
</p>
</div>
<Switch
id="debug-mode"
checked={preferences.debug}
onCheckedChange={async (checked) => {
try {
await updatePreferences({ debug: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
console.error("Erreur détaillée:", error);
toast({
variant: "destructive",
title: "Erreur",
description:
error instanceof Error
? error.message
: "Une erreur est survenue lors de la mise à jour des préférences",
});
}
}}
/>
</div>
</div>
</div>
</div>
{/* Section Configuration Komga */}
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
<Network className="h-5 w-5" />
{t("settings.komga.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{t("settings.komga.description")}
</p>
</div>
{!shouldShowForm ? (
<div className="space-y-4">
<div className="space-y-3">
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.serverUrl")}</label>
<p className="text-sm text-muted-foreground">{config.serverUrl}</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.email")}</label>
<p className="text-sm text-muted-foreground">{config.username}</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.password")}</label>
<p className="text-sm text-muted-foreground"></p>
</div>
</div>
<button
type="button"
onClick={() => setIsEditingConfig(true)}
className="inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{t("settings.komga.buttons.edit")}
</button>
</div>
) : (
<form onSubmit={handleSave} className="space-y-4">
<div className="space-y-3">
<div className="space-y-2">
<label htmlFor="serverUrl" className="text-sm font-medium">
{t("settings.komga.serverUrl")}
</label>
<input
type="url"
id="serverUrl"
name="serverUrl"
required
value={config.serverUrl}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="username" className="text-sm font-medium">
{t("settings.komga.email")}
</label>
<input
type="text"
id="username"
name="username"
required
value={config.username}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="password" className="text-sm font-medium">
{t("settings.komga.password")}
</label>
<input
type="password"
id="password"
name="password"
required
value={config.password}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="flex gap-3">
<button
type="submit"
disabled={isSaving}
className="flex-1 inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.komga.buttons.saving")}
</>
) : (
t("settings.komga.buttons.save")
)}
</button>
<button
type="button"
onClick={handleTest}
disabled={isLoading}
className="flex-1 inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.komga.buttons.testing")}
</>
) : (
t("settings.komga.buttons.test")
)}
</button>
{initialConfig && (
<button
type="button"
onClick={() => {
setIsEditingConfig(false);
setConfig({
serverUrl: initialConfig.url,
username: initialConfig.username,
password: "",
authHeader: initialConfig.authHeader,
});
}}
className="flex-1 inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{t("settings.komga.buttons.cancel")}
</button>
)}
</div>
</form>
)}
</div>
</div>
{/* Section Configuration du Cache */}
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
<Trash2 className="h-5 w-5" />
{t("settings.cache.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">
{t("settings.cache.description")}
</p>
</div>
<div className="flex items-center justify-between mb-4">
<div className="space-y-0.5">
<Label htmlFor="cache-mode">{t("settings.cache.mode.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.cache.mode.description")}
</p>
</div>
<CacheModeSwitch />
</div>
{/* Formulaire TTL */}
<form onSubmit={handleSaveTTL} className="space-y-4">
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-2">
<label htmlFor="defaultTTL" className="text-sm font-medium">
{t("settings.cache.ttl.default")}
</label>
<input
type="number"
id="defaultTTL"
name="defaultTTL"
min="1"
value={ttlConfig.defaultTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="homeTTL" className="text-sm font-medium">
{t("settings.cache.ttl.home")}
</label>
<input
type="number"
id="homeTTL"
name="homeTTL"
min="1"
value={ttlConfig.homeTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="librariesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.libraries")}
</label>
<input
type="number"
id="librariesTTL"
name="librariesTTL"
min="1"
value={ttlConfig.librariesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="seriesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.series")}
</label>
<input
type="number"
id="seriesTTL"
name="seriesTTL"
min="1"
value={ttlConfig.seriesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="booksTTL" className="text-sm font-medium">
{t("settings.cache.ttl.books")}
</label>
<input
type="number"
id="booksTTL"
name="booksTTL"
min="1"
value={ttlConfig.booksTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="imagesTTL" className="text-sm font-medium">
{t("settings.cache.ttl.images")}
</label>
<input
type="number"
id="imagesTTL"
name="imagesTTL"
min="1"
value={ttlConfig.imagesTTL}
onChange={handleTTLChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="flex gap-3">
<button
type="submit"
className="flex-1 inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{t("settings.cache.buttons.saveTTL")}
</button>
<button
type="button"
onClick={handleClearCache}
disabled={isCacheClearing}
className="flex-1 inline-flex items-center justify-center rounded-md bg-destructive px-3 py-2 text-sm font-medium text-destructive-foreground ring-offset-background transition-colors hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isCacheClearing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.cache.buttons.clearing")}
</>
) : (
t("settings.cache.buttons.clear")
)}
</button>
</div>
</form>
</div>
</div>
<div className="space-y-8">
<DisplaySettings />
<KomgaSettings initialConfig={initialConfig} />
<CacheSettings initialTTLConfig={initialTTLConfig} />
</div>
</div>
);

View File

@@ -0,0 +1,113 @@
import { useTranslate } from "@/hooks/useTranslate";
import { usePreferences } from "@/contexts/PreferencesContext";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
export function DisplaySettings() {
const { t } = useTranslate();
const { toast } = useToast();
const { preferences, updatePreferences } = usePreferences();
const handleToggleThumbnails = async (checked: boolean) => {
try {
await updatePreferences({ showThumbnails: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
console.error("Erreur détaillée:", error);
toast({
variant: "destructive",
title: t("settings.error.title"),
description: t("settings.error.message"),
});
}
};
return (
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
{t("settings.display.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">{t("settings.display.description")}</p>
</div>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="thumbnails">{t("settings.display.thumbnails.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.thumbnails.description")}
</p>
</div>
<Switch
id="thumbnails"
checked={preferences.showThumbnails}
onCheckedChange={handleToggleThumbnails}
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="unread-filter">{t("settings.display.unreadFilter.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.unreadFilter.description")}
</p>
</div>
<Switch
id="unread-filter"
checked={preferences.showOnlyUnread}
onCheckedChange={async (checked) => {
try {
await updatePreferences({ showOnlyUnread: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
console.error("Erreur détaillée:", error);
toast({
variant: "destructive",
title: t("settings.error.title"),
description: t("settings.error.message"),
});
}
}}
/>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="debug-mode">{t("settings.display.debugMode.label")}</Label>
<p className="text-sm text-muted-foreground">
{t("settings.display.debugMode.description")}
</p>
</div>
<Switch
id="debug-mode"
checked={preferences.debug}
onCheckedChange={async (checked) => {
try {
await updatePreferences({ debug: checked });
toast({
title: t("settings.title"),
description: t("settings.komga.messages.configSaved"),
});
} catch (error) {
console.error("Erreur détaillée:", error);
toast({
variant: "destructive",
title: t("settings.error.title"),
description: t("settings.error.message"),
});
}
}}
/>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,280 @@
"use client";
import { useState } from "react";
import { useTranslate } from "@/hooks/useTranslate";
import { useToast } from "@/components/ui/use-toast";
import { Network, Loader2 } from "lucide-react";
import { KomgaConfig } from "@/types/komga";
interface KomgaSettingsProps {
initialConfig: KomgaConfig | null;
}
export function KomgaSettings({ initialConfig }: KomgaSettingsProps) {
const { t } = useTranslate();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [config, setConfig] = useState({
serverUrl: initialConfig?.url || "",
username: initialConfig?.username || "",
password: initialConfig?.password || "",
authHeader: initialConfig?.authHeader || "",
});
const [isEditingConfig, setIsEditingConfig] = useState(false);
const [localInitialConfig, setLocalInitialConfig] = useState(initialConfig);
const hasToShowEditForm =
localInitialConfig && config.serverUrl !== null && config.username !== null;
const shouldShowForm = !hasToShowEditForm || isEditingConfig;
const handleTest = async () => {
setIsLoading(true);
const form = document.querySelector("form") as HTMLFormElement;
const formData = new FormData(form);
const serverUrl = formData.get("serverUrl") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string;
try {
const response = await fetch("/api/komga/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
serverUrl: serverUrl.trim(),
username,
password: password || config.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || t("settings.komga.error.message"));
}
toast({
title: t("settings.komga.title"),
description: t("settings.komga.messages.connectionSuccess"),
});
} catch (error) {
console.error("Erreur:", error);
toast({
variant: "destructive",
title: t("settings.komga.error.title"),
description: t("settings.komga.error.message"),
});
} finally {
setIsLoading(false);
}
};
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setIsSaving(true);
const formData = new FormData(event.currentTarget);
const serverUrl = formData.get("serverUrl") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string;
const newConfig = {
serverUrl: serverUrl.trim(),
username,
password,
authHeader: config.authHeader,
};
try {
const response = await fetch("/api/komga/config", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
url: newConfig.serverUrl,
username: newConfig.username,
password: newConfig.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || t("settings.komga.error.message"));
}
const savedConfig = await response.json();
setConfig(newConfig);
setLocalInitialConfig({
url: newConfig.serverUrl,
username: newConfig.username,
userId: savedConfig.userId,
authHeader: savedConfig.authHeader,
});
setIsEditingConfig(false);
toast({
title: t("settings.komga.title"),
description: t("settings.komga.messages.configSaved"),
});
// Forcer un rechargement complet de la page
window.location.reload();
} catch (error) {
console.error("Erreur lors de la sauvegarde:", error);
toast({
variant: "destructive",
title: t("settings.komga.error.title"),
description: t("settings.komga.error.message"),
});
} finally {
setIsSaving(false);
}
};
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setConfig((prev) => ({
...prev,
[name]: value,
}));
};
return (
<div className="rounded-lg border bg-card text-card-foreground shadow-sm">
<div className="p-5 space-y-4">
<div>
<h2 className="text-xl font-semibold flex items-center gap-2">
<Network className="h-5 w-5" />
{t("settings.komga.title")}
</h2>
<p className="text-sm text-muted-foreground mt-1">{t("settings.komga.description")}</p>
</div>
{!shouldShowForm ? (
<div className="space-y-4">
<div className="space-y-3">
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.serverUrl")}</label>
<p className="text-sm text-muted-foreground">{config.serverUrl}</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.email")}</label>
<p className="text-sm text-muted-foreground">{config.username}</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">{t("settings.komga.password")}</label>
<p className="text-sm text-muted-foreground"></p>
</div>
</div>
<button
type="button"
onClick={() => setIsEditingConfig(true)}
className="inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{t("settings.komga.buttons.edit")}
</button>
</div>
) : (
<form onSubmit={handleSave} className="space-y-4">
<div className="space-y-3">
<div className="space-y-2">
<label htmlFor="serverUrl" className="text-sm font-medium">
{t("settings.komga.serverUrl")}
</label>
<input
type="url"
id="serverUrl"
name="serverUrl"
required
value={config.serverUrl}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="username" className="text-sm font-medium">
{t("settings.komga.email")}
</label>
<input
type="text"
id="username"
name="username"
required
value={config.username}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
<div className="space-y-2">
<label htmlFor="password" className="text-sm font-medium">
{t("settings.komga.password")}
</label>
<input
type="password"
id="password"
name="password"
required
value={config.password}
onChange={handleInputChange}
className="flex h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="flex gap-3">
<button
type="submit"
disabled={isSaving}
className="flex-1 inline-flex items-center justify-center rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.komga.buttons.saving")}
</>
) : (
t("settings.komga.buttons.save")
)}
</button>
<button
type="button"
onClick={handleTest}
disabled={isLoading}
className="flex-1 inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t("settings.komga.buttons.testing")}
</>
) : (
t("settings.komga.buttons.test")
)}
</button>
{initialConfig && (
<button
type="button"
onClick={() => {
setIsEditingConfig(false);
setConfig({
serverUrl: initialConfig.url,
username: initialConfig.username,
password: "",
authHeader: initialConfig.authHeader,
});
}}
className="flex-1 inline-flex items-center justify-center rounded-md bg-secondary px-3 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{t("settings.komga.buttons.cancel")}
</button>
)}
</div>
</form>
)}
</div>
</div>
);
}

View File

@@ -5,13 +5,16 @@ import { useTranslate } from "@/hooks/useTranslate";
interface ErrorMessageProps {
errorCode: string;
error?: Error;
variant?: "default" | "form";
}
export const ErrorMessage = ({ errorCode, variant = "default" }: ErrorMessageProps) => {
export const ErrorMessage = ({ errorCode, error, variant = "default" }: ErrorMessageProps) => {
const { t } = useTranslate();
const message = t(`errors.${errorCode}`);
console.error(error);
if (variant === "form") {
return (
<div

View File

@@ -81,6 +81,10 @@
"description": "Show debug information in the interface"
}
},
"error": {
"title": "Error",
"message": "An error occurred while updating preferences"
},
"komga": {
"title": "Komga Configuration",
"description": "Configure your Komga server connection information.",
@@ -98,6 +102,10 @@
"messages": {
"connectionSuccess": "Successfully connected to Komga server",
"configSaved": "Configuration saved successfully"
},
"error": {
"title": "Error saving configuration",
"message": "An error occurred while saving the configuration"
}
},
"cache": {
@@ -123,6 +131,11 @@
"messages": {
"ttlSaved": "TTL configuration saved successfully",
"cleared": "Server cache cleared successfully"
},
"error": {
"title": "Error clearing server cache",
"message": "An error occurred while clearing the server cache",
"ttl": "Error saving TTL configuration"
}
}
},
@@ -241,6 +254,8 @@
"AUTH_LOGOUT_ERROR": "Logout error",
"AUTH_INVALID_USER_DATA": "Invalid user data",
"AUTH_UNAUTHENTICATED": "Unauthenticated",
"AUTH_LOGIN_ERROR": "Login error",
"AUTH_REGISTER_ERROR": "Register error",
"SERIES_FETCH_ERROR": "Error fetching series",
"HOME_FETCH_ERROR": "Error fetching home",

View File

@@ -81,6 +81,10 @@
"description": "Afficher les informations de debug dans l'interface"
}
},
"error": {
"title": "Erreur",
"message": "Une erreur est survenue lors de la mise à jour des préférences"
},
"komga": {
"title": "Configuration Komga",
"description": "Configurez les informations de connexion à votre serveur Komga.",
@@ -98,6 +102,10 @@
"messages": {
"connectionSuccess": "La connexion au serveur Komga a été établie avec succès",
"configSaved": "La configuration a été sauvegardée avec succès"
},
"error": {
"title": "Erreur lors de la sauvegarde de la configuration",
"message": "Une erreur est survenue lors de la sauvegarde de la configuration"
}
},
"cache": {
@@ -123,6 +131,11 @@
"messages": {
"ttlSaved": "La configuration des TTL a été sauvegardée avec succès",
"cleared": "Cache serveur supprimé avec succès"
},
"error": {
"title": "Erreur lors de la suppression du cache",
"message": "Une erreur est survenue lors de la suppression du cache",
"ttl": "Erreur lors de la sauvegarde de la configuration TTL"
}
}
},
@@ -241,6 +254,8 @@
"AUTH_LOGOUT_ERROR": "Erreur lors de la déconnexion",
"AUTH_INVALID_USER_DATA": "Données utilisateur invalides",
"AUTH_UNAUTHENTICATED": "Non authentifié",
"AUTH_LOGIN_ERROR": "Erreur lors de la connexion",
"AUTH_REGISTER_ERROR": "Erreur lors de l'inscription",
"SERIES_FETCH_ERROR": "Erreur lors de la récupération des séries",
"HOME_FETCH_ERROR": "Erreur lors de la récupération de l'accueil",

View File

@@ -1,6 +1,6 @@
"use client";
import { AuthError } from "@/types/auth";
import { AppErrorType } from "@/types/global";
import { ERROR_CODES } from "@/constants/errorCodes";
class AuthService {
@@ -36,12 +36,14 @@ class AuthService {
throw data.error;
}
} catch (error) {
if ((error as AuthError).code) {
if ((error as AppErrorType).code) {
throw error;
}
throw {
code: ERROR_CODES.AUTH.INVALID_CREDENTIALS,
} as AuthError;
name: "Invalid credentials",
message: "The email or password is incorrect",
} as AppErrorType;
}
}
@@ -63,12 +65,14 @@ class AuthService {
throw data.error;
}
} catch (error) {
if ((error as AuthError).code) {
if ((error as AppErrorType).code) {
throw error;
}
throw {
code: ERROR_CODES.AUTH.INVALID_USER_DATA,
} as AuthError;
name: "Invalid user data",
message: "The email or password is incorrect",
} as AppErrorType;
}
}
@@ -86,12 +90,14 @@ class AuthService {
throw data.error;
}
} catch (error) {
if ((error as AuthError).code) {
if ((error as AppErrorType).code) {
throw error;
}
throw {
code: ERROR_CODES.AUTH.LOGOUT_ERROR,
} as AuthError;
name: "Logout error",
message: "The logout failed",
} as AppErrorType;
}
}
}

View File

@@ -57,7 +57,13 @@ export function middleware(request: NextRequest) {
if (!user || !user.value) {
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ error: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED) },
{
error: {
code: ERROR_CODES.MIDDLEWARE.UNAUTHORIZED,
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.UNAUTHORIZED),
name: "Unauthorized",
},
},
{ status: 401 }
);
}
@@ -75,7 +81,13 @@ export function middleware(request: NextRequest) {
console.error("Erreur de validation du cookie:", error);
if (pathname.startsWith("/api/")) {
return NextResponse.json(
{ error: getErrorMessage(ERROR_CODES.MIDDLEWARE.INVALID_TOKEN) },
{
error: {
code: ERROR_CODES.MIDDLEWARE.INVALID_TOKEN,
message: getErrorMessage(ERROR_CODES.MIDDLEWARE.INVALID_TOKEN),
name: "Invalid token",
},
},
{ status: 401 }
);
}

View File

@@ -1,5 +1,4 @@
import { KomgaUser } from "./komga";
import { ErrorCode } from "@/constants/errorCodes";
export interface AuthConfig {
serverUrl: string;
@@ -11,10 +10,3 @@ export interface AuthState {
user: KomgaUser | null;
serverUrl: string | null;
}
export interface AuthError {
code: ErrorCode;
}
// Deprecated - Use ErrorCode from @/constants/errorCodes instead
export type AuthErrorCode = ErrorCode;

7
src/types/global.d.ts vendored Normal file
View File

@@ -0,0 +1,7 @@
import { ErrorCode } from "@/constants/errorCodes";
export interface AppErrorType extends Error {
code: ErrorCode;
message: string;
name: string;
}