Compare commits
3 Commits
494206b5b3
...
2c3d9d95c6
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c3d9d95c6 | |||
| df8e594d57 | |||
| f80b8cb81c |
@@ -3,6 +3,7 @@ import { AppDataSource } from "../config/data-source";
|
||||
import { User } from "../entities/User";
|
||||
import { UserRole } from "../entities/UserRole";
|
||||
import { AuthenticatedRequest } from "./auth.middleware";
|
||||
import logger from "../utils/logger";
|
||||
|
||||
/**
|
||||
* Middleware requireAdmin — s'exécute APRÈS requireAuth.
|
||||
@@ -39,7 +40,8 @@ export const requireAdmin = async (
|
||||
}
|
||||
|
||||
next();
|
||||
} catch {
|
||||
} catch (err) {
|
||||
logger.error("requireAdmin — DB error", { err });
|
||||
res.status(500).json({ success: false, error: "INTERNAL_ERROR" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AppDataSource } from "../config/data-source";
|
||||
import { Video } from "../entities/Video";
|
||||
import { User } from "../entities/User";
|
||||
import { UserSubscription } from "../entities/UserSubscription";
|
||||
import logger from "../utils/logger";
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -41,7 +42,8 @@ async function getUserLevel(token: string | undefined): Promise<number> {
|
||||
});
|
||||
|
||||
return sub?.plan.level ?? 0;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
logger.warn("getUserLevel — auth/DB error", { err });
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -128,7 +130,8 @@ router.get("/:key(*)", async (req: Request, res: Response): Promise<void> => {
|
||||
});
|
||||
fs.createReadStream(resolved).pipe(res);
|
||||
}
|
||||
} catch {
|
||||
} catch (err) {
|
||||
logger.error("GET /stream/:key — unexpected error", { err });
|
||||
res.status(500).json({ success: false, error: "INTERNAL_ERROR" });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ import { AppDataSource } from "../config/data-source";
|
||||
import { User } from "../entities/User";
|
||||
import { UserSubscription } from "../entities/UserSubscription";
|
||||
import { requireAuth, AuthenticatedRequest } from "../middleware/auth.middleware";
|
||||
import logger from "../utils/logger";
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -27,45 +28,50 @@ async function getActiveSub(userId: string) {
|
||||
router.get("/me/profile", requireAuth, async (req: Request, res: Response): Promise<void> => {
|
||||
const { user } = req as AuthenticatedRequest;
|
||||
|
||||
const localUser = await AppDataSource.getRepository(User).findOne({
|
||||
where: { superOAuthId: user.id },
|
||||
relations: ["userRoles", "userRoles.role"],
|
||||
});
|
||||
try {
|
||||
const localUser = await AppDataSource.getRepository(User).findOne({
|
||||
where: { superOAuthId: user.id },
|
||||
relations: ["userRoles", "userRoles.role"],
|
||||
});
|
||||
|
||||
if (!localUser) {
|
||||
res.status(404).json({ success: false, error: "USER_NOT_FOUND" });
|
||||
return;
|
||||
if (!localUser) {
|
||||
res.status(404).json({ success: false, error: "USER_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
|
||||
const roles = localUser.userRoles.map((ur) => ur.role.slug);
|
||||
const activeSub = await getActiveSub(localUser.id);
|
||||
|
||||
const plan = activeSub
|
||||
? { slug: activeSub.plan.slug, name: activeSub.plan.name, level: activeSub.plan.level }
|
||||
: null;
|
||||
|
||||
const subscription = activeSub
|
||||
? {
|
||||
status: activeSub.status,
|
||||
startsAt: activeSub.startsAt.toISOString(),
|
||||
endsAt: activeSub.endsAt ? activeSub.endsAt.toISOString() : null,
|
||||
}
|
||||
: null;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
id: localUser.id,
|
||||
superOAuthId: localUser.superOAuthId,
|
||||
email: localUser.email,
|
||||
nickname: localUser.nickname,
|
||||
avatar: localUser.avatar,
|
||||
roles,
|
||||
plan,
|
||||
subscription,
|
||||
createdAt: localUser.createdAt.toISOString(),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error("GET /users/me/profile — DB error", { err });
|
||||
res.status(500).json({ success: false, error: "INTERNAL_ERROR" });
|
||||
}
|
||||
|
||||
const roles = localUser.userRoles.map((ur) => ur.role.slug);
|
||||
const activeSub = await getActiveSub(localUser.id);
|
||||
|
||||
const plan = activeSub
|
||||
? { slug: activeSub.plan.slug, name: activeSub.plan.name, level: activeSub.plan.level }
|
||||
: null;
|
||||
|
||||
const subscription = activeSub
|
||||
? {
|
||||
status: activeSub.status,
|
||||
startsAt: activeSub.startsAt.toISOString(),
|
||||
endsAt: activeSub.endsAt ? activeSub.endsAt.toISOString() : null,
|
||||
}
|
||||
: null;
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
id: localUser.id,
|
||||
superOAuthId: localUser.superOAuthId,
|
||||
email: localUser.email,
|
||||
nickname: localUser.nickname,
|
||||
avatar: localUser.avatar,
|
||||
roles,
|
||||
plan,
|
||||
subscription,
|
||||
createdAt: localUser.createdAt.toISOString(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -95,33 +101,38 @@ router.patch("/me", requireAuth, async (req: Request, res: Response): Promise<vo
|
||||
if (!["http:", "https:"].includes(parsed.protocol)) {
|
||||
throw new Error("invalid protocol");
|
||||
}
|
||||
} catch {
|
||||
} catch (_err) {
|
||||
res.status(400).json({ success: false, error: "INVALID_AVATAR", message: "avatar must be a valid http/https URL or null" });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const userRepo = AppDataSource.getRepository(User);
|
||||
const localUser = await userRepo.findOne({ where: { superOAuthId: user.id } });
|
||||
try {
|
||||
const userRepo = AppDataSource.getRepository(User);
|
||||
const localUser = await userRepo.findOne({ where: { superOAuthId: user.id } });
|
||||
|
||||
if (!localUser) {
|
||||
res.status(404).json({ success: false, error: "USER_NOT_FOUND" });
|
||||
return;
|
||||
if (!localUser) {
|
||||
res.status(404).json({ success: false, error: "USER_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (nickname !== undefined) localUser.nickname = (nickname as string).trim();
|
||||
if (avatar !== undefined) localUser.avatar = avatar as string | null;
|
||||
|
||||
await userRepo.save(localUser);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
id: localUser.id,
|
||||
nickname: localUser.nickname,
|
||||
avatar: localUser.avatar,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error("PATCH /users/me — DB error", { err });
|
||||
res.status(500).json({ success: false, error: "INTERNAL_ERROR" });
|
||||
}
|
||||
|
||||
if (nickname !== undefined) localUser.nickname = (nickname as string).trim();
|
||||
if (avatar !== undefined) localUser.avatar = avatar as string | null;
|
||||
|
||||
await userRepo.save(localUser);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: {
|
||||
id: localUser.id,
|
||||
nickname: localUser.nickname,
|
||||
avatar: localUser.avatar,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
31
frontend/src/components/ErrorBoundary.tsx
Normal file
31
frontend/src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import { Component, type ReactNode } from 'react';
|
||||
|
||||
interface Props { children: ReactNode; }
|
||||
interface State { hasError: boolean; }
|
||||
|
||||
export default class ErrorBoundary extends Component<Props, State> {
|
||||
state: State = { hasError: false };
|
||||
|
||||
static getDerivedStateFromError(): State {
|
||||
return { hasError: true };
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-od-bg">
|
||||
<div className="rounded border border-od-crit/40 bg-od-surface p-8 text-center">
|
||||
<p className="font-mono text-sm text-od-crit">Une erreur inattendue s'est produite.</p>
|
||||
<button
|
||||
className="mt-4 rounded border border-od-border px-4 py-2 text-xs text-od-muted hover:border-od-accent/40"
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
Recharger
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ function NativePlayer({ url }: { url: string }) {
|
||||
hls = new Hls();
|
||||
hls.loadSource(url);
|
||||
hls.attachMedia(video);
|
||||
});
|
||||
}).catch(() => { /* HLS non disponible — dégradation silencieuse */ });
|
||||
}
|
||||
|
||||
return () => { hls?.destroy(); };
|
||||
|
||||
@@ -2,9 +2,12 @@ import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./styles/index.css";
|
||||
import App from "./App";
|
||||
import ErrorBoundary from "./components/ErrorBoundary";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
</StrictMode>
|
||||
);
|
||||
|
||||
@@ -19,11 +19,12 @@ interface VideosResponse {
|
||||
export default function HomePage() {
|
||||
const [videos, setVideos] = useState<Video[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<VideosResponse>('/videos')
|
||||
.then((res) => setVideos(res.data.videos))
|
||||
.catch(() => setVideos([]))
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
@@ -47,7 +48,11 @@ export default function HomePage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && (
|
||||
{error && (
|
||||
<p className="text-sm text-od-crit">Impossible de charger les vidéos. Réessaie plus tard.</p>
|
||||
)}
|
||||
|
||||
{!loading && !error && (
|
||||
<>
|
||||
{free.length > 0 && (
|
||||
<section>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { useParams, Link, useNavigate } from 'react-router-dom';
|
||||
import { apiFetch, ApiError } from '../lib/api';
|
||||
|
||||
interface Video {
|
||||
@@ -27,9 +27,25 @@ interface PlaylistResponse {
|
||||
|
||||
export default function PlaylistPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [data, setData] = useState<PlaylistResponse['data'] | null>(null);
|
||||
const [error, setError] = useState<'forbidden' | 'not_found' | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [actionError, setActionError] = useState<string | null>(null);
|
||||
|
||||
// Edit inline form
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editTitle, setEditTitle] = useState('');
|
||||
const [editVisibility, setEditVisibility] = useState<'private' | 'shared' | 'public'>('private');
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Share modal
|
||||
const [shareOpen, setShareOpen] = useState(false);
|
||||
const [shareUserId, setShareUserId] = useState('');
|
||||
const [sharePermission, setSharePermission] = useState<'view' | 'edit'>('view');
|
||||
const [sharing, setSharing] = useState(false);
|
||||
const [shareError, setShareError] = useState<string | null>(null);
|
||||
const [shareOk, setShareOk] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -42,6 +58,73 @@ export default function PlaylistPage() {
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
function openEdit() {
|
||||
if (!data) return;
|
||||
setEditTitle(data.playlist.title);
|
||||
setEditVisibility(data.playlist.visibility);
|
||||
setEditOpen(true);
|
||||
setActionError(null);
|
||||
}
|
||||
|
||||
async function handleEdit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!id || saving) return;
|
||||
setSaving(true);
|
||||
setActionError(null);
|
||||
try {
|
||||
const res = await apiFetch<{ success: boolean; data: { playlist: Playlist } }>(
|
||||
`/playlists/${id}`,
|
||||
{ method: 'PATCH', body: JSON.stringify({ title: editTitle.trim(), visibility: editVisibility }) }
|
||||
);
|
||||
setData((prev) => prev ? { ...prev, playlist: res.data.playlist } : prev);
|
||||
setEditOpen(false);
|
||||
} catch {
|
||||
setActionError('Impossible de modifier la playlist.');
|
||||
}
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!id || !confirm('Supprimer cette playlist ?')) return;
|
||||
setActionError(null);
|
||||
try {
|
||||
await apiFetch(`/playlists/${id}`, { method: 'DELETE' });
|
||||
navigate('/playlists');
|
||||
} catch {
|
||||
setActionError('Impossible de supprimer la playlist.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRemoveVideo(videoId: string) {
|
||||
if (!id || !confirm('Retirer cette vidéo de la playlist ?')) return;
|
||||
setActionError(null);
|
||||
try {
|
||||
await apiFetch(`/playlists/${id}/videos/${videoId}`, { method: 'DELETE' });
|
||||
setData((prev) => prev ? { ...prev, videos: prev.videos.filter((v) => v.id !== videoId) } : prev);
|
||||
} catch {
|
||||
setActionError('Impossible de retirer la vidéo.');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleShare(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!id || !shareUserId.trim() || sharing) return;
|
||||
setSharing(true);
|
||||
setShareError(null);
|
||||
setShareOk(false);
|
||||
try {
|
||||
await apiFetch(`/playlists/${id}/share`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ userId: shareUserId.trim(), permission: sharePermission }),
|
||||
});
|
||||
setShareOk(true);
|
||||
setShareUserId('');
|
||||
} catch {
|
||||
setShareError("Impossible d'envoyer l'invitation.");
|
||||
}
|
||||
setSharing(false);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
@@ -77,41 +160,162 @@ export default function PlaylistPage() {
|
||||
}
|
||||
|
||||
const { playlist, videos, permission } = data;
|
||||
const isOwner = permission === 'owner';
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
|
||||
<div className="flex flex-col gap-1 border-b border-od-border pb-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-od-text">{playlist.title}</h1>
|
||||
<span className="font-mono text-xs text-od-muted">{permission}</span>
|
||||
</div>
|
||||
{playlist.description && (
|
||||
<p className="text-sm text-od-muted">{playlist.description}</p>
|
||||
{/* Header */}
|
||||
<div className="flex flex-col gap-3 border-b border-od-border pb-6">
|
||||
{editOpen ? (
|
||||
<form onSubmit={handleEdit} className="flex flex-col gap-3 rounded border border-od-border bg-od-surface p-4">
|
||||
<p className="font-mono text-xs text-od-muted uppercase tracking-widest">Modifier</p>
|
||||
<input
|
||||
value={editTitle}
|
||||
onChange={(e) => setEditTitle(e.target.value)}
|
||||
required
|
||||
className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
|
||||
/>
|
||||
<select
|
||||
value={editVisibility}
|
||||
onChange={(e) => setEditVisibility(e.target.value as 'private' | 'shared' | 'public')}
|
||||
className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text outline-none focus:border-od-accent"
|
||||
>
|
||||
<option value="private">Privée</option>
|
||||
<option value="shared">Partagée</option>
|
||||
<option value="public">Publique</option>
|
||||
</select>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
className="rounded border border-od-accent px-4 py-1.5 font-mono text-xs text-od-accent hover:bg-od-accent hover:text-od-bg transition-colors disabled:opacity-40"
|
||||
>
|
||||
{saving ? '…' : 'Enregistrer'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditOpen(false)}
|
||||
className="rounded border border-od-border px-4 py-1.5 font-mono text-xs text-od-muted hover:text-od-text transition-colors"
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-xl font-semibold text-od-text">{playlist.title}</h1>
|
||||
<span className="font-mono text-xs text-od-muted">{permission}</span>
|
||||
</div>
|
||||
{playlist.description && (
|
||||
<p className="text-sm text-od-muted">{playlist.description}</p>
|
||||
)}
|
||||
{isOwner && (
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={openEdit}
|
||||
className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors"
|
||||
>
|
||||
Éditer
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setShareOpen(true); setShareError(null); setShareOk(false); }}
|
||||
className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors"
|
||||
>
|
||||
Partager
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-crit hover:text-od-crit transition-colors"
|
||||
>
|
||||
Supprimer
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{actionError && <p className="font-mono text-xs text-od-crit">{actionError}</p>}
|
||||
</div>
|
||||
|
||||
{/* Share modal */}
|
||||
{shareOpen && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-od-bg/80">
|
||||
<div className="w-full max-w-sm rounded border border-od-border bg-od-surface p-6 flex flex-col gap-4">
|
||||
<p className="font-mono text-xs text-od-muted uppercase tracking-widest">Partager</p>
|
||||
<form onSubmit={handleShare} className="flex flex-col gap-3">
|
||||
<input
|
||||
value={shareUserId}
|
||||
onChange={(e) => setShareUserId(e.target.value)}
|
||||
placeholder="ID utilisateur"
|
||||
required
|
||||
className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
|
||||
/>
|
||||
<select
|
||||
value={sharePermission}
|
||||
onChange={(e) => setSharePermission(e.target.value as 'view' | 'edit')}
|
||||
className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text outline-none focus:border-od-accent"
|
||||
>
|
||||
<option value="view">Lecture seule</option>
|
||||
<option value="edit">Édition</option>
|
||||
</select>
|
||||
{shareError && <p className="font-mono text-xs text-od-crit">{shareError}</p>}
|
||||
{shareOk && <p className="font-mono text-xs text-od-ok">Invitation envoyée.</p>}
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={sharing || !shareUserId.trim()}
|
||||
className="rounded border border-od-accent px-4 py-1.5 font-mono text-xs text-od-accent hover:bg-od-accent hover:text-od-bg transition-colors disabled:opacity-40"
|
||||
>
|
||||
{sharing ? '…' : 'Inviter'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShareOpen(false)}
|
||||
className="rounded border border-od-border px-4 py-1.5 font-mono text-xs text-od-muted hover:text-od-text transition-colors"
|
||||
>
|
||||
Fermer
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Videos */}
|
||||
{videos.length === 0 ? (
|
||||
<p className="text-sm text-od-muted">Aucune vidéo dans cette playlist.</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{videos.map((v, i) => (
|
||||
<Link
|
||||
<div
|
||||
key={v.id}
|
||||
to={`/video/${v.id}`}
|
||||
className="flex items-center gap-4 rounded border border-od-border bg-od-surface px-4 py-3 hover:border-od-accent/40 transition-colors"
|
||||
className="flex items-center gap-4 rounded border border-od-border bg-od-surface px-4 py-3"
|
||||
>
|
||||
<span className="font-mono text-xs text-od-muted w-5 shrink-0">{i + 1}</span>
|
||||
{v.thumbnailUrl && (
|
||||
<img src={v.thumbnailUrl} alt="" className="h-10 w-16 rounded object-cover shrink-0" />
|
||||
<Link
|
||||
to={`/video/${v.id}`}
|
||||
className="flex flex-1 items-center gap-4 hover:opacity-80 transition-opacity min-w-0"
|
||||
>
|
||||
{v.thumbnailUrl && (
|
||||
<img src={v.thumbnailUrl} alt="" className="h-10 w-16 rounded object-cover shrink-0" />
|
||||
)}
|
||||
<span className="flex-1 text-sm text-od-text truncate">{v.title}</span>
|
||||
{v.duration && (
|
||||
<span className="font-mono text-xs text-od-muted shrink-0">
|
||||
{Math.floor(v.duration / 60)}:{String(v.duration % 60).padStart(2, '0')}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
{isOwner && (
|
||||
<button
|
||||
onClick={() => handleRemoveVideo(v.id)}
|
||||
className="font-mono text-xs text-od-muted hover:text-od-crit transition-colors shrink-0"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
<span className="flex-1 text-sm text-od-text">{v.title}</span>
|
||||
{v.duration && (
|
||||
<span className="font-mono text-xs text-od-muted shrink-0">
|
||||
{Math.floor(v.duration / 60)}:{String(v.duration % 60).padStart(2, '0')}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -9,28 +9,40 @@ interface Playlist {
|
||||
visibility: 'private' | 'shared' | 'public';
|
||||
}
|
||||
|
||||
interface Invitation {
|
||||
shareId: string;
|
||||
playlistId: string;
|
||||
playlistTitle: string;
|
||||
permission: 'view' | 'edit';
|
||||
}
|
||||
|
||||
interface PlaylistsResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
owned: Playlist[];
|
||||
shared: (Playlist & { permission: 'view' | 'edit' })[];
|
||||
invitations?: Invitation[];
|
||||
};
|
||||
}
|
||||
|
||||
export default function PlaylistsPage() {
|
||||
const [owned, setOwned] = useState<Playlist[]>([]);
|
||||
const [shared, setShared] = useState<(Playlist & { permission: 'view' | 'edit' })[]>([]);
|
||||
const [invitations, setInvitations] = useState<Invitation[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [fetchError, setFetchError] = useState<string | null>(null);
|
||||
const [createTitle, setCreateTitle] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
const [inviteError, setInviteError] = useState<string | null>(null);
|
||||
const [respondingId, setRespondingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<PlaylistsResponse>('/playlists')
|
||||
.then((res) => {
|
||||
setOwned(res.data.owned);
|
||||
setShared(res.data.shared);
|
||||
setInvitations(res.data.invitations ?? []);
|
||||
})
|
||||
.catch(() => setFetchError('Impossible de charger les playlists.'))
|
||||
.finally(() => setLoading(false));
|
||||
@@ -54,6 +66,28 @@ export default function PlaylistsPage() {
|
||||
setCreating(false);
|
||||
}
|
||||
|
||||
async function respondInvitation(inv: Invitation, status: 'accepted' | 'revoked') {
|
||||
if (respondingId) return;
|
||||
setRespondingId(inv.shareId);
|
||||
setInviteError(null);
|
||||
try {
|
||||
await apiFetch(`/playlists/${inv.playlistId}/share/${inv.shareId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
setInvitations((prev) => prev.filter((i) => i.shareId !== inv.shareId));
|
||||
if (status === 'accepted') {
|
||||
const res = await apiFetch<PlaylistsResponse>('/playlists');
|
||||
setOwned(res.data.owned);
|
||||
setShared(res.data.shared);
|
||||
setInvitations(res.data.invitations ?? []);
|
||||
}
|
||||
} catch {
|
||||
setInviteError("Impossible de répondre à l'invitation.");
|
||||
}
|
||||
setRespondingId(null);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
@@ -77,25 +111,60 @@ export default function PlaylistsPage() {
|
||||
|
||||
{/* Créer */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<form onSubmit={handleCreate} className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={createTitle}
|
||||
onChange={(e) => setCreateTitle(e.target.value)}
|
||||
placeholder="Nouvelle playlist…"
|
||||
className="flex-1 rounded border border-od-border bg-od-surface px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!createTitle.trim() || creating}
|
||||
className="rounded border border-od-border px-4 py-2 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors disabled:opacity-40"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</form>
|
||||
{createError && <p className="font-mono text-xs text-od-crit">{createError}</p>}
|
||||
<form onSubmit={handleCreate} className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={createTitle}
|
||||
onChange={(e) => setCreateTitle(e.target.value)}
|
||||
placeholder="Nouvelle playlist…"
|
||||
className="flex-1 rounded border border-od-border bg-od-surface px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!createTitle.trim() || creating}
|
||||
className="rounded border border-od-border px-4 py-2 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors disabled:opacity-40"
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</form>
|
||||
{createError && <p className="font-mono text-xs text-od-crit">{createError}</p>}
|
||||
</div>
|
||||
|
||||
{/* Invitations reçues */}
|
||||
{invitations.length > 0 && (
|
||||
<section className="flex flex-col gap-2">
|
||||
<h2 className="font-mono text-xs uppercase tracking-widest text-od-muted">Invitations</h2>
|
||||
{inviteError && <p className="font-mono text-xs text-od-crit">{inviteError}</p>}
|
||||
{invitations.map((inv) => (
|
||||
<div
|
||||
key={inv.shareId}
|
||||
className="flex items-center justify-between gap-4 rounded border border-od-border bg-od-surface px-4 py-3"
|
||||
>
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="text-sm text-od-text truncate">{inv.playlistTitle}</span>
|
||||
<span className="font-mono text-xs text-od-muted">{inv.permission}</span>
|
||||
</div>
|
||||
<div className="flex gap-2 shrink-0">
|
||||
<button
|
||||
disabled={respondingId === inv.shareId}
|
||||
onClick={() => respondInvitation(inv, 'accepted')}
|
||||
className="rounded border border-od-ok px-3 py-1 font-mono text-xs text-od-ok hover:bg-od-ok hover:text-od-bg transition-colors disabled:opacity-40"
|
||||
>
|
||||
{respondingId === inv.shareId ? '…' : 'Accepter'}
|
||||
</button>
|
||||
<button
|
||||
disabled={respondingId === inv.shareId}
|
||||
onClick={() => respondInvitation(inv, 'revoked')}
|
||||
className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-crit hover:text-od-crit transition-colors disabled:opacity-40"
|
||||
>
|
||||
Refuser
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Mes playlists */}
|
||||
{owned.length > 0 && (
|
||||
<section className="flex flex-col gap-2">
|
||||
@@ -112,7 +181,7 @@ export default function PlaylistsPage() {
|
||||
</section>
|
||||
)}
|
||||
|
||||
{owned.length === 0 && shared.length === 0 && (
|
||||
{owned.length === 0 && shared.length === 0 && invitations.length === 0 && (
|
||||
<p className="text-sm text-od-muted">Aucune playlist pour l'instant.</p>
|
||||
)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user