feat(db): init mongo and passing komga conf

This commit is contained in:
Julien Froidefond
2025-02-14 14:23:30 +01:00
parent 08f6e6a264
commit 1f881ade26
11 changed files with 1047 additions and 446 deletions

View File

@@ -1,16 +1,57 @@
import { NextResponse } from "next/server";
import { ConfigDBService } from "@/lib/services/config-db.service";
export async function POST(request: Request) {
try {
const data = await request.json();
console.log("Configuration Komga reçue:", data);
return NextResponse.json({ message: "Configuration reçue avec succès" }, { status: 200 });
} catch (error) {
console.error("Erreur lors de la réception de la configuration:", error);
const mongoConfig = await ConfigDBService.saveConfig(data);
// Convertir le document Mongoose en objet simple
const config = {
url: mongoConfig.url,
username: mongoConfig.username,
password: mongoConfig.password,
userId: mongoConfig.userId,
};
return NextResponse.json(
{ error: "Erreur lors de la réception de la configuration" },
{ status: 400 }
{ message: "Configuration sauvegardée avec succès", config },
{ status: 200 }
);
} catch (error) {
console.error("Erreur lors de la sauvegarde de la configuration:", error);
if (error instanceof Error && error.message === "Utilisateur non authentifié") {
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
}
return NextResponse.json(
{ error: "Erreur lors de la sauvegarde de la configuration" },
{ status: 500 }
);
}
}
export async function GET() {
try {
const mongoConfig = await ConfigDBService.getConfig();
// Convertir le document Mongoose en objet simple
const config = {
url: mongoConfig.url,
username: mongoConfig.username,
password: mongoConfig.password,
userId: mongoConfig.userId,
};
return NextResponse.json(config, { status: 200 });
} catch (error) {
console.error("Erreur lors de la récupération de la configuration:", error);
if (error instanceof Error) {
if (error.message === "Utilisateur non authentifié") {
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
}
if (error.message === "Configuration non trouvée") {
return NextResponse.json({ error: "Configuration non trouvée" }, { status: 404 });
}
}
return NextResponse.json(
{ error: "Erreur lors de la récupération de la configuration" },
{ status: 500 }
);
}
}

View File

@@ -1,429 +1,24 @@
"use client";
import { ConfigDBService } from "@/lib/services/config-db.service";
import { ClientSettings } from "@/components/settings/ClientSettings";
import { useState, useEffect, useRef } from "react";
import { Loader2, Network, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { storageService } from "@/lib/services/storage.service";
import { AuthError } from "@/types/auth";
import { useToast } from "@/components/ui/use-toast";
import { komgaConfigService } from "@/lib/services/komga-config.service";
export default async function SettingsPage() {
let config = null;
interface ErrorMessage {
message: string;
}
export default function SettingsPage() {
const router = useRouter();
const { toast } = useToast();
const [isLoading, setIsLoading] = 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: "",
username: "",
password: "",
});
const [ttlConfig, setTTLConfig] = useState({
defaultTTL: 5,
homeTTL: 5,
librariesTTL: 1440,
seriesTTL: 5,
booksTTL: 5,
imagesTTL: 1440,
});
useEffect(() => {
// Charger la configuration existante
const savedConfig = storageService.getCredentials();
if (savedConfig) {
setConfig({
serverUrl: savedConfig.serverUrl,
username: savedConfig.credentials?.username || "",
password: savedConfig.credentials?.password || "",
});
}
// Charger la configuration des TTL
const savedTTLConfig = storageService.getTTLConfig();
if (savedTTLConfig) {
setTTLConfig(savedTTLConfig);
}
}, []);
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: "Cache supprimé",
description: "Cache serveur supprimé avec succès",
});
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);
try {
const response = await fetch("/api/komga/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
serverUrl: config.serverUrl,
username: config.username,
password: config.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors du test de connexion");
}
toast({
title: "Connexion réussie",
description: "La connexion au serveur Komga a été établie avec succès",
});
} 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 = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
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,
};
const komgaConfig = {
serverUrl: newConfig.serverUrl,
credentials: {
username: newConfig.username,
password: newConfig.password,
},
};
komgaConfigService.setConfig(komgaConfig, true);
fetch("/api/komga/config", {
method: "POST",
body: JSON.stringify(komgaConfig),
});
setConfig(newConfig);
// Émettre un événement pour notifier les autres composants
const configChangeEvent = new CustomEvent("komga-config-changed", { detail: komgaConfig });
window.dispatchEvent(configChangeEvent);
toast({
title: "Configuration sauvegardée",
description: "La configuration a été sauvegardée avec succès",
});
};
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 = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
storageService.setTTLConfig(ttlConfig);
toast({
title: "Configuration TTL sauvegardée",
description: "La configuration des TTL a été sauvegardée avec succès",
});
};
return (
<div className="container max-w-3xl mx-auto py-8 space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Préférences</h1>
</div>
{/* Messages de succès/erreur */}
{error && (
<div className="rounded-md bg-destructive/15 p-4">
<p className="text-sm text-destructive">{error.message}</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 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" />
Configuration Komga
</h2>
<p className="text-sm text-muted-foreground mt-1">
Configurez les informations de connexion à votre serveur Komga.
</p>
</div>
{/* Formulaire de configuration */}
<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">
L&apos;URL du serveur
</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">
L&apos;adresse email de connexion
</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">
Mot de passe
</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"
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"
>
Sauvegarder
</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" />
Test en cours...
</>
) : (
"Tester la connexion"
)}
</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" />
Configuration du Cache
</h2>
<p className="text-sm text-muted-foreground mt-1">
Gérez les paramètres de mise en cache des données.
</p>
</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">
TTL par défaut (minutes)
</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">
TTL page d'accueil
</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">
TTL bibliothèques
</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">
TTL séries
</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">
TTL tomes
</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">
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"
>
Sauvegarder les TTL
</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" />
Suppression...
</>
) : (
"Vider le cache"
)}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
try {
const mongoConfig = await ConfigDBService.getConfig();
// Convertir le document Mongoose en objet simple
if (mongoConfig) {
config = {
url: mongoConfig.url,
username: mongoConfig.username,
password: mongoConfig.password,
userId: mongoConfig.userId,
};
}
} catch (error) {
console.error("Erreur lors de la récupération de la configuration:", error);
// On ne fait rien si la config n'existe pas, on laissera le composant client gérer l'état initial
}
return <ClientSettings initialConfig={config} />;
}

View File

@@ -0,0 +1,438 @@
"use client";
import { useState, useEffect } from "react";
import { Loader2, Network, Trash2 } from "lucide-react";
import { useRouter } from "next/navigation";
import { storageService } from "@/lib/services/storage.service";
import { AuthError } from "@/types/auth";
import { useToast } from "@/components/ui/use-toast";
import { komgaConfigService } from "@/lib/services/komga-config.service";
interface ErrorMessage {
message: string;
}
interface KomgaConfig {
url: string;
username: string;
password: string;
userId: string;
}
interface ClientSettingsProps {
initialConfig: KomgaConfig | null;
}
export function ClientSettings({ initialConfig }: ClientSettingsProps) {
console.log("initialConfig", initialConfig);
const router = useRouter();
const { toast } = useToast();
const [isLoading, setIsLoading] = 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 || "",
});
const [ttlConfig, setTTLConfig] = useState({
defaultTTL: 5,
homeTTL: 5,
librariesTTL: 1440,
seriesTTL: 5,
booksTTL: 5,
imagesTTL: 1440,
});
useEffect(() => {
// Charger la configuration des TTL
const savedTTLConfig = storageService.getTTLConfig();
if (savedTTLConfig) {
setTTLConfig(savedTTLConfig);
}
}, []);
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: "Cache supprimé",
description: "Cache serveur supprimé avec succès",
});
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);
try {
const response = await fetch("/api/komga/test", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
serverUrl: config.serverUrl,
username: config.username,
password: config.password,
}),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors du test de connexion");
}
toast({
title: "Connexion réussie",
description: "La connexion au serveur Komga a été établie avec succès",
});
} 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 = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
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,
};
const komgaConfig = {
serverUrl: newConfig.serverUrl,
credentials: {
username: newConfig.username,
password: newConfig.password,
},
};
komgaConfigService.setConfig(komgaConfig, true);
fetch("/api/komga/config", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
url: newConfig.serverUrl,
username: newConfig.username,
password: newConfig.password,
}),
});
setConfig(newConfig);
// Émettre un événement pour notifier les autres composants
const configChangeEvent = new CustomEvent("komga-config-changed", { detail: komgaConfig });
window.dispatchEvent(configChangeEvent);
toast({
title: "Configuration sauvegardée",
description: "La configuration a été sauvegardée avec succès",
});
};
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 = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setSuccess(null);
storageService.setTTLConfig(ttlConfig);
toast({
title: "Configuration TTL sauvegardée",
description: "La configuration des TTL a été sauvegardée avec succès",
});
};
return (
<div className="container max-w-3xl mx-auto py-8 space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Préférences</h1>
</div>
{/* Messages de succès/erreur */}
{error && (
<div className="rounded-md bg-destructive/15 p-4">
<p className="text-sm text-destructive">{error.message}</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 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" />
Configuration Komga
</h2>
<p className="text-sm text-muted-foreground mt-1">
Configurez les informations de connexion à votre serveur Komga.
</p>
</div>
{/* Formulaire de configuration */}
<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">
L&apos;URL du serveur
</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">
L&apos;adresse email de connexion
</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">
Mot de passe
</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"
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"
>
Sauvegarder
</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" />
Test en cours...
</>
) : (
"Tester la connexion"
)}
</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" />
Configuration du Cache
</h2>
<p className="text-sm text-muted-foreground mt-1">
Gérez les paramètres de mise en cache des données.
</p>
</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">
TTL par défaut (minutes)
</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">
TTL page d'accueil
</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">
TTL bibliothèques
</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">
TTL séries
</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">
TTL tomes
</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">
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"
>
Sauvegarder les TTL
</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" />
Suppression...
</>
) : (
"Vider le cache"
)}
</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,35 @@
import mongoose from "mongoose";
const configSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
unique: true,
},
url: {
type: String,
required: true,
},
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
// Middleware pour mettre à jour le champ updatedAt avant la sauvegarde
configSchema.pre("save", function (next) {
this.updatedAt = new Date();
next();
});
export const KomgaConfig =
mongoose.models.KomgaConfig || mongoose.model("KomgaConfig", configSchema);

51
src/lib/mongodb.ts Normal file
View File

@@ -0,0 +1,51 @@
import mongoose from "mongoose";
const MONGODB_URI = process.env.MONGODB_URI;
if (!MONGODB_URI) {
throw new Error(
"Veuillez définir la variable d'environnement MONGODB_URI dans votre fichier .env"
);
}
interface MongooseCache {
conn: typeof mongoose | null;
promise: Promise<typeof mongoose> | null;
}
declare global {
var mongoose: MongooseCache | undefined;
}
let cached: MongooseCache = global.mongoose || { conn: null, promise: null };
if (!global.mongoose) {
global.mongoose = { conn: null, promise: null };
}
async function connectDB(): Promise<typeof mongoose> {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI!, opts).then((mongoose) => {
return mongoose;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}
export default connectDB;

View File

@@ -0,0 +1,62 @@
import { cookies } from "next/headers";
import connectDB from "@/lib/mongodb";
import { KomgaConfig } from "@/lib/models/config.model";
interface User {
id: string;
email: string;
}
interface KomgaConfigData {
url: string;
username: string;
password: string;
}
export class ConfigDBService {
private static async getCurrentUser(): Promise<User> {
const userCookie = cookies().get("stripUser");
if (!userCookie) {
throw new Error("Utilisateur non authentifié");
}
try {
return JSON.parse(atob(userCookie.value));
} catch (error) {
console.error("Erreur lors de la récupération de l'utilisateur depuis le cookie:", error);
throw new Error("Utilisateur non authentifié");
}
}
static async saveConfig(data: KomgaConfigData) {
const user = await this.getCurrentUser();
await connectDB();
const config = await KomgaConfig.findOneAndUpdate(
{ userId: user.id },
{
userId: user.id,
url: data.url,
username: data.username,
password: data.password,
},
{ upsert: true, new: true }
);
return config;
}
static async getConfig() {
const user = await this.getCurrentUser();
await connectDB();
const config = await KomgaConfig.findOne({ userId: user.id });
if (!config) {
throw new Error("Configuration non trouvée");
}
return config;
}
}