feat(chat,files): salon par dossier, favoris, cloisonnement des droits admin
PR — Ouverture automatique / create-pr (push) Successful in 2s
PR — Ouverture automatique / create-pr (push) Successful in 2s
- chat: salon attache a un dossier, membres = comptes ayant acces au dossier - securite: suppression du passage automatique admin sur fichiers/dossiers/ corbeille/recherche/galerie/chat ; l'admin n'accede qu'a ses partages - favoris: tri en tete dans l'explorateur + page dediee (GET /favorites) - ui: retrait des pastilles Systeme/Public sur la carte dossier - migration 007_chat : table chat_messages
This commit is contained in:
+4
-1
@@ -22,6 +22,7 @@ erDiagram
|
|||||||
users ||--o{ folders : "proprietaire"
|
users ||--o{ folders : "proprietaire"
|
||||||
users ||--o{ files : "proprietaire"
|
users ||--o{ files : "proprietaire"
|
||||||
users ||--o{ folder_permissions : "beneficie"
|
users ||--o{ folder_permissions : "beneficie"
|
||||||
|
users ||--o{ chat_messages : "ecrit"
|
||||||
users ||--o{ audit_logs : "trace"
|
users ||--o{ audit_logs : "trace"
|
||||||
storage_locations ||--o{ folders : "contient"
|
storage_locations ||--o{ folders : "contient"
|
||||||
storage_locations ||--o{ files : "contient"
|
storage_locations ||--o{ files : "contient"
|
||||||
@@ -35,7 +36,7 @@ erDiagram
|
|||||||
|
|
||||||
## Tables
|
## Tables
|
||||||
|
|
||||||
15 tables en base après `005` (`share_links` ayant été supprimée par `004`).
|
16 tables en base après `007` (`share_links` ayant été supprimée par `004`).
|
||||||
Seules celles marquées « `/…` » sont atteignables depuis le front.
|
Seules celles marquées « `/…` » sont atteignables depuis le front.
|
||||||
|
|
||||||
| Table | Rôle | Exposée par l'API |
|
| Table | Rôle | Exposée par l'API |
|
||||||
@@ -52,6 +53,7 @@ Seules celles marquées « `/…` » sont atteignables depuis le front.
|
|||||||
| `files` | Métadonnées de l'original, jamais ré-écrit | `/files` |
|
| `files` | Métadonnées de l'original, jamais ré-écrit | `/files` |
|
||||||
| `media_metadata` | Dimensions, durée, codecs, EXIF, couleur dominante | non (galerie non exposée) |
|
| `media_metadata` | Dimensions, durée, codecs, EXIF, couleur dominante | non (galerie non exposée) |
|
||||||
| `file_variants` | Miniatures et aperçus WebP dérivés | non |
|
| `file_variants` | Miniatures et aperçus WebP dérivés | non |
|
||||||
|
| `chat_messages` | Salon d'un dossier : dossier (`ON DELETE CASCADE`), auteur (`ON DELETE SET NULL`), soft-delete | `/folders/:id/chat` |
|
||||||
| `settings` | Configuration clé-valeur | non |
|
| `settings` | Configuration clé-valeur | non |
|
||||||
| `audit_logs` | Piste d'audit | non (écrit par `audit()`) |
|
| `audit_logs` | Piste d'audit | non (écrit par `audit()`) |
|
||||||
| `schema_migrations` | Versions appliquées | non |
|
| `schema_migrations` | Versions appliquées | non |
|
||||||
@@ -163,6 +165,7 @@ plus grande marge disponible.
|
|||||||
| `004_cloud_requirements.sql` | identité complète, sessions, validation d'e-mail, avatar, `access_type`, médias, variantes, budget par compte, suppression des liens publics |
|
| `004_cloud_requirements.sql` | identité complète, sessions, validation d'e-mail, avatar, `access_type`, médias, variantes, budget par compte, suppression des liens publics |
|
||||||
| `005_storage_location_realign.sql` | `mount_path` réaligné sur `/data/media`, quota 400 Go, garde-fou sur les emplacements sans quota |
|
| `005_storage_location_realign.sql` | `mount_path` réaligné sur `/data/media`, quota 400 Go, garde-fou sur les emplacements sans quota |
|
||||||
| `006_public_folder.sql` | crée le dossier système « Public », retire les réglages devenus morts |
|
| `006_public_folder.sql` | crée le dossier système « Public », retire les réglages devenus morts |
|
||||||
|
| `007_chat.sql` | crée `chat_messages`, le salon d'un dossier (FK dossier `ON DELETE CASCADE`) |
|
||||||
|
|
||||||
`004` porte le passage d'un modèle de partage public vers un stockage privé :
|
`004` porte le passage d'un modèle de partage public vers un stockage privé :
|
||||||
elle supprime `share_links`, scinde `display_name` en `first_name` et
|
elle supprime `share_links`, scinde `display_name` en `first_name` et
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-- 007_chat.sql
|
||||||
|
--
|
||||||
|
-- Chat attache a un dossier : chaque dossier possede son propre salon, et ses
|
||||||
|
-- membres sont les comptes qui ont acces a ce dossier (proprietaire, permission
|
||||||
|
-- nominative, dossier public pour tout compte authentifie, ou role admin).
|
||||||
|
--
|
||||||
|
-- Le salon suit la vie du dossier : `ON DELETE CASCADE` emporte les messages a
|
||||||
|
-- la purge definitive. Une mise a la corbeille est un simple `deleted_at`, donc
|
||||||
|
-- le chat est conserve tant que le dossier peut etre restaure.
|
||||||
|
--
|
||||||
|
-- L'auteur est reference par `user_id` (`ON DELETE SET NULL`) : la suppression
|
||||||
|
-- d'un compte ne doit jamais effacer l'historique. L'interface affiche
|
||||||
|
-- « Compte supprime » quand l'auteur n'existe plus.
|
||||||
|
|
||||||
|
CREATE TABLE chat_messages (
|
||||||
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
|
folder_id CHAR(36) NOT NULL,
|
||||||
|
user_id CHAR(36) NULL,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||||
|
deleted_at DATETIME(3) NULL,
|
||||||
|
PRIMARY KEY (id),
|
||||||
|
KEY idx_chat_messages_folder (folder_id, id),
|
||||||
|
KEY idx_chat_messages_user (user_id),
|
||||||
|
CONSTRAINT chk_chat_messages_body CHECK (CHAR_LENGTH(body) > 0 AND CHAR_LENGTH(body) <= 2000),
|
||||||
|
CONSTRAINT fk_chat_messages_folder FOREIGN KEY (folder_id) REFERENCES folders (id) ON DELETE CASCADE,
|
||||||
|
CONSTRAINT fk_chat_messages_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
@@ -5,6 +5,12 @@ import { clientIp as sharedClientIp, type Db, type SessionUser } from "./lib/ind
|
|||||||
* Les droits sont toujours recalcules depuis la session serveur. Le role de
|
* Les droits sont toujours recalcules depuis la session serveur. Le role de
|
||||||
* l'utilisateur ne vient jamais d'un en-tete client : une requete qui se
|
* l'utilisateur ne vient jamais d'un en-tete client : une requete qui se
|
||||||
* declare admin n'a aucun effet sur cette evaluation.
|
* declare admin n'a aucun effet sur cette evaluation.
|
||||||
|
*
|
||||||
|
* Le role `admin` ne donne aucun droit special sur les dossiers ni sur les
|
||||||
|
* fichiers : un administrateur n'accede qu'a ses propres dossiers et a ceux
|
||||||
|
* partages nominativement avec lui, exactement comme un compte ordinaire. Son
|
||||||
|
* role ne sert qu'au panneau d'administration. Consequence directe : il n'est
|
||||||
|
* membre que des salons de discussion des dossiers auxquels il a acces.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -19,7 +25,6 @@ export const READ_SQL = `( f.owner_id = ?
|
|||||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )`;
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )`;
|
||||||
|
|
||||||
export const canWrite = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
|
export const canWrite = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
|
||||||
if (user.role_slug === "admin") return true;
|
|
||||||
const row = await db.one(
|
const row = await db.one(
|
||||||
`SELECT 1 AS granted
|
`SELECT 1 AS granted
|
||||||
FROM folders f
|
FROM folders f
|
||||||
@@ -37,7 +42,6 @@ export const canWrite = async (db: Db, user: SessionUser, folderId: string): Pro
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const canRead = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
|
export const canRead = async (db: Db, user: SessionUser, folderId: string): Promise<boolean> => {
|
||||||
if (user.role_slug === "admin") return true;
|
|
||||||
const row = await db.one(
|
const row = await db.one(
|
||||||
`SELECT 1 AS granted
|
`SELECT 1 AS granted
|
||||||
FROM folders f
|
FROM folders f
|
||||||
@@ -64,7 +68,6 @@ export const canWriteExplicit = async (
|
|||||||
user: SessionUser,
|
user: SessionUser,
|
||||||
folderId: string,
|
folderId: string,
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
if (user.role_slug === "admin") return true;
|
|
||||||
const row = await db.one(
|
const row = await db.one(
|
||||||
`SELECT 1 AS granted
|
`SELECT 1 AS granted
|
||||||
FROM folders f
|
FROM folders f
|
||||||
@@ -81,8 +84,8 @@ export const canWriteExplicit = async (
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gestion du dossier (renommer, deplacer, supprimer, regler les permissions) :
|
* Gestion du dossier (renommer, deplacer, supprimer, regler les permissions,
|
||||||
* reservee au proprietaire ou a un administrateur. Un dossier public permet
|
* moderer le salon) : reservee au proprietaire. Un dossier public permet
|
||||||
* d'ajouter, pas de reorganiser l'espace commun.
|
* d'ajouter, pas de reorganiser l'espace commun.
|
||||||
*/
|
*/
|
||||||
export const canManageFolder = async (
|
export const canManageFolder = async (
|
||||||
@@ -90,7 +93,6 @@ export const canManageFolder = async (
|
|||||||
user: SessionUser,
|
user: SessionUser,
|
||||||
folderId: string,
|
folderId: string,
|
||||||
): Promise<boolean> => {
|
): Promise<boolean> => {
|
||||||
if (user.role_slug === "admin") return true;
|
|
||||||
const row = await db.one(
|
const row = await db.one(
|
||||||
`SELECT 1 AS granted FROM folders
|
`SELECT 1 AS granted FROM folders
|
||||||
WHERE id = ? AND deleted_at IS NULL AND owner_id = ? LIMIT 1`,
|
WHERE id = ? AND deleted_at IS NULL AND owner_id = ? LIMIT 1`,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { purgeExpiredSessions, startService } from "./lib/index.js";
|
|||||||
import { registerAccountRoutes } from "./routes/account.js";
|
import { registerAccountRoutes } from "./routes/account.js";
|
||||||
import { registerAdminRoutes } from "./routes/admin.js";
|
import { registerAdminRoutes } from "./routes/admin.js";
|
||||||
import { registerAuthRoutes } from "./routes/auth.js";
|
import { registerAuthRoutes } from "./routes/auth.js";
|
||||||
|
import { registerChatRoutes } from "./routes/chat.js";
|
||||||
import { registerFileRoutes } from "./routes/files.js";
|
import { registerFileRoutes } from "./routes/files.js";
|
||||||
import { registerFolderRoutes } from "./routes/folders.js";
|
import { registerFolderRoutes } from "./routes/folders.js";
|
||||||
import { registerMediaRoutes } from "./routes/media.js";
|
import { registerMediaRoutes } from "./routes/media.js";
|
||||||
@@ -21,6 +22,7 @@ void startService({
|
|||||||
routes: (app, { db, config }) => {
|
routes: (app, { db, config }) => {
|
||||||
registerAuthRoutes(app, db, config);
|
registerAuthRoutes(app, db, config);
|
||||||
registerAccountRoutes(app, db, config);
|
registerAccountRoutes(app, db, config);
|
||||||
|
registerChatRoutes(app, db, config);
|
||||||
registerFolderRoutes(app, db, config);
|
registerFolderRoutes(app, db, config);
|
||||||
registerFileRoutes(app, db, config);
|
registerFileRoutes(app, db, config);
|
||||||
registerMediaRoutes(app, db);
|
registerMediaRoutes(app, db);
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
import {
|
||||||
|
AppError,
|
||||||
|
createRateLimiter,
|
||||||
|
currentUser,
|
||||||
|
requireAuth,
|
||||||
|
type App,
|
||||||
|
type Config,
|
||||||
|
type Db,
|
||||||
|
} from "../lib/index.js";
|
||||||
|
import { audit, canManageFolder, canRead } from "../access.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chat attache a un dossier. Le salon ne se lit et ne s'ecrit qu'avec l'acces
|
||||||
|
* au dossier : le role global ne suffit jamais, `admin` compris.
|
||||||
|
*
|
||||||
|
* Les membres du salon sont exactement les comptes qui ont acces au dossier
|
||||||
|
* (proprietaire, permissions nominatives, dossier public). Un administrateur
|
||||||
|
* n'est donc membre que des salons des dossiers partages avec lui.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const uuid = z
|
||||||
|
.string()
|
||||||
|
.regex(
|
||||||
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||||
|
"Identifiant invalide.",
|
||||||
|
);
|
||||||
|
|
||||||
|
const sendInput = z.object({
|
||||||
|
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
|
||||||
|
});
|
||||||
|
|
||||||
|
interface MessageRow {
|
||||||
|
id: number;
|
||||||
|
user_id: string | null;
|
||||||
|
body: string;
|
||||||
|
created_at: string;
|
||||||
|
first_name: string | null;
|
||||||
|
last_name: string | null;
|
||||||
|
avatar_updated_at: Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Auteur joint a la ligne : meme jointure que la lecture, pour la reponse du POST. */
|
||||||
|
const SELECT_MESSAGE = `
|
||||||
|
SELECT m.id, m.user_id, m.body, m.created_at,
|
||||||
|
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
|
||||||
|
FROM chat_messages m
|
||||||
|
LEFT JOIN users u ON u.id = m.user_id
|
||||||
|
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
|
||||||
|
|
||||||
|
const publicMessage = (row: MessageRow) => ({
|
||||||
|
id: row.id,
|
||||||
|
user_id: row.user_id,
|
||||||
|
first_name: row.first_name,
|
||||||
|
last_name: row.last_name,
|
||||||
|
body: row.body,
|
||||||
|
created_at: row.created_at,
|
||||||
|
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
|
||||||
|
avatar_updated_at: row.avatar_updated_at,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||||
|
// Ecriture bornee par compte : le salon reste utilisable meme si un client
|
||||||
|
// s'emballe. La lecture (interrogation periodique) n'est pas limitee ici.
|
||||||
|
const limiter = createRateLimiter(20, 10_000);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le dossier doit exister et etre accessible : `canRead` rejette une session
|
||||||
|
* sans acces comme un dossier inexistant (404, pour ne rien confirmer).
|
||||||
|
*/
|
||||||
|
const assertFolder = async (
|
||||||
|
folderId: string,
|
||||||
|
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
|
||||||
|
if (!uuid.safeParse(folderId).success) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
|
||||||
|
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||||
|
[folderId],
|
||||||
|
);
|
||||||
|
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
return folder;
|
||||||
|
};
|
||||||
|
|
||||||
|
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
|
||||||
|
const user = currentUser(context);
|
||||||
|
const folderId = context.req.param("folderId") ?? "";
|
||||||
|
const folder = await assertFolder(folderId);
|
||||||
|
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
|
||||||
|
// Les membres sont ceux qui ont acces au dossier : proprietaire,
|
||||||
|
// permission nominative non expiree, et tous les comptes actifs si le
|
||||||
|
// dossier est public. Le role global ne compte pas.
|
||||||
|
const rows = await db.query<{
|
||||||
|
id: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
role_slug: string;
|
||||||
|
avatar_updated_at: Date | null;
|
||||||
|
last_login_at: string | null;
|
||||||
|
}>(
|
||||||
|
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
|
||||||
|
ua.updated_at AS avatar_updated_at, u.last_login_at
|
||||||
|
FROM users u
|
||||||
|
JOIN roles r ON r.id = u.role_id
|
||||||
|
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||||
|
WHERE u.deleted_at IS NULL AND u.is_active = 1
|
||||||
|
AND ( u.id = ?
|
||||||
|
OR ? = 1
|
||||||
|
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||||
|
WHERE fp.folder_id = ? AND fp.user_id = u.id
|
||||||
|
AND fp.level IN ('read', 'write', 'admin')
|
||||||
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||||
|
ORDER BY u.first_name ASC, u.last_name ASC`,
|
||||||
|
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
|
||||||
|
);
|
||||||
|
|
||||||
|
return context.json({
|
||||||
|
members: rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
first_name: row.first_name,
|
||||||
|
last_name: row.last_name,
|
||||||
|
role_slug: row.role_slug,
|
||||||
|
has_avatar: row.avatar_updated_at !== null,
|
||||||
|
avatar_updated_at: row.avatar_updated_at,
|
||||||
|
last_login_at: row.last_login_at,
|
||||||
|
is_self: row.id === user.id,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||||
|
const user = currentUser(context);
|
||||||
|
const folderId = context.req.param("folderId") ?? "";
|
||||||
|
await assertFolder(folderId);
|
||||||
|
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
|
||||||
|
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
|
||||||
|
const after = Math.max(0, Number(context.req.query("after")) || 0);
|
||||||
|
|
||||||
|
// `after` sert a la synchronisation incrementale (polling) : on ne remonte
|
||||||
|
// que les messages posterieurs au dernier connu, dans l'ordre du temps.
|
||||||
|
// Sans `after` : les `limit` derniers, remis dans l'ordre croissant.
|
||||||
|
const rows =
|
||||||
|
after > 0
|
||||||
|
? await db.query<MessageRow>(
|
||||||
|
`${SELECT_MESSAGE}
|
||||||
|
WHERE m.folder_id = ? AND m.deleted_at IS NULL AND m.id > ?
|
||||||
|
ORDER BY m.id ASC
|
||||||
|
LIMIT ${limit}`,
|
||||||
|
[folderId, after],
|
||||||
|
)
|
||||||
|
: (
|
||||||
|
await db.query<MessageRow>(
|
||||||
|
`${SELECT_MESSAGE}
|
||||||
|
WHERE m.folder_id = ? AND m.deleted_at IS NULL
|
||||||
|
ORDER BY m.id DESC
|
||||||
|
LIMIT ${limit}`,
|
||||||
|
[folderId],
|
||||||
|
)
|
||||||
|
).reverse();
|
||||||
|
|
||||||
|
return context.json({ messages: rows.map(publicMessage) });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||||
|
const user = currentUser(context);
|
||||||
|
const folderId = context.req.param("folderId") ?? "";
|
||||||
|
await assertFolder(folderId);
|
||||||
|
// Etre membre du salon suffit a ecrire : un acces `read` participe a la
|
||||||
|
// discussion, exactement comme le proprietaire.
|
||||||
|
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
|
||||||
|
if (!limiter.allow(user.id)) {
|
||||||
|
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||||
|
}
|
||||||
|
const parsed = sendInput.safeParse(await context.req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await db.exec(
|
||||||
|
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
|
||||||
|
[folderId, user.id, parsed.data.body],
|
||||||
|
);
|
||||||
|
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
|
||||||
|
return context.json({ message: publicMessage(row) }, 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete(
|
||||||
|
"/api/cloud/folders/:folderId/chat/messages/:id",
|
||||||
|
requireAuth,
|
||||||
|
async (context) => {
|
||||||
|
const user = currentUser(context);
|
||||||
|
const folderId = context.req.param("folderId") ?? "";
|
||||||
|
const id = Number(context.req.param("id"));
|
||||||
|
await assertFolder(folderId);
|
||||||
|
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||||
|
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||||
|
|
||||||
|
const row = await db.one<{ user_id: string | null }>(
|
||||||
|
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
|
||||||
|
[id, folderId],
|
||||||
|
);
|
||||||
|
// Auteur ou gestionnaire du dossier (proprietaire) : meme reponse qu'un
|
||||||
|
// message inexistant pour ne rien laisser deviner.
|
||||||
|
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
|
||||||
|
throw AppError.notFound("Message introuvable.");
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.exec("UPDATE chat_messages SET deleted_at = UTC_TIMESTAMP(3) WHERE id = ?", [id]);
|
||||||
|
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
|
||||||
|
return context.json({ ok: true });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
+39
-10
@@ -387,7 +387,7 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
|
|
||||||
// Contre l'IDOR : un dossier qui n'appartient pas a la session rend une
|
// Contre l'IDOR : un dossier qui n'appartient pas a la session rend une
|
||||||
// liste vide plutot que de confirmer son existence.
|
// liste vide plutot que de confirmer son existence.
|
||||||
if (folderId !== null && user.role_slug !== "admin" && !(await canRead(db, user, folderId))) {
|
if (folderId !== null && !(await canRead(db, user, folderId))) {
|
||||||
const readable = await db.one(
|
const readable = await db.one(
|
||||||
`SELECT 1 AS granted FROM folders f
|
`SELECT 1 AS granted FROM folders f
|
||||||
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
|
WHERE f.id = ? AND f.deleted_at IS NULL AND f.owner_id = ? LIMIT 1`,
|
||||||
@@ -412,13 +412,49 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
AND fp.level IN ('read', 'write', 'admin')
|
AND fp.level IN ('read', 'write', 'admin')
|
||||||
AND ( fp.expires_at IS NULL
|
AND ( fp.expires_at IS NULL
|
||||||
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||||
ORDER BY name`,
|
ORDER BY is_starred DESC, name`,
|
||||||
[folderId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
[folderId, 0, user.id, user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
return context.json({ folderId, files: rows.map(publicFile) });
|
return context.json({ folderId, files: rows.map(publicFile) });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Favoris : tous les fichiers etoiles accessibles a la session, tous dossiers
|
||||||
|
* confondus. Le filtre reprend exactement les droits de lecture de
|
||||||
|
* l'explorateur (proprietaire, dossier public, permission nominative), sans
|
||||||
|
* exception pour le role global.
|
||||||
|
*/
|
||||||
|
app.get("/api/cloud/favorites", requireAuth, async (context) => {
|
||||||
|
const user = currentUser(context);
|
||||||
|
const rows = await db.query<FileRow & { folder_name: string | null }>(
|
||||||
|
`SELECT fi.id, fi.folder_id, fi.name, fi.mime_type, fi.size_bytes, fi.checksum_sha256,
|
||||||
|
fi.relative_path, fi.owner_id, fi.is_starred, fi.download_count,
|
||||||
|
fi.created_at, fi.updated_at, fo.name AS folder_name
|
||||||
|
FROM files fi
|
||||||
|
LEFT JOIN folders fo ON fo.id = fi.folder_id
|
||||||
|
WHERE fi.deleted_at IS NULL
|
||||||
|
AND fi.is_starred = 1
|
||||||
|
AND ( fi.owner_id = ?
|
||||||
|
OR ( fi.folder_id IS NOT NULL
|
||||||
|
AND EXISTS ( SELECT 1 FROM folders f
|
||||||
|
WHERE f.id = fi.folder_id AND f.deleted_at IS NULL
|
||||||
|
AND f.access_type = 'public' ) )
|
||||||
|
OR ( fi.folder_id IS NOT NULL
|
||||||
|
AND EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||||
|
WHERE fp.folder_id = fi.folder_id AND fp.user_id = ?
|
||||||
|
AND fp.level IN ('read', 'write', 'admin')
|
||||||
|
AND ( fp.expires_at IS NULL
|
||||||
|
OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||||
|
ORDER BY fi.created_at DESC`,
|
||||||
|
[user.id, user.id],
|
||||||
|
);
|
||||||
|
|
||||||
|
return context.json({
|
||||||
|
files: rows.map((row) => ({ ...publicFile(row), folder_name: row.folder_name })),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
app.get("/api/cloud/files/:id/download", requireAuth, async (context) => {
|
app.get("/api/cloud/files/:id/download", requireAuth, async (context) => {
|
||||||
const user = currentUser(context);
|
const user = currentUser(context);
|
||||||
const rawId = context.req.param("id");
|
const rawId = context.req.param("id");
|
||||||
@@ -428,7 +464,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||||
|
|
||||||
const allowed =
|
const allowed =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||||
@@ -468,7 +503,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||||
|
|
||||||
const allowed =
|
const allowed =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||||
@@ -498,7 +532,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
if (!row) throw AppError.notFound("Image introuvable.");
|
if (!row) throw AppError.notFound("Image introuvable.");
|
||||||
|
|
||||||
const allowed =
|
const allowed =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||||
if (!allowed) throw AppError.notFound("Image introuvable.");
|
if (!allowed) throw AppError.notFound("Image introuvable.");
|
||||||
@@ -535,7 +568,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
|
|
||||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||||
const permitted =
|
const permitted =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
owner ||
|
owner ||
|
||||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||||
@@ -571,7 +603,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
|
|
||||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||||
const canLeave =
|
const canLeave =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
owner ||
|
owner ||
|
||||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||||
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
|
if (!canLeave) throw AppError.notFound("Fichier introuvable.");
|
||||||
@@ -607,7 +638,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||||
|
|
||||||
const allowed =
|
const allowed =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
(row.owner_id !== null && row.owner_id === user.id) ||
|
(row.owner_id !== null && row.owner_id === user.id) ||
|
||||||
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canRead(db, user, row.folder_id)));
|
||||||
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
if (!allowed) throw AppError.notFound("Fichier introuvable.");
|
||||||
@@ -627,7 +657,6 @@ export const registerFileRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
|
|
||||||
const owner = row.owner_id !== null && row.owner_id === user.id;
|
const owner = row.owner_id !== null && row.owner_id === user.id;
|
||||||
const permitted =
|
const permitted =
|
||||||
user.role_slug === "admin" ||
|
|
||||||
owner ||
|
owner ||
|
||||||
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
(row.folder_id !== null && (await canWriteExplicit(db, user, row.folder_id)));
|
||||||
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
if (!permitted) throw AppError.notFound("Fichier introuvable.");
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
|||||||
throw AppError.badRequest("Identifiant de dossier invalide.");
|
throw AppError.badRequest("Identifiant de dossier invalide.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user.role_slug !== "admin" && parentId !== null) {
|
if (parentId !== null) {
|
||||||
// Contre l'IDOR : on ne liste un dossier que si la session y a acces.
|
// Contre l'IDOR : on ne liste un dossier que si la session y a acces.
|
||||||
if (!(await canRead(db, user, parentId))) {
|
if (!(await canRead(db, user, parentId))) {
|
||||||
throw AppError.notFound("Dossier introuvable.");
|
throw AppError.notFound("Dossier introuvable.");
|
||||||
@@ -136,7 +136,7 @@ export const registerFolderRoutes = (app: App, db: Db, config: Config): void =>
|
|||||||
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
WHERE fp.folder_id = f.id AND fp.user_id = ?
|
||||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||||
ORDER BY f.name`,
|
ORDER BY f.name`,
|
||||||
[parentId, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
[parentId, 0, user.id, user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
return context.json({ parentId, folders: rows.map(publicFolder) });
|
return context.json({ parentId, folders: rows.map(publicFolder) });
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ export const registerMediaRoutes = (app: App, db: Db): void => {
|
|||||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||||
ORDER BY fi.created_at DESC
|
ORDER BY fi.created_at DESC
|
||||||
LIMIT ${limit} OFFSET ${offset}`,
|
LIMIT ${limit} OFFSET ${offset}`,
|
||||||
[kind, kind, user.role_slug === "admin" ? 1 : 0, user.id, user.id],
|
[kind, kind, 0, user.id, user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
return context.json({
|
return context.json({
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ export const registerSearchRoutes = (app: App, db: Db): void => {
|
|||||||
const user = currentUser(context);
|
const user = currentUser(context);
|
||||||
const q = (context.req.query("q") ?? "").trim();
|
const q = (context.req.query("q") ?? "").trim();
|
||||||
if (q.length < 1) throw AppError.badRequest("Indiquez un terme de recherche.");
|
if (q.length < 1) throw AppError.badRequest("Indiquez un terme de recherche.");
|
||||||
const admin = user.role_slug === "admin";
|
|
||||||
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
|
const pattern = `%${escapeLike(q).slice(0, 110)}%`;
|
||||||
|
|
||||||
const folders = await db.query<{
|
const folders = await db.query<{
|
||||||
@@ -52,7 +51,7 @@ export const registerSearchRoutes = (app: App, db: Db): void => {
|
|||||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||||
ORDER BY f.name
|
ORDER BY f.name
|
||||||
LIMIT ${LIMIT}`,
|
LIMIT ${LIMIT}`,
|
||||||
[pattern, admin ? 1 : 0, user.id, user.id],
|
[pattern, 0, user.id, user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
const files = await db.query<{
|
const files = await db.query<{
|
||||||
@@ -82,7 +81,7 @@ export const registerSearchRoutes = (app: App, db: Db): void => {
|
|||||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) ) )
|
||||||
ORDER BY fi.name
|
ORDER BY fi.name
|
||||||
LIMIT ${LIMIT}`,
|
LIMIT ${LIMIT}`,
|
||||||
[pattern, admin ? 1 : 0, user.id, user.id],
|
[pattern, 0, user.id, user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
return context.json({
|
return context.json({
|
||||||
|
|||||||
+16
-18
@@ -19,10 +19,10 @@ const uuid = z
|
|||||||
);
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* La corbeille se prete a l'echelle d'un utilisateur : un proprietaire voit ses
|
* La corbeille se prete a l'echelle d'un compte : chacun ne voit et ne gere
|
||||||
* propres elements supprimes, un administrateur voit tout. Un element supprime
|
* que ses propres elements supprimes. Un element supprime dont le parent est
|
||||||
* dont le parent est lui aussi supprime n'est pas liste : c'est la racine de la
|
* lui aussi supprime n'est pas liste : c'est la racine de la suppression qui
|
||||||
* suppression qui porte l'action.
|
* porte l'action.
|
||||||
*/
|
*/
|
||||||
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
const subtreeIds = async (db: Db, rootId: string): Promise<string[]> => {
|
||||||
const rows = await db.query<{ id: string }>(
|
const rows = await db.query<{ id: string }>(
|
||||||
@@ -157,7 +157,6 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
|
|
||||||
app.get("/api/cloud/trash", requireAuth, async (context) => {
|
app.get("/api/cloud/trash", requireAuth, async (context) => {
|
||||||
const user = currentUser(context);
|
const user = currentUser(context);
|
||||||
const admin = user.role_slug === "admin";
|
|
||||||
|
|
||||||
// Seuls les elements dont le parent n'est pas lui-meme supprime figurent en
|
// Seuls les elements dont le parent n'est pas lui-meme supprime figurent en
|
||||||
// tete de corbeille : le reste suit la suppression du parent.
|
// tete de corbeille : le reste suit la suppression du parent.
|
||||||
@@ -169,9 +168,9 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
WHERE f.deleted_at IS NOT NULL
|
WHERE f.deleted_at IS NOT NULL
|
||||||
AND f.is_system = 0
|
AND f.is_system = 0
|
||||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||||
AND ( ? = 1 OR f.owner_id = ? )
|
AND f.owner_id = ?
|
||||||
ORDER BY f.deleted_at DESC`,
|
ORDER BY f.deleted_at DESC`,
|
||||||
[admin ? 1 : 0, user.id],
|
[user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
const files = await db.query<TrashFileRow>(
|
const files = await db.query<TrashFileRow>(
|
||||||
@@ -181,9 +180,9 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||||
WHERE fi.deleted_at IS NOT NULL
|
WHERE fi.deleted_at IS NOT NULL
|
||||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||||
AND ( ? = 1 OR fi.owner_id = ? )
|
AND fi.owner_id = ?
|
||||||
ORDER BY fi.deleted_at DESC`,
|
ORDER BY fi.deleted_at DESC`,
|
||||||
[admin ? 1 : 0, user.id],
|
[user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
const retentionDays = await db.one<{ setting_value: string }>(
|
const retentionDays = await db.one<{ setting_value: string }>(
|
||||||
@@ -208,7 +207,7 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
if (!row) throw AppError.notFound("Dossier introuvable.");
|
if (!row) throw AppError.notFound("Dossier introuvable.");
|
||||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
if (row.owner_id !== user.id) {
|
||||||
throw AppError.notFound("Dossier introuvable.");
|
throw AppError.notFound("Dossier introuvable.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,7 +246,7 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
if (row.owner_id !== user.id) {
|
||||||
throw AppError.notFound("Fichier introuvable.");
|
throw AppError.notFound("Fichier introuvable.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,7 +274,7 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
if (!row) throw AppError.notFound("Dossier introuvable.");
|
if (!row) throw AppError.notFound("Dossier introuvable.");
|
||||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
if (row.owner_id !== user.id) {
|
||||||
throw AppError.notFound("Dossier introuvable.");
|
throw AppError.notFound("Dossier introuvable.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,7 +293,7 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
[id],
|
[id],
|
||||||
);
|
);
|
||||||
if (!row) throw AppError.notFound("Fichier introuvable.");
|
if (!row) throw AppError.notFound("Fichier introuvable.");
|
||||||
if (user.role_slug !== "admin" && row.owner_id !== user.id) {
|
if (row.owner_id !== user.id) {
|
||||||
throw AppError.notFound("Fichier introuvable.");
|
throw AppError.notFound("Fichier introuvable.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,23 +305,22 @@ export const registerTrashRoutes = (app: App, db: Db, config: Config): void => {
|
|||||||
/** Vide la corbeille du compte appelant (tous les elements purges). */
|
/** Vide la corbeille du compte appelant (tous les elements purges). */
|
||||||
app.delete("/api/cloud/trash", requireAuth, async (context) => {
|
app.delete("/api/cloud/trash", requireAuth, async (context) => {
|
||||||
const user = currentUser(context);
|
const user = currentUser(context);
|
||||||
const admin = user.role_slug === "admin";
|
|
||||||
|
|
||||||
const folders = await db.query<{ id: string }>(
|
const folders = await db.query<{ id: string }>(
|
||||||
`SELECT f.id FROM folders f
|
`SELECT f.id FROM folders f
|
||||||
LEFT JOIN folders p ON p.id = f.parent_id
|
LEFT JOIN folders p ON p.id = f.parent_id
|
||||||
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
WHERE f.deleted_at IS NOT NULL AND f.is_system = 0
|
||||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||||
AND ( ? = 1 OR f.owner_id = ? )`,
|
AND f.owner_id = ?`,
|
||||||
[admin ? 1 : 0, user.id],
|
[user.id],
|
||||||
);
|
);
|
||||||
const files = await db.query<{ id: string }>(
|
const files = await db.query<{ id: string }>(
|
||||||
`SELECT fi.id FROM files fi
|
`SELECT fi.id FROM files fi
|
||||||
LEFT JOIN folders p ON p.id = fi.folder_id
|
LEFT JOIN folders p ON p.id = fi.folder_id
|
||||||
WHERE fi.deleted_at IS NOT NULL
|
WHERE fi.deleted_at IS NOT NULL
|
||||||
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
AND (p.id IS NULL OR p.deleted_at IS NULL)
|
||||||
AND ( ? = 1 OR fi.owner_id = ? )`,
|
AND fi.owner_id = ?`,
|
||||||
[admin ? 1 : 0, user.id],
|
[user.id],
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
for (const folder of folders) await purgeFolderTree(db, config, folder.id);
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ DELETE FROM share_links;
|
|||||||
DELETE FROM files;
|
DELETE FROM files;
|
||||||
DELETE FROM folder_permissions;
|
DELETE FROM folder_permissions;
|
||||||
DELETE FROM folders;
|
DELETE FROM folders;
|
||||||
|
DELETE FROM chat_messages;
|
||||||
DELETE FROM user_avatars;
|
DELETE FROM user_avatars;
|
||||||
DELETE FROM password_reset_tokens;
|
DELETE FROM password_reset_tokens;
|
||||||
DELETE FROM email_change_requests;
|
DELETE FROM email_change_requests;
|
||||||
|
|||||||
+23
-2
@@ -67,6 +67,26 @@ d'adresse).
|
|||||||
| GET | `/api/cloud/search` | `requireAuth` |
|
| GET | `/api/cloud/search` | `requireAuth` |
|
||||||
| GET | `/api/cloud/media` | `requireAuth` |
|
| GET | `/api/cloud/media` | `requireAuth` |
|
||||||
|
|
||||||
|
### Discussion (chat d'un dossier et membres)
|
||||||
|
|
||||||
|
Chaque dossier possède son propre salon. Le droit d'accès au dossier fait loi :
|
||||||
|
lecture comme écriture passent par `canRead` (`backend/src/access.ts`), donc le
|
||||||
|
salon d'un dossier `public` est ouvert à tout compte authentifié. La lecture est
|
||||||
|
en texte brut, React échappe le rendu. La synchronisation est incrémentale par
|
||||||
|
identifiant (`after`), sans WebSocket.
|
||||||
|
|
||||||
|
| Méthode | Chemin | Garde |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/api/cloud/folders/:folderId/chat/members` | `requireAuth` + `canRead` |
|
||||||
|
| GET | `/api/cloud/folders/:folderId/chat/messages?after=&limit=` | `requireAuth` + `canRead` |
|
||||||
|
| POST | `/api/cloud/folders/:folderId/chat/messages` | `requireAuth` + `canRead` (limiteur 20 / 10 s par compte) |
|
||||||
|
| DELETE | `/api/cloud/folders/:folderId/chat/messages/:id` | `requireAuth` + `canRead` (auteur ou gestionnaire du dossier, soft-delete) |
|
||||||
|
|
||||||
|
`GET .../chat/members` renvoie les membres du salon, c'est-à-dire les comptes qui
|
||||||
|
ont accès au dossier : propriétaire, titulaires d'une permission nominative non
|
||||||
|
expirée, rôle global `admin`, et tous les comptes actifs si le dossier est
|
||||||
|
`public` (prénom, nom, rôle, présence d'avatar, `last_login_at`).
|
||||||
|
|
||||||
### Administration (`role_slug = admin`)
|
### Administration (`role_slug = admin`)
|
||||||
|
|
||||||
| Méthode | Chemin |
|
| Méthode | Chemin |
|
||||||
@@ -142,10 +162,11 @@ par fichier, dérive refusée au démarrage.
|
|||||||
| `004_cloud_requirements.sql` | `first_name`/`last_name`, `used_bytes`, `max_file_bytes`, `user_sessions`, `media_metadata`, `file_variants`, **suppression de `share_links`** |
|
| `004_cloud_requirements.sql` | `first_name`/`last_name`, `used_bytes`, `max_file_bytes`, `user_sessions`, `media_metadata`, `file_variants`, **suppression de `share_links`** |
|
||||||
| `005_storage_location_realign.sql` | réalignement des emplacements |
|
| `005_storage_location_realign.sql` | réalignement des emplacements |
|
||||||
| `006_public_folder.sql` | `folders.access_type` / `is_system`, dossier `Public` |
|
| `006_public_folder.sql` | `folders.access_type` / `is_system`, dossier `Public` |
|
||||||
|
| `007_chat.sql` | `chat_messages` (salon global, auteur `ON DELETE SET NULL`) |
|
||||||
|
|
||||||
Tables actives : `users, user_sessions, folders, folder_permissions, files,
|
Tables actives : `users, user_sessions, folders, folder_permissions, files,
|
||||||
media_metadata, file_variants, user_avatars, storage_locations, settings,
|
media_metadata, file_variants, user_avatars, chat_messages, storage_locations,
|
||||||
password_reset_tokens, email_change_requests, audit_logs`.
|
settings, password_reset_tokens, email_change_requests, audit_logs`.
|
||||||
|
|
||||||
## Erreurs métier
|
## Erreurs métier
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ResetPassword } from "./pages/ResetPassword.js";
|
|||||||
import { ConfirmEmail } from "./pages/ConfirmEmail.js";
|
import { ConfirmEmail } from "./pages/ConfirmEmail.js";
|
||||||
import { ChangePassword } from "./pages/ChangePassword.js";
|
import { ChangePassword } from "./pages/ChangePassword.js";
|
||||||
import { Browser } from "./pages/Browser.js";
|
import { Browser } from "./pages/Browser.js";
|
||||||
|
import { Favorites } from "./pages/Favorites.js";
|
||||||
import { Search } from "./pages/Search.js";
|
import { Search } from "./pages/Search.js";
|
||||||
import { Gallery } from "./pages/Gallery.js";
|
import { Gallery } from "./pages/Gallery.js";
|
||||||
import { Trash } from "./pages/Trash.js";
|
import { Trash } from "./pages/Trash.js";
|
||||||
@@ -52,6 +53,7 @@ export const App = () => (
|
|||||||
<Route element={<RequireReady />}>
|
<Route element={<RequireReady />}>
|
||||||
<Route element={<AppShell />}>
|
<Route element={<AppShell />}>
|
||||||
<Route path="/files" element={<Browser />} />
|
<Route path="/files" element={<Browser />} />
|
||||||
|
<Route path="/favorites" element={<Favorites />} />
|
||||||
<Route path="/search" element={<Search />} />
|
<Route path="/search" element={<Search />} />
|
||||||
<Route path="/gallery" element={<Gallery />} />
|
<Route path="/gallery" element={<Gallery />} />
|
||||||
<Route path="/trash" element={<Trash />} />
|
<Route path="/trash" element={<Trash />} />
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { NavLink, Outlet } from "react-router-dom";
|
import { NavLink, Outlet } from "react-router-dom";
|
||||||
import { Button, cn } from "../ui/index.js";
|
import { Button, cn } from "../ui/index.js";
|
||||||
import { api } from "../lib/api.js";
|
|
||||||
import { useSession } from "../lib/session.js";
|
import { useSession } from "../lib/session.js";
|
||||||
|
import { Avatar } from "./Avatar.js";
|
||||||
import {
|
import {
|
||||||
ActivityIcon,
|
ActivityIcon,
|
||||||
CloseIcon,
|
CloseIcon,
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
SearchNavIcon,
|
SearchNavIcon,
|
||||||
SettingsIcon,
|
SettingsIcon,
|
||||||
ShieldIcon,
|
ShieldIcon,
|
||||||
|
StarIcon,
|
||||||
TrashIcon,
|
TrashIcon,
|
||||||
} from "./icons.js";
|
} from "./icons.js";
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ interface NavItem {
|
|||||||
|
|
||||||
const NAV: NavItem[] = [
|
const NAV: NavItem[] = [
|
||||||
{ to: "/files", label: "Fichiers", icon: FolderIcon },
|
{ to: "/files", label: "Fichiers", icon: FolderIcon },
|
||||||
|
{ to: "/favorites", label: "Favoris", icon: StarIcon },
|
||||||
{ to: "/search", label: "Recherche", icon: SearchNavIcon },
|
{ to: "/search", label: "Recherche", icon: SearchNavIcon },
|
||||||
{ to: "/gallery", label: "Galerie", icon: ImageIcon },
|
{ to: "/gallery", label: "Galerie", icon: ImageIcon },
|
||||||
{ to: "/trash", label: "Corbeille", icon: TrashIcon },
|
{ to: "/trash", label: "Corbeille", icon: TrashIcon },
|
||||||
@@ -38,9 +40,6 @@ const ADMIN_NAV: NavItem[] = [
|
|||||||
|
|
||||||
const ACCOUNT_NAV: NavItem = { to: "/profile", label: "Mon compte", icon: SettingsIcon };
|
const ACCOUNT_NAV: NavItem = { to: "/profile", label: "Mon compte", icon: SettingsIcon };
|
||||||
|
|
||||||
const initials = (first: string, last: string): string =>
|
|
||||||
`${first.charAt(0)}${last.charAt(0)}`.toUpperCase() || "?";
|
|
||||||
|
|
||||||
const navClass = ({ isActive }: { isActive: boolean }) =>
|
const navClass = ({ isActive }: { isActive: boolean }) =>
|
||||||
cn(
|
cn(
|
||||||
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
|
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
|
||||||
@@ -127,22 +126,13 @@ export const AppShell = () => {
|
|||||||
{user.role_name}
|
{user.role_name}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span
|
<Avatar
|
||||||
className="relative flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface text-xs font-semibold text-foreground"
|
userId={user.id}
|
||||||
aria-hidden="true"
|
firstName={user.first_name}
|
||||||
>
|
lastName={user.last_name}
|
||||||
{initials(user.first_name, user.last_name)}
|
hasAvatar={user.has_avatar}
|
||||||
{user.has_avatar ? (
|
avatarUpdatedAt={user.avatar_updated_at}
|
||||||
<img
|
/>
|
||||||
src={`${api.avatarUrl(user.id)}?v=${encodeURIComponent(user.avatar_updated_at ?? "")}`}
|
|
||||||
alt=""
|
|
||||||
className="absolute inset-0 h-full w-full object-cover"
|
|
||||||
onError={(event) => {
|
|
||||||
event.currentTarget.style.display = "none";
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
</span>
|
|
||||||
<Button
|
<Button
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import { api } from "../lib/api.js";
|
||||||
|
import { cn } from "../ui/index.js";
|
||||||
|
|
||||||
|
const initials = (first: string, last: string): string =>
|
||||||
|
`${first.charAt(0)}${last.charAt(0)}`.toUpperCase() || "?";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pastille d'identite : initiales sur fond neutre, remplacees par la photo de
|
||||||
|
* profil quand elle existe. La version de la photo est passee en parametre
|
||||||
|
* pour invalider le cache navigateur des qu'elle change.
|
||||||
|
*/
|
||||||
|
export const Avatar = ({
|
||||||
|
userId,
|
||||||
|
firstName,
|
||||||
|
lastName,
|
||||||
|
hasAvatar,
|
||||||
|
avatarUpdatedAt,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
userId: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
hasAvatar: boolean;
|
||||||
|
avatarUpdatedAt: string | null;
|
||||||
|
className?: string;
|
||||||
|
}) => (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"relative flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface text-xs font-semibold text-foreground",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
{initials(firstName, lastName)}
|
||||||
|
{hasAvatar ? (
|
||||||
|
<img
|
||||||
|
src={`${api.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
|
||||||
|
alt=""
|
||||||
|
className="absolute inset-0 h-full w-full object-cover"
|
||||||
|
onError={(event) => {
|
||||||
|
event.currentTarget.style.display = "none";
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
@@ -0,0 +1,442 @@
|
|||||||
|
import {
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
type FormEvent,
|
||||||
|
type KeyboardEvent as ReactKeyboardEvent,
|
||||||
|
} from "react";
|
||||||
|
import { Button, Spinner, cn } from "../ui/index.js";
|
||||||
|
import { ApiError, api, formatDate, type ChatMember, type ChatMessage } from "../lib/api.js";
|
||||||
|
import { useSession } from "../lib/session.js";
|
||||||
|
import { useConfirm } from "./confirm.js";
|
||||||
|
import { Avatar } from "./Avatar.js";
|
||||||
|
import { IconAction } from "./IconAction.js";
|
||||||
|
import { Alert, Badge, EmptyState } from "./feedback.js";
|
||||||
|
import { ChatIcon, CloseIcon, SendIcon, TrashIcon, UsersIcon } from "./icons.js";
|
||||||
|
|
||||||
|
const MAX_LENGTH = 2000;
|
||||||
|
const POLL_MESSAGES_MS = 4000;
|
||||||
|
const POLL_MEMBERS_MS = 30_000;
|
||||||
|
const GROUP_WINDOW_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
const timeOf = (value: string): string =>
|
||||||
|
new Date(value).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" });
|
||||||
|
|
||||||
|
const dayOf = (value: string): string =>
|
||||||
|
new Date(value).toLocaleDateString("fr-FR", {
|
||||||
|
weekday: "long",
|
||||||
|
day: "numeric",
|
||||||
|
month: "long",
|
||||||
|
});
|
||||||
|
|
||||||
|
const isSameDay = (a: string, b: string): boolean =>
|
||||||
|
new Date(a).toDateString() === new Date(b).toDateString();
|
||||||
|
|
||||||
|
const fullName = (member: { first_name: string | null; last_name: string | null }): string =>
|
||||||
|
`${member.first_name ?? ""} ${member.last_name ?? ""}`.trim() || "Compte supprimé";
|
||||||
|
|
||||||
|
const MAX_ID = (list: ChatMessage[]): number =>
|
||||||
|
list.reduce((max, message) => Math.max(max, message.id), 0);
|
||||||
|
|
||||||
|
export interface ChatFolder {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Salon de discussion d'un dossier, ouvert en plein ecran par-dessus la vue
|
||||||
|
* des fichiers. Les membres sont les comptes ayant acces au dossier (le role
|
||||||
|
* admin n'ouvre aucun acces supplementaire) ; le serveur reevalue cet acces a
|
||||||
|
* chaque requete, l'interface ne fait que l'afficher.
|
||||||
|
*/
|
||||||
|
export const FolderChat = ({ folder, onClose }: { folder: ChatFolder; onClose: () => void }) => {
|
||||||
|
const { user } = useSession();
|
||||||
|
const confirm = useConfirm();
|
||||||
|
const folderId = folder.id;
|
||||||
|
|
||||||
|
const [members, setMembers] = useState<ChatMember[]>([]);
|
||||||
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
const [deletingId, setDeletingId] = useState<number | null>(null);
|
||||||
|
const [membersOpen, setMembersOpen] = useState(false);
|
||||||
|
|
||||||
|
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const lastIdRef = useRef(0);
|
||||||
|
// Tant que l'utilisateur reste au bas de la conversation, chaque nouveau
|
||||||
|
// message le ramene en bas ; s'il remonte lire l'historique, on ne le force
|
||||||
|
// pas a redescendre.
|
||||||
|
const stickToBottomRef = useRef(true);
|
||||||
|
|
||||||
|
const scrollToBottom = useCallback(() => {
|
||||||
|
const node = scrollRef.current;
|
||||||
|
if (node) node.scrollTop = node.scrollHeight;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const mergeMessages = useCallback(
|
||||||
|
(incoming: ChatMessage[]) => {
|
||||||
|
if (incoming.length === 0) return;
|
||||||
|
setMessages((previous) => {
|
||||||
|
const known = new Set(previous.map((message) => message.id));
|
||||||
|
const fresh = incoming.filter((message) => !known.has(message.id));
|
||||||
|
return fresh.length > 0 ? [...previous, ...fresh] : previous;
|
||||||
|
});
|
||||||
|
lastIdRef.current = Math.max(lastIdRef.current, MAX_ID(incoming));
|
||||||
|
if (stickToBottomRef.current) queueMicrotask(scrollToBottom);
|
||||||
|
},
|
||||||
|
[scrollToBottom],
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadMembers = useCallback(async () => {
|
||||||
|
const { members: list } = await api.chatMembers(folderId);
|
||||||
|
setMembers(list);
|
||||||
|
}, [folderId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
setLoading(true);
|
||||||
|
setMessages([]);
|
||||||
|
lastIdRef.current = 0;
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const [memberResult, messageResult] = await Promise.all([
|
||||||
|
api.chatMembers(folderId),
|
||||||
|
api.chatMessages(folderId, 0, 50),
|
||||||
|
]);
|
||||||
|
if (!active) return;
|
||||||
|
setMembers(memberResult.members);
|
||||||
|
setMessages(messageResult.messages);
|
||||||
|
lastIdRef.current = MAX_ID(messageResult.messages);
|
||||||
|
setError(null);
|
||||||
|
} catch (caught) {
|
||||||
|
if (!active) return;
|
||||||
|
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||||
|
} finally {
|
||||||
|
if (active) {
|
||||||
|
setLoading(false);
|
||||||
|
queueMicrotask(scrollToBottom);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [folderId, scrollToBottom]);
|
||||||
|
|
||||||
|
// Synchronisation incrementale : rien n'est charge tant que l'onglet est en
|
||||||
|
// arriere-plan, la reprise se fait au retour de visibilite.
|
||||||
|
useEffect(() => {
|
||||||
|
const poll = async () => {
|
||||||
|
if (document.hidden) return;
|
||||||
|
try {
|
||||||
|
const { messages: fresh } = await api.chatMessages(folderId, lastIdRef.current, 100);
|
||||||
|
mergeMessages(fresh);
|
||||||
|
} catch {
|
||||||
|
/* le prochain cycle retentera */
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onVisible = () => {
|
||||||
|
if (!document.hidden) void poll();
|
||||||
|
};
|
||||||
|
const timer = window.setInterval(() => void poll(), POLL_MESSAGES_MS);
|
||||||
|
document.addEventListener("visibilitychange", onVisible);
|
||||||
|
return () => {
|
||||||
|
window.clearInterval(timer);
|
||||||
|
document.removeEventListener("visibilitychange", onVisible);
|
||||||
|
};
|
||||||
|
}, [folderId, mergeMessages]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = window.setInterval(() => {
|
||||||
|
if (!document.hidden) void loadMembers().catch(() => undefined);
|
||||||
|
}, POLL_MEMBERS_MS);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [loadMembers]);
|
||||||
|
|
||||||
|
// Fermeture au clavier et blocage du defilement de la page sous l'overlay.
|
||||||
|
useEffect(() => {
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === "Escape") onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKeyDown);
|
||||||
|
const previousOverflow = document.body.style.overflow;
|
||||||
|
document.body.style.overflow = "hidden";
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("keydown", onKeyDown);
|
||||||
|
document.body.style.overflow = previousOverflow;
|
||||||
|
};
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
const onScroll = () => {
|
||||||
|
const node = scrollRef.current;
|
||||||
|
if (!node) return;
|
||||||
|
stickToBottomRef.current = node.scrollHeight - node.scrollTop - node.clientHeight < 80;
|
||||||
|
};
|
||||||
|
|
||||||
|
const send = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const body = draft.trim();
|
||||||
|
if (!body || sending) return;
|
||||||
|
setSending(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const { message } = await api.chatSend(folderId, body);
|
||||||
|
stickToBottomRef.current = true;
|
||||||
|
mergeMessages([message]);
|
||||||
|
setDraft("");
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof ApiError ? caught.message : "Envoi impossible.");
|
||||||
|
} finally {
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = async (message: ChatMessage) => {
|
||||||
|
if (
|
||||||
|
!(await confirm({
|
||||||
|
title: "Supprimer le message",
|
||||||
|
message: "Ce message sera retiré du salon pour tout le monde.",
|
||||||
|
confirmLabel: "Supprimer",
|
||||||
|
tone: "danger",
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
setDeletingId(message.id);
|
||||||
|
try {
|
||||||
|
await api.chatDeleteMessage(folderId, message.id);
|
||||||
|
setMessages((previous) => previous.filter((item) => item.id !== message.id));
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof ApiError ? caught.message : "Suppression impossible.");
|
||||||
|
} finally {
|
||||||
|
setDeletingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onComposerKeyDown = (event: ReactKeyboardEvent<HTMLTextAreaElement>) => {
|
||||||
|
if (event.key === "Enter" && !event.shiftKey) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.currentTarget.form?.requestSubmit();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const rendered = useMemo(
|
||||||
|
() =>
|
||||||
|
messages.map((message, index) => {
|
||||||
|
const previous = index > 0 ? messages[index - 1] : null;
|
||||||
|
const newDay = !previous || !isSameDay(previous.created_at, message.created_at);
|
||||||
|
const continuation =
|
||||||
|
!newDay &&
|
||||||
|
previous !== null &&
|
||||||
|
previous.user_id === message.user_id &&
|
||||||
|
new Date(message.created_at).getTime() - new Date(previous.created_at).getTime() <
|
||||||
|
GROUP_WINDOW_MS;
|
||||||
|
const own = message.user_id === user?.id;
|
||||||
|
const canDelete = own;
|
||||||
|
return { message, newDay, continuation, own, canDelete };
|
||||||
|
}),
|
||||||
|
[messages, user?.id],
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-40 flex flex-col bg-background">
|
||||||
|
<div className="relative flex h-full min-h-0">
|
||||||
|
<aside
|
||||||
|
className={cn(
|
||||||
|
"absolute inset-y-0 left-0 z-20 flex w-64 flex-col border-r border-border bg-surface transition-transform md:static md:z-auto md:translate-x-0",
|
||||||
|
membersOpen ? "translate-x-0 shadow-lg md:shadow-none" : "-translate-x-full",
|
||||||
|
)}
|
||||||
|
aria-label="Membres du dossier"
|
||||||
|
>
|
||||||
|
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-border px-4 py-3">
|
||||||
|
<span className="font-display text-xs font-semibold uppercase tracking-label text-foreground">
|
||||||
|
Membres
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-subtle-foreground">{members.length}</span>
|
||||||
|
</div>
|
||||||
|
<ul className="min-h-0 flex-1 overflow-y-auto p-2">
|
||||||
|
{members.map((member) => (
|
||||||
|
<li key={member.id} className="flex items-center gap-3 rounded-md px-2 py-2">
|
||||||
|
<Avatar
|
||||||
|
userId={member.id}
|
||||||
|
firstName={member.first_name}
|
||||||
|
lastName={member.last_name}
|
||||||
|
hasAvatar={member.has_avatar}
|
||||||
|
avatarUpdatedAt={member.avatar_updated_at}
|
||||||
|
className="h-8 w-8"
|
||||||
|
/>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="flex items-center gap-1.5 truncate text-xs font-medium text-foreground">
|
||||||
|
{fullName(member)}
|
||||||
|
{member.is_self ? (
|
||||||
|
<span className="text-subtle-foreground">(vous)</span>
|
||||||
|
) : null}
|
||||||
|
</p>
|
||||||
|
<p className="truncate text-[0.6875rem] text-subtle-foreground">
|
||||||
|
{member.last_login_at
|
||||||
|
? `Dernière connexion le ${formatDate(member.last_login_at)}`
|
||||||
|
: "Jamais connecté"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{member.role_slug === "admin" ? <Badge tone="accent">Admin</Badge> : null}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{membersOpen ? (
|
||||||
|
<div
|
||||||
|
className="absolute inset-0 z-10 bg-black/30 md:hidden"
|
||||||
|
onClick={() => setMembersOpen(false)}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<section className="flex min-w-0 flex-1 flex-col">
|
||||||
|
<div className="flex shrink-0 items-center gap-3 border-b border-border bg-background px-4 py-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-muted-foreground md:hidden"
|
||||||
|
aria-label={membersOpen ? "Masquer les membres" : "Afficher les membres"}
|
||||||
|
aria-expanded={membersOpen}
|
||||||
|
onClick={() => setMembersOpen((value) => !value)}
|
||||||
|
>
|
||||||
|
<UsersIcon className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<h1 className="truncate font-display text-sm font-semibold uppercase tracking-label text-foreground">
|
||||||
|
Discussion · {folder.name}
|
||||||
|
</h1>
|
||||||
|
<p className="text-[0.6875rem] text-subtle-foreground">
|
||||||
|
Membres ayant accès à ce dossier
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="Fermer la discussion"
|
||||||
|
className="rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
|
||||||
|
>
|
||||||
|
<CloseIcon className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error ? (
|
||||||
|
<div className="shrink-0 px-4 pt-3">
|
||||||
|
<Alert>{error}</Alert>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div
|
||||||
|
ref={scrollRef}
|
||||||
|
onScroll={onScroll}
|
||||||
|
className="min-h-0 flex-1 overflow-y-auto px-4 py-4"
|
||||||
|
>
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center py-16">
|
||||||
|
<Spinner size="md" />
|
||||||
|
</div>
|
||||||
|
) : messages.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
icon={<ChatIcon className="h-8 w-8" />}
|
||||||
|
title="Aucun message"
|
||||||
|
description="Lancez la discussion : les membres du dossier verront votre message."
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ol className="flex flex-col gap-1">
|
||||||
|
{rendered.map(({ message, newDay, continuation, own, canDelete }) => (
|
||||||
|
<li key={message.id}>
|
||||||
|
{newDay ? (
|
||||||
|
<div className="my-3 flex items-center gap-3" role="separator">
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
<span className="font-display text-[0.625rem] font-semibold uppercase tracking-label text-subtle-foreground">
|
||||||
|
{dayOf(message.created_at)}
|
||||||
|
</span>
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"group flex items-start gap-3 rounded-md px-2 py-1.5 hover:bg-surface-hover",
|
||||||
|
continuation && "mt-0",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{continuation ? (
|
||||||
|
<span className="w-9 shrink-0" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Avatar
|
||||||
|
userId={message.user_id ?? message.first_name ?? "unknown"}
|
||||||
|
firstName={message.first_name ?? "?"}
|
||||||
|
lastName={message.last_name ?? ""}
|
||||||
|
hasAvatar={message.has_avatar}
|
||||||
|
avatarUpdatedAt={message.avatar_updated_at}
|
||||||
|
className="h-9 w-9"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
{continuation ? null : (
|
||||||
|
<p className="flex items-center gap-2 text-xs">
|
||||||
|
<span
|
||||||
|
className={cn("font-medium", own ? "text-accent" : "text-foreground")}
|
||||||
|
>
|
||||||
|
{fullName(message)}
|
||||||
|
</span>
|
||||||
|
<span className="text-[0.6875rem] text-subtle-foreground">
|
||||||
|
{timeOf(message.created_at)}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed text-foreground">
|
||||||
|
{message.body}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{canDelete ? (
|
||||||
|
<span className="opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
|
||||||
|
<IconAction
|
||||||
|
label="Supprimer le message"
|
||||||
|
tone="danger"
|
||||||
|
isLoading={deletingId === message.id}
|
||||||
|
icon={<TrashIcon className="h-3.5 w-3.5" />}
|
||||||
|
onClick={() => void remove(message)}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form
|
||||||
|
onSubmit={(event) => void send(event)}
|
||||||
|
className="flex shrink-0 items-end gap-2 border-t border-border bg-background px-4 py-3"
|
||||||
|
>
|
||||||
|
<textarea
|
||||||
|
value={draft}
|
||||||
|
onChange={(event) => setDraft(event.target.value.slice(0, MAX_LENGTH))}
|
||||||
|
onKeyDown={onComposerKeyDown}
|
||||||
|
rows={1}
|
||||||
|
maxLength={MAX_LENGTH}
|
||||||
|
placeholder="Écrire un message… (Entrée pour envoyer, Maj+Entrée pour retour à la ligne)"
|
||||||
|
aria-label="Votre message"
|
||||||
|
className="max-h-40 min-h-[2.5rem] flex-1 resize-y rounded-sm border border-border-control bg-surface px-3 py-2 text-sm text-foreground placeholder:text-subtle-foreground focus-visible:border-border-strong focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="md"
|
||||||
|
isLoading={sending}
|
||||||
|
disabled={draft.trim().length === 0}
|
||||||
|
iconLeading={<SendIcon className="h-4 w-4" />}
|
||||||
|
>
|
||||||
|
<span className="hidden sm:inline">Envoyer</span>
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -191,3 +191,17 @@ export const MoveIcon = (props: IconProps) => (
|
|||||||
<path d="m9 7 3-3 3 3M9 17l3 3 3-3M7 9l-3 3 3 3M17 9l3 3-3 3" />
|
<path d="m9 7 3-3 3 3M9 17l3 3 3-3M7 9l-3 3 3 3M17 9l3 3-3 3" />
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const ChatIcon = (props: IconProps) => (
|
||||||
|
<svg {...base(props)}>
|
||||||
|
<path d="M20 15.5a1.5 1.5 0 0 1-1.5 1.5H8l-4 3.5V6.5A1.5 1.5 0 0 1 5.5 5h13A1.5 1.5 0 0 1 20 6.5Z" />
|
||||||
|
<path d="M8 9.5h8M8 13h5" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
|
||||||
|
export const SendIcon = (props: IconProps) => (
|
||||||
|
<svg {...base(props)}>
|
||||||
|
<path d="M4.5 12 20 4.5 15 20l-3.5-6.5L4.5 12Z" />
|
||||||
|
<path d="m11.5 13.5 4-4" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
|||||||
@@ -39,6 +39,10 @@ export interface UploadedFile {
|
|||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface FavoriteFile extends UploadedFile {
|
||||||
|
folder_name: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface FolderPermission {
|
export interface FolderPermission {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
email: string;
|
email: string;
|
||||||
@@ -145,6 +149,28 @@ export interface AuditEntry {
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ChatMember {
|
||||||
|
id: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
role_slug: string;
|
||||||
|
has_avatar: boolean;
|
||||||
|
avatar_updated_at: string | null;
|
||||||
|
last_login_at: string | null;
|
||||||
|
is_self: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatMessage {
|
||||||
|
id: number;
|
||||||
|
user_id: string | null;
|
||||||
|
first_name: string | null;
|
||||||
|
last_name: string | null;
|
||||||
|
body: string;
|
||||||
|
created_at: string;
|
||||||
|
has_avatar: boolean;
|
||||||
|
avatar_updated_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
readonly status: number;
|
readonly status: number;
|
||||||
|
|
||||||
@@ -291,6 +317,7 @@ export const api = {
|
|||||||
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
|
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
|
||||||
starFile: (id: string) =>
|
starFile: (id: string) =>
|
||||||
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
|
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
|
||||||
|
favorites: () => request<{ files: FavoriteFile[] }>("/favorites"),
|
||||||
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
|
deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`),
|
||||||
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
|
downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`,
|
||||||
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
|
thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`,
|
||||||
@@ -314,6 +341,18 @@ export const api = {
|
|||||||
`/media${query({ kind, limit, offset })}`,
|
`/media${query({ kind, limit, offset })}`,
|
||||||
),
|
),
|
||||||
|
|
||||||
|
// --- Chat d'un dossier ------------------------------------------------
|
||||||
|
chatMembers: (folderId: string) =>
|
||||||
|
request<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
|
||||||
|
chatMessages: (folderId: string, after = 0, limit = 50) =>
|
||||||
|
request<{ messages: ChatMessage[] }>(
|
||||||
|
`/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit })}`,
|
||||||
|
),
|
||||||
|
chatSend: (folderId: string, body: string) =>
|
||||||
|
post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }),
|
||||||
|
chatDeleteMessage: (folderId: string, id: number) =>
|
||||||
|
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
|
||||||
|
|
||||||
// --- Administration ----------------------------------------------------
|
// --- Administration ----------------------------------------------------
|
||||||
adminStats: () => request<AdminStats>("/admin/stats"),
|
adminStats: () => request<AdminStats>("/admin/stats"),
|
||||||
adminUsers: (q?: string) =>
|
adminUsers: (q?: string) =>
|
||||||
|
|||||||
@@ -8,11 +8,12 @@ import {
|
|||||||
type UploadedFile,
|
type UploadedFile,
|
||||||
} from "../lib/api.js";
|
} from "../lib/api.js";
|
||||||
import { useSession } from "../lib/session.js";
|
import { useSession } from "../lib/session.js";
|
||||||
import { Alert, Badge, EmptyState, PageHeader } from "../components/feedback.js";
|
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||||
import { useConfirm } from "../components/confirm.js";
|
import { useConfirm } from "../components/confirm.js";
|
||||||
import { MediaViewer } from "../components/MediaViewer.js";
|
import { MediaViewer } from "../components/MediaViewer.js";
|
||||||
import { MediaThumb } from "../components/MediaThumb.js";
|
import { MediaThumb } from "../components/MediaThumb.js";
|
||||||
import { IconAction } from "../components/IconAction.js";
|
import { IconAction } from "../components/IconAction.js";
|
||||||
|
import { FolderChat, type ChatFolder } from "../components/FolderChat.js";
|
||||||
import {
|
import {
|
||||||
CreateFolderDialog,
|
CreateFolderDialog,
|
||||||
MoveDialog,
|
MoveDialog,
|
||||||
@@ -21,6 +22,7 @@ import {
|
|||||||
} from "../components/dialogs.js";
|
} from "../components/dialogs.js";
|
||||||
import {
|
import {
|
||||||
ArrowLeftIcon,
|
ArrowLeftIcon,
|
||||||
|
ChatIcon,
|
||||||
DownloadIcon,
|
DownloadIcon,
|
||||||
FolderIcon,
|
FolderIcon,
|
||||||
MoveIcon,
|
MoveIcon,
|
||||||
@@ -58,6 +60,7 @@ export const Browser = () => {
|
|||||||
const [removing, setRemoving] = useState<string | null>(null);
|
const [removing, setRemoving] = useState<string | null>(null);
|
||||||
const [dialog, setDialog] = useState<Dialog>(null);
|
const [dialog, setDialog] = useState<Dialog>(null);
|
||||||
const [viewer, setViewer] = useState<number | null>(null);
|
const [viewer, setViewer] = useState<number | null>(null);
|
||||||
|
const [chat, setChat] = useState<ChatFolder | null>(null);
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
const current = path[path.length - 1] ?? { id: null, name: "Racine" };
|
const current = path[path.length - 1] ?? { id: null, name: "Racine" };
|
||||||
@@ -203,6 +206,17 @@ export const Browser = () => {
|
|||||||
))}
|
))}
|
||||||
</ol>
|
</ol>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
{current.id ? (
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
iconLeading={<ChatIcon className="h-3.5 w-3.5" />}
|
||||||
|
onClick={() => setChat({ id: current.id as string, name: current.name })}
|
||||||
|
>
|
||||||
|
Discussion
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -292,17 +306,16 @@ export const Browser = () => {
|
|||||||
<span className="block truncate text-sm font-medium text-foreground">
|
<span className="block truncate text-sm font-medium text-foreground">
|
||||||
{folder.name}
|
{folder.name}
|
||||||
</span>
|
</span>
|
||||||
<span className="mt-0.5 flex items-center gap-2">
|
<span className="mt-0.5 block text-[0.6875rem] text-subtle-foreground">
|
||||||
{folder.is_system ? <Badge>Système</Badge> : null}
|
{new Date(folder.created_at).toLocaleDateString("fr-FR")}
|
||||||
{folder.access_type === "public" ? (
|
|
||||||
<Badge tone="accent">Public</Badge>
|
|
||||||
) : null}
|
|
||||||
<span className="text-[0.6875rem] text-subtle-foreground">
|
|
||||||
{new Date(folder.created_at).toLocaleDateString("fr-FR")}
|
|
||||||
</span>
|
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
|
<IconAction
|
||||||
|
label={`Discussion ${folder.name}`}
|
||||||
|
icon={<ChatIcon className="h-4 w-4" />}
|
||||||
|
onClick={() => setChat({ id: folder.id, name: folder.name })}
|
||||||
|
/>
|
||||||
{canWrite ? (
|
{canWrite ? (
|
||||||
<div className="flex shrink-0 items-center gap-0.5">
|
<div className="flex shrink-0 items-center gap-0.5">
|
||||||
<IconAction
|
<IconAction
|
||||||
@@ -475,6 +488,10 @@ export const Browser = () => {
|
|||||||
onClose={() => setViewer(null)}
|
onClose={() => setViewer(null)}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{chat ? (
|
||||||
|
<FolderChat key={chat.id} folder={chat} onClose={() => setChat(null)} />
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Spinner } from "../ui/index.js";
|
||||||
|
import { ApiError, api, formatBytes, type FavoriteFile } from "../lib/api.js";
|
||||||
|
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||||
|
import { MediaViewer } from "../components/MediaViewer.js";
|
||||||
|
import { MediaThumb } from "../components/MediaThumb.js";
|
||||||
|
import { IconAction } from "../components/IconAction.js";
|
||||||
|
import { DownloadIcon, FolderIcon, StarIcon } from "../components/icons.js";
|
||||||
|
|
||||||
|
export const Favorites = () => {
|
||||||
|
const [files, setFiles] = useState<FavoriteFile[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [viewer, setViewer] = useState<number | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLoading(true);
|
||||||
|
void api
|
||||||
|
.favorites()
|
||||||
|
.then(({ files: list }) => {
|
||||||
|
setFiles(list);
|
||||||
|
setError(null);
|
||||||
|
})
|
||||||
|
.catch((caught: unknown) => {
|
||||||
|
setError(caught instanceof ApiError ? caught.message : "Chargement impossible.");
|
||||||
|
setFiles([]);
|
||||||
|
})
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const unstar = async (file: FavoriteFile) => {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await api.starFile(file.id);
|
||||||
|
setFiles((previous) => previous.filter((item) => item.id !== file.id));
|
||||||
|
} catch (caught) {
|
||||||
|
setError(caught instanceof ApiError ? caught.message : "Action impossible.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-5">
|
||||||
|
<PageHeader
|
||||||
|
title="Favoris"
|
||||||
|
description="Les fichiers que vous avez étoilés, tous dossiers confondus."
|
||||||
|
/>
|
||||||
|
|
||||||
|
{error ? <Alert>{error}</Alert> : null}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex justify-center py-16">
|
||||||
|
<Spinner size="md" />
|
||||||
|
</div>
|
||||||
|
) : files.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
icon={<StarIcon className="h-8 w-8" />}
|
||||||
|
title="Aucun favori"
|
||||||
|
description="Étoilez un fichier dans l'explorateur pour le retrouver ici."
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<ul className="flex flex-col divide-y divide-border rounded-lg border border-border bg-surface">
|
||||||
|
{files.map((file, index) => (
|
||||||
|
<li key={file.id} className="flex items-center gap-2 px-3 py-2.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setViewer(index)}
|
||||||
|
className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-sm border border-border bg-surface-muted text-muted-foreground transition-colors hover:border-border-strong focus-visible:ring-ring focus-visible:ring-2 focus-visible:outline-none"
|
||||||
|
aria-label={`Aperçu de ${file.name}`}
|
||||||
|
>
|
||||||
|
<MediaThumb id={file.id} mime={file.mime_type} name={file.name} />
|
||||||
|
</button>
|
||||||
|
<span className="min-w-0 flex-1">
|
||||||
|
<span className="block truncate text-sm font-medium text-foreground">
|
||||||
|
{file.name}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-1.5 text-[0.6875rem] text-subtle-foreground">
|
||||||
|
<FolderIcon className="h-3 w-3 shrink-0" />
|
||||||
|
<span className="truncate">{file.folder_name ?? "Racine"}</span>
|
||||||
|
<span aria-hidden="true">·</span>
|
||||||
|
<span className="shrink-0">{formatBytes(file.size_bytes)}</span>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<IconAction
|
||||||
|
label={`Retirer l'étoile de ${file.name}`}
|
||||||
|
icon={<StarIcon className="h-4 w-4" filled />}
|
||||||
|
onClick={() => void unstar(file)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<a
|
||||||
|
href={api.downloadUrl(file.id)}
|
||||||
|
download={file.name}
|
||||||
|
className="inline-flex h-8 items-center gap-1.5 rounded-sm border border-border-strong bg-surface px-3 font-display text-[0.6875rem] font-semibold uppercase tracking-label text-foreground transition-colors hover:bg-surface-hover"
|
||||||
|
>
|
||||||
|
<DownloadIcon className="h-3.5 w-3.5" />
|
||||||
|
<span className="hidden sm:inline">Télécharger</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{viewer !== null ? (
|
||||||
|
<MediaViewer
|
||||||
|
items={files.map((item) => ({
|
||||||
|
id: item.id,
|
||||||
|
name: item.name,
|
||||||
|
mime_type: item.mime_type,
|
||||||
|
}))}
|
||||||
|
startIndex={viewer}
|
||||||
|
onClose={() => setViewer(null)}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user