import { getLanguage, getLocale } from "./locale"; export type Theme = "system" | "light" | "dark"; export type Language = "fr" | "en"; export interface User { id: string; email: string; first_name: string; last_name: string; role_slug: string; role_name: string; quota_bytes: number; used_bytes: number; max_file_bytes: number; must_change_password: boolean; theme: Theme; language: Language; has_avatar: boolean; avatar_updated_at: string | null; } export interface Folder { id: string; parent_id: string | null; name: string; owner_id: string | null; access_type: string; is_system: boolean; created_at: string; updated_at: string; } export interface UploadedFile { id: string; folder_id: string | null; name: string; mime_type: string | null; size_bytes: number; checksum_sha256: string | null; owner_id: string | null; is_starred: boolean; download_count: number; created_at: string; updated_at: string; } export interface FavoriteFile extends UploadedFile { folder_name: string | null; } export interface FolderPermission { user_id: string; email: string; first_name: string; last_name: string; level: string; expires_at: string | null; created_at: string; } export interface SessionInfo { id: string; ip_address: string | null; user_agent: string | null; created_at: string; last_seen_at: string; expires_at: string; current: boolean; } export interface TrashFolder { id: string; parent_id: string | null; name: string; owner_id: string | null; access_type: string; created_at: string; updated_at: string; deleted_at: string; } export interface TrashFile { id: string; folder_id: string | null; name: string; mime_type: string | null; size_bytes: number; owner_id: string | null; created_at: string; updated_at: string; deleted_at: string; } export interface MediaItem { id: string; folder_id: string | null; name: string; mime_type: string | null; size_bytes: number; owner_id: string | null; is_starred: boolean; kind: string | null; width: number | null; height: number | null; created_at: string; has_thumbnail: boolean; } export interface AdminUser { id: string; email: string; first_name: string; last_name: string; role_slug: string; quota_bytes: number; used_bytes: number; max_file_bytes: number; is_active: boolean; must_change_password: boolean; last_login_at: string | null; created_at: string; } export interface StorageLocation { id: number; name: string; slug: string; mount_path: string; quota_bytes: number | null; used_bytes: number; is_active: boolean; created_at: string; } export interface AdminStats { users: number; folders: number; files: number; usedBytes: number; trashFiles: number; locations: { id: number; name: string; used_bytes: number; quota_bytes: number | null }[]; } export interface AuditEntry { id: number; user_id: string | null; user_email: string | null; action: string; resource: string; resource_id: string | null; details: string | null; ip_address: string | null; 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; edited_at: string | null; is_pinned: boolean; has_avatar: boolean; avatar_updated_at: string | null; } export interface DirectoryUser { id: string; first_name: string; last_name: string; email: string; has_avatar: boolean; avatar_updated_at: string | null; } export class ApiError extends Error { readonly status: number; constructor(status: number, message: string) { super(message); this.name = "ApiError"; this.status = status; } } const BASE = "/api/cloud"; const messageOf = (body: unknown, fallback: string): string => (body as { error?: { message?: string } } | null)?.error?.message ?? fallback; /** * Un seul point d'entree HTTP. Le cookie de session est envoye * automatiquement (same-origin), et toute erreur non-2xx devient une * ApiError portant le message serveur, jamais un corps brut. */ const request = async (path: string, init?: RequestInit): Promise => { let response: Response; try { response = await fetch(`${BASE}${path}`, { credentials: "same-origin", ...init, headers: { ...(init?.body ? { "content-type": "application/json" } : {}), ...init?.headers, }, }); } catch { throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); } const body: unknown = await response.json().catch(() => null); if (!response.ok) throw new ApiError(response.status, messageOf(body, "Une erreur est survenue.")); return body as T; }; const post = (path: string, payload?: unknown): Promise => request(path, { method: "POST", ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), }); const patch = (path: string, payload: unknown): Promise => request(path, { method: "PATCH", body: JSON.stringify(payload) }); const put = (path: string, payload?: unknown): Promise => request(path, { method: "PUT", ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), }); const del = (path: string): Promise => request(path, { method: "DELETE" }); const query = (params: Record): string => { const search = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value !== null && value !== undefined && value !== "") search.set(key, String(value)); } const suffix = search.toString(); return suffix ? `?${suffix}` : ""; }; /** Envoi d'un corps brut (fichier, image), hors JSON. */ const putBinary = async (path: string, body: BodyInit, type: string): Promise => { let response: Response; try { response = await fetch(`${BASE}${path}`, { method: "PUT", credentials: "same-origin", headers: type ? { "content-type": type } : {}, body, }); } catch { throw new ApiError(0, "Serveur injoignable. Verifiez votre connexion."); } const parsed: unknown = await response.json().catch(() => null); if (!response.ok) throw new ApiError(response.status, messageOf(parsed, "L'envoi a echoue.")); return parsed as T; }; export const api = { // --- Session ----------------------------------------------------------- me: () => request<{ user: User }>("/auth/me"), login: (email: string, password: string) => post<{ user: User }>("/auth/login", { email, password }), logout: () => post<{ ok: boolean }>("/auth/logout"), changePassword: (current: string, next: string) => post<{ ok: boolean }>("/auth/change-password", { current, next }), forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }), resetPassword: (token: string, password: string) => post<{ ok: boolean }>("/account/reset-password", { token, password }), requestEmailChange: (password: string, new_email: string) => post<{ ok: boolean }>("/account/email-change", { password, new_email }), confirmEmailChange: (token: string) => post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }), // --- Compte ------------------------------------------------------------ updateProfile: (first_name: string, last_name: string) => patch<{ ok: boolean }>("/account/profile", { first_name, last_name }), preferences: () => request<{ theme: Theme; language: Language }>("/account/preferences"), updatePreferences: (theme: Theme, language: Language) => patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }), sessions: () => request<{ sessions: SessionInfo[] }>("/account/sessions"), revokeSession: (id: string) => del<{ ok: boolean }>(`/account/sessions/${encodeURIComponent(id)}`), revokeOtherSessions: () => del<{ ok: boolean }>("/account/sessions"), avatarUrl: (userId: string) => `${BASE}/account/avatar/${encodeURIComponent(userId)}`, uploadAvatar: (file: File) => putBinary<{ ok: boolean }>("/account/avatar", file, file.type), deleteAvatar: () => del<{ ok: boolean }>("/account/avatar"), directory: () => request<{ users: DirectoryUser[] }>("/directory"), // --- Dossiers ---------------------------------------------------------- folders: (parentId?: string | null) => request<{ parentId: string | null; folders: Folder[] }>( `/folders${query({ parentId })}`, ), createFolder: (name: string, parentId?: string | null) => post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null }), updateFolder: (id: string, name: string) => patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, { name }), moveFolder: (id: string, parentId: string | null) => post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }), deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`), folderPermissions: (id: string) => request<{ permissions: FolderPermission[] }>( `/folders/${encodeURIComponent(id)}/permissions`, ), grantPermission: (id: string, email: string, level: string, expiresAt: string | null) => post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, { email, level, expiresAt, }), revokePermission: (id: string, userId: string) => del<{ ok: boolean }>( `/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`, ), // --- Fichiers ---------------------------------------------------------- files: (folderId?: string | null) => request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`), uploadFile: (file: File, folderId: string | null) => putBinary<{ file: UploadedFile }>( `/files${query({ name: file.name, folderId })}`, file, file.type, ), renameFile: (id: string, name: string) => patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }), moveFile: (id: string, folderId: string | null) => post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }), starFile: (id: string) => request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }), favorites: () => request<{ files: FavoriteFile[] }>("/favorites"), deleteFile: (id: string) => del<{ ok: boolean }>(`/files/${encodeURIComponent(id)}`), downloadUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/download`, thumbnailUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/thumbnail`, previewUrl: (id: string) => `${BASE}/files/${encodeURIComponent(id)}/preview`, // --- Corbeille, recherche, galerie ------------------------------------ trash: () => request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"), restoreFolder: (id: string) => post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`), restoreFile: (id: string) => post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`), purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`), purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`), emptyTrash: () => del<{ ok: boolean }>("/trash"), search: (q: string) => request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`), gallery: (kind: string, limit = 60, offset = 0) => request<{ kind: string | null; items: MediaItem[] }>( `/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, editedAfter?: string | null) => request<{ messages: ChatMessage[]; cursor: string }>( `/folders/${encodeURIComponent(folderId)}/chat/messages${query({ after, limit, editedAfter })}`, ), chatSend: (folderId: string, body: string) => post<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages`, { body }), chatEditMessage: (folderId: string, id: number, body: string) => patch<{ message: ChatMessage }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`, { body, }), chatTogglePin: (folderId: string, id: number) => put<{ pinned: boolean }>( `/folders/${encodeURIComponent(folderId)}/chat/messages/${id}/pin`, ), chatPins: (folderId: string) => request<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`), chatDeleteMessage: (folderId: string, id: number) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`), chatUnread: () => request<{ unread: Record }>("/chat/unread"), // --- Administration ---------------------------------------------------- adminStats: () => request("/admin/stats"), adminUsers: (q?: string) => request<{ users: AdminUser[] }>(`/admin/users${query({ q })}`), adminCreateUser: (payload: { email: string; first_name: string; last_name: string; role_slug: string; quota_bytes?: number | null; max_file_bytes?: number | null; }) => post<{ user: AdminUser }>("/admin/users", payload), adminUpdateUser: ( id: string, payload: Partial<{ first_name: string; last_name: string; role_slug: string; quota_bytes: number; max_file_bytes: number; is_active: boolean; }>, ) => patch<{ user: AdminUser }>(`/admin/users/${encodeURIComponent(id)}`, payload), adminDeleteUser: (id: string) => del<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}`), adminResetPassword: (id: string) => post<{ ok: boolean }>(`/admin/users/${encodeURIComponent(id)}/reset-password`), adminStorageLocations: () => request<{ locations: StorageLocation[] }>("/admin/storage-locations"), adminCreateStorageLocation: (payload: { name: string; slug: string; mount_path: string; quota_bytes?: number | null; }) => post<{ ok: boolean }>("/admin/storage-locations", payload), adminUpdateStorageLocation: ( id: number, payload: { name?: string; quota_bytes?: number | null; is_active?: boolean }, ) => patch<{ ok: boolean }>(`/admin/storage-locations/${id}`, payload), adminAudit: (limit = 100, offset = 0, action?: string, userId?: string) => request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`), adminAuditFilters: () => request<{ actions: string[]; users: { id: string; email: string | null }[] }>( "/admin/audit/filters", ), }; /** Octets en lecture humaine, sans precision inutile. */ export const formatBytes = (bytes: number): string => { const english = getLanguage() === "en"; if (bytes < 1024) return `${bytes} ${english ? "B" : "o"}`; const units = english ? ["KB", "MB", "GB", "TB"] : ["Ko", "Mo", "Go", "To"]; let value = bytes; let index = -1; do { value /= 1024; index += 1; } while (value >= 1024 && index < units.length - 1); return `${value.toLocaleString(getLocale(), { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`; }; export const formatDate = (value: string | null): string => value ? new Date(value).toLocaleString(getLocale(), { dateStyle: "medium", timeStyle: "short" }) : "—"; /** Date et heure completes, avec les secondes : utilise au survol d'un mention. */ export const formatDateTimeSeconds = (value: string | null): string => value ? new Date(value).toLocaleString(getLocale(), { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit", }) : "—";