feat: pref for image quality
This commit is contained in:
23
src/app/api/preferences/route.ts
Normal file
23
src/app/api/preferences/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { PreferencesService } from "@/lib/services/preferences.service";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const preferences = await PreferencesService.getPreferences();
|
||||
return NextResponse.json(preferences);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des préférences:", error);
|
||||
return new NextResponse("Erreur lors de la récupération des préférences", { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const preferences = await request.json();
|
||||
const updatedPreferences = await PreferencesService.updatePreferences(preferences);
|
||||
return NextResponse.json(updatedPreferences);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la mise à jour des préférences:", error);
|
||||
return new NextResponse("Erreur lors de la mise à jour des préférences", { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { InstallPWA } from "../ui/InstallPWA";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { authService } from "@/lib/services/auth.service";
|
||||
import { PreferencesProvider } from "@/contexts/PreferencesContext";
|
||||
|
||||
// Routes qui ne nécessitent pas d'authentification
|
||||
const publicRoutes = ["/login", "/register"];
|
||||
@@ -69,13 +70,15 @@ export default function ClientLayout({ children }: { children: React.ReactNode }
|
||||
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
<div className="relative min-h-screen">
|
||||
{!isPublicRoute && <Header onToggleSidebar={handleToggleSidebar} />}
|
||||
{!isPublicRoute && <Sidebar isOpen={isSidebarOpen} onClose={handleCloseSidebar} />}
|
||||
<main className={`${!isPublicRoute ? "container pt-4 md:pt-8" : ""}`}>{children}</main>
|
||||
<InstallPWA />
|
||||
<Toaster />
|
||||
</div>
|
||||
<PreferencesProvider>
|
||||
<div className="relative min-h-screen">
|
||||
{!isPublicRoute && <Header onToggleSidebar={handleToggleSidebar} />}
|
||||
{!isPublicRoute && <Sidebar isOpen={isSidebarOpen} onClose={handleCloseSidebar} />}
|
||||
<main className={`${!isPublicRoute ? "container pt-4 md:pt-8" : ""}`}>{children}</main>
|
||||
<InstallPWA />
|
||||
<Toaster />
|
||||
</div>
|
||||
</PreferencesProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ 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";
|
||||
|
||||
interface ErrorMessage {
|
||||
message: string;
|
||||
@@ -54,6 +57,7 @@ export function ClientSettings({ initialConfig, initialTTLConfig }: ClientSettin
|
||||
imagesTTL: 1440,
|
||||
}
|
||||
);
|
||||
const { preferences, updatePreferences } = usePreferences();
|
||||
|
||||
const handleClearCache = async () => {
|
||||
setIsCacheClearing(true);
|
||||
@@ -241,6 +245,22 @@ export function ClientSettings({ initialConfig, initialTTLConfig }: ClientSettin
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleThumbnails = async (checked: boolean) => {
|
||||
try {
|
||||
await updatePreferences({ showThumbnails: checked });
|
||||
toast({
|
||||
title: "Préférences sauvegardées",
|
||||
description: "Les préférences ont été mises à jour avec succès",
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Erreur",
|
||||
description: "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">
|
||||
@@ -260,6 +280,36 @@ export function ClientSettings({ initialConfig, initialTTLConfig }: ClientSettin
|
||||
)}
|
||||
|
||||
<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">
|
||||
Préférences d'affichage
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Personnalisez l'affichage de votre bibliothèque.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="thumbnails">Afficher les vignettes</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Utiliser les vignettes au lieu des premières pages pour l'affichage des séries
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="thumbnails"
|
||||
checked={preferences.showThumbnails}
|
||||
onCheckedChange={handleToggleThumbnails}
|
||||
/>
|
||||
</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">
|
||||
|
||||
20
src/components/ui/label.tsx
Normal file
20
src/components/ui/label.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const labelVariants = cva(
|
||||
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
);
|
||||
|
||||
const Label = React.forwardRef<
|
||||
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> & VariantProps<typeof labelVariants>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
|
||||
));
|
||||
Label.displayName = LabelPrimitive.Root.displayName;
|
||||
|
||||
export { Label };
|
||||
28
src/components/ui/switch.tsx
Normal file
28
src/components/ui/switch.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SwitchPrimitives from "@radix-ui/react-switch";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Switch = React.forwardRef<
|
||||
React.ElementRef<typeof SwitchPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-[24px] w-[44px] shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
));
|
||||
Switch.displayName = SwitchPrimitives.Root.displayName;
|
||||
|
||||
export { Switch };
|
||||
70
src/contexts/PreferencesContext.tsx
Normal file
70
src/contexts/PreferencesContext.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import { UserPreferences } from "@/lib/services/preferences.service";
|
||||
|
||||
interface PreferencesContextType {
|
||||
preferences: UserPreferences;
|
||||
updatePreferences: (newPreferences: Partial<UserPreferences>) => Promise<void>;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
const PreferencesContext = createContext<PreferencesContextType | undefined>(undefined);
|
||||
|
||||
export function PreferencesProvider({ children }: { children: React.ReactNode }) {
|
||||
const [preferences, setPreferences] = useState<UserPreferences>({
|
||||
showThumbnails: false,
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPreferences = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/preferences");
|
||||
if (!response.ok) throw new Error("Erreur lors de la récupération des préférences");
|
||||
const data = await response.json();
|
||||
setPreferences(data);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des préférences:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPreferences();
|
||||
}, []);
|
||||
|
||||
const updatePreferences = async (newPreferences: Partial<UserPreferences>) => {
|
||||
try {
|
||||
const response = await fetch("/api/preferences", {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(newPreferences),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Erreur lors de la mise à jour des préférences");
|
||||
|
||||
const updatedPreferences = await response.json();
|
||||
setPreferences(updatedPreferences);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la mise à jour des préférences:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<PreferencesContext.Provider value={{ preferences, updatePreferences, isLoading }}>
|
||||
{children}
|
||||
</PreferencesContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePreferences() {
|
||||
const context = useContext(PreferencesContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("usePreferences must be used within a PreferencesProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
21
src/lib/models/preferences.model.ts
Normal file
21
src/lib/models/preferences.model.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
const preferencesSchema = new mongoose.Schema(
|
||||
{
|
||||
userId: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
showThumbnails: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
export const PreferencesModel =
|
||||
mongoose.models.Preferences || mongoose.model("Preferences", preferencesSchema);
|
||||
@@ -1,6 +1,7 @@
|
||||
import { BaseApiService } from "./base-api.service";
|
||||
import { KomgaBook } from "@/types/komga";
|
||||
import { ImageService } from "./image.service";
|
||||
import { PreferencesService } from "./preferences.service";
|
||||
|
||||
export class BookService extends BaseApiService {
|
||||
static async getBook(bookId: string): Promise<{ book: KomgaBook; pages: number[] }> {
|
||||
@@ -66,6 +67,14 @@ export class BookService extends BaseApiService {
|
||||
|
||||
static async getPage(bookId: string, pageNumber: number): Promise<Response> {
|
||||
try {
|
||||
// Récupérer les préférences de l'utilisateur
|
||||
const preferences = await PreferencesService.getPreferences();
|
||||
|
||||
// Si l'utilisateur préfère les vignettes, utiliser getPageThumbnail
|
||||
if (preferences.showThumbnails) {
|
||||
return this.getPageThumbnail(bookId, pageNumber);
|
||||
}
|
||||
|
||||
// Ajuster le numéro de page pour l'API Komga (zero-based)
|
||||
const adjustedPageNumber = pageNumber - 1;
|
||||
const response = await ImageService.getImage(
|
||||
@@ -91,6 +100,7 @@ export class BookService extends BaseApiService {
|
||||
return new Response(response.buffer, {
|
||||
headers: {
|
||||
"Content-Type": response.contentType || "image/jpeg",
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
65
src/lib/services/preferences.service.ts
Normal file
65
src/lib/services/preferences.service.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { cookies } from "next/headers";
|
||||
import connectDB from "@/lib/mongodb";
|
||||
import { PreferencesModel } from "@/lib/models/preferences.model";
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface UserPreferences {
|
||||
showThumbnails: boolean;
|
||||
}
|
||||
|
||||
export class PreferencesService {
|
||||
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 getPreferences(): Promise<UserPreferences> {
|
||||
await connectDB();
|
||||
const user = await this.getCurrentUser();
|
||||
|
||||
const preferences = await PreferencesModel.findOne({ userId: user.id });
|
||||
if (!preferences) {
|
||||
// Créer les préférences par défaut si elles n'existent pas
|
||||
const defaultPreferences = await PreferencesModel.create({
|
||||
userId: user.id,
|
||||
showThumbnails: false,
|
||||
});
|
||||
return {
|
||||
showThumbnails: defaultPreferences.showThumbnails,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
showThumbnails: preferences.showThumbnails,
|
||||
};
|
||||
}
|
||||
|
||||
static async updatePreferences(preferences: Partial<UserPreferences>): Promise<UserPreferences> {
|
||||
await connectDB();
|
||||
const user = await this.getCurrentUser();
|
||||
|
||||
const updatedPreferences = await PreferencesModel.findOneAndUpdate(
|
||||
{ userId: user.id },
|
||||
{ $set: preferences },
|
||||
{ new: true, upsert: true }
|
||||
);
|
||||
|
||||
return {
|
||||
showThumbnails: updatedPreferences.showThumbnails,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { LibraryResponse } from "@/types/library";
|
||||
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
||||
import { BookService } from "./book.service";
|
||||
import { ImageService } from "./image.service";
|
||||
import { PreferencesService } from "./preferences.service";
|
||||
|
||||
export class SeriesService extends BaseApiService {
|
||||
static async getSeries(seriesId: string): Promise<KomgaSeries> {
|
||||
@@ -78,22 +79,20 @@ export class SeriesService extends BaseApiService {
|
||||
|
||||
static async getFirstPage(seriesId: string): Promise<Response> {
|
||||
try {
|
||||
// Récupérer l'ID du premier livre
|
||||
const firstBookId = await this.getFirstBook(seriesId);
|
||||
return await BookService.getPage(firstBookId, 1);
|
||||
} catch (error) {
|
||||
// En cas d'erreur, on essaie de récupérer le thumbnail comme fallback
|
||||
try {
|
||||
const response = await ImageService.getImage(`series/${seriesId}/thumbnail`);
|
||||
return new Response(response.buffer, {
|
||||
headers: {
|
||||
"Content-Type": response.contentType || "image/jpeg",
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
},
|
||||
});
|
||||
} catch (fallbackError) {
|
||||
throw this.handleError(fallbackError, "Impossible de récupérer l'image de la série");
|
||||
// Récupérer les préférences de l'utilisateur
|
||||
const preferences = await PreferencesService.getPreferences();
|
||||
|
||||
// Si l'utilisateur préfère les vignettes, utiliser getThumbnail
|
||||
if (preferences.showThumbnails) {
|
||||
return this.getThumbnail(seriesId);
|
||||
}
|
||||
|
||||
// Sinon, récupérer la première page
|
||||
const firstBookId = await this.getFirstBook(seriesId);
|
||||
const response = await BookService.getPage(firstBookId, 1);
|
||||
return response;
|
||||
} catch (error) {
|
||||
throw this.handleError(error, "Impossible de récupérer la première page");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user