refactor: restructure frontend and backend by domain services (#26)
CD — Deployment / deploy (push) Successful in 34s
CD — Deployment / deploy (push) Successful in 34s
Split the monolithic backend (lib/, routes/, access.ts, storage.ts, media.ts) into a layered structure inspired by JeanXXIII-CRM: - config/: appConfig, db - middleware/: auth (session, roles, cookies) - models/: shared types - routes/: *Routes.ts (thin HTTP handlers) - services/: *Service.ts (business logic, one per domain) - utils/: errors, http, migrate, ratelimit, validators, service bootstrap Frontend likewise: services/*Service.ts + apiClient, contexts/, types/, utils/format. Route files now carry the "Routes" suffix; service files are named authService.ts, ratelimit.ts, etc. and live in their own files, frontend and backend separated. Updated docs and READMEs to reflect the new layout. Typecheck and builds pass. --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #26 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
This commit was merged in pull request #26.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { Navigate, Outlet, Route, Routes } from "react-router-dom";
|
||||
import { Spinner } from "./ui/index.js";
|
||||
import { useSession } from "./lib/session.js";
|
||||
import { useSession } from "./contexts/SessionContext.js";
|
||||
import { AppShell } from "./components/AppShell.js";
|
||||
import { AuthLayout } from "./components/AuthLayout.js";
|
||||
import { DocumentTitle } from "./components/DocumentTitle.js";
|
||||
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
} from "react";
|
||||
import { NavLink, Outlet } from "react-router-dom";
|
||||
import { cn } from "../ui/index.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { Avatar } from "./Avatar.js";
|
||||
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
|
||||
import {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { api } from "../lib/api.js";
|
||||
import { accountService } from "../services/accountService.js";
|
||||
import { cn } from "../ui/index.js";
|
||||
|
||||
const initials = (first: string, last: string): string =>
|
||||
@@ -29,7 +29,7 @@ export const Avatar = ({
|
||||
{initials(firstName, lastName)}
|
||||
{hasAvatar ? (
|
||||
<img
|
||||
src={`${api.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
|
||||
src={`${accountService.avatarUrl(userId)}?v=${encodeURIComponent(avatarUpdatedAt ?? "")}`}
|
||||
alt=""
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
onError={(event) => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect } from "react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
const BRAND = "CoHaiSe Cloud";
|
||||
|
||||
|
||||
@@ -8,17 +8,13 @@ import {
|
||||
type KeyboardEvent as ReactKeyboardEvent,
|
||||
} from "react";
|
||||
import { Button, Spinner, cn } from "../ui/index.js";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
formatDateTimeSeconds,
|
||||
type ChatMember,
|
||||
type ChatMessage,
|
||||
} from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { chatService } from "../services/chatService.js";
|
||||
import { formatDate, formatDateTimeSeconds } from "../utils/format.js";
|
||||
import type { ChatMember, ChatMessage } from "../types/index.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { getLocale } from "../lib/locale.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useConfirm } from "./confirm.js";
|
||||
import { Avatar } from "./Avatar.js";
|
||||
import { ColorBendsBackdrop } from "./ColorBendsBackdrop.js";
|
||||
@@ -142,7 +138,7 @@ export const FolderChat = ({
|
||||
);
|
||||
|
||||
const loadMembers = useCallback(async () => {
|
||||
const { members: list } = await api.chatMembers(folderId);
|
||||
const { members: list } = await chatService.chatMembers(folderId);
|
||||
setMembers(list);
|
||||
}, [folderId]);
|
||||
|
||||
@@ -156,9 +152,9 @@ export const FolderChat = ({
|
||||
void (async () => {
|
||||
try {
|
||||
const [memberResult, messageResult, pinResult] = await Promise.all([
|
||||
api.chatMembers(folderId),
|
||||
api.chatMessages(folderId, 0, 50),
|
||||
api.chatPins(folderId),
|
||||
chatService.chatMembers(folderId),
|
||||
chatService.chatMessages(folderId, 0, 50),
|
||||
chatService.chatPins(folderId),
|
||||
]);
|
||||
if (!active) return;
|
||||
setMembers(memberResult.members);
|
||||
@@ -191,13 +187,13 @@ export const FolderChat = ({
|
||||
if (document.hidden) return;
|
||||
try {
|
||||
const [result, pinResult] = await Promise.all([
|
||||
api.chatMessages(
|
||||
chatService.chatMessages(
|
||||
folderId,
|
||||
lastIdRef.current,
|
||||
100,
|
||||
editedSinceRef.current,
|
||||
),
|
||||
api.chatPins(folderId),
|
||||
chatService.chatPins(folderId),
|
||||
]);
|
||||
editedSinceRef.current = result.cursor;
|
||||
mergeMessages(result.messages);
|
||||
@@ -250,7 +246,7 @@ export const FolderChat = ({
|
||||
setSending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { message } = await api.chatSend(folderId, body);
|
||||
const { message } = await chatService.chatSend(folderId, body);
|
||||
stickToBottomRef.current = true;
|
||||
mergeMessages([message]);
|
||||
setDraft("");
|
||||
@@ -277,7 +273,7 @@ export const FolderChat = ({
|
||||
return;
|
||||
setDeletingId(message.id);
|
||||
try {
|
||||
await api.chatDeleteMessage(folderId, message.id);
|
||||
await chatService.chatDeleteMessage(folderId, message.id);
|
||||
setMessages((previous) =>
|
||||
previous.filter((item) => item.id !== message.id),
|
||||
);
|
||||
@@ -309,7 +305,7 @@ export const FolderChat = ({
|
||||
setSavingEdit(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { message: updated } = await api.chatEditMessage(
|
||||
const { message: updated } = await chatService.chatEditMessage(
|
||||
folderId,
|
||||
message.id,
|
||||
body,
|
||||
@@ -337,7 +333,7 @@ export const FolderChat = ({
|
||||
setPinningId(message.id);
|
||||
setError(null);
|
||||
try {
|
||||
const { pinned } = await api.chatTogglePin(folderId, message.id);
|
||||
const { pinned } = await chatService.chatTogglePin(folderId, message.id);
|
||||
const updated = { ...message, is_pinned: pinned };
|
||||
mergeMessages([updated]);
|
||||
setPins((previous) =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { api } from "../lib/api.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { mediaKind } from "../lib/media.js";
|
||||
import { ArchiveIcon, AudioIcon, FileIcon, PlayIcon } from "./icons.js";
|
||||
|
||||
@@ -18,7 +18,7 @@ export const MediaThumb = ({
|
||||
if (kind === "image") {
|
||||
return (
|
||||
<img
|
||||
src={api.thumbnailUrl(id)}
|
||||
src={fileService.thumbnailUrl(id)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className="pointer-events-none h-full w-full object-cover"
|
||||
@@ -32,7 +32,7 @@ export const MediaThumb = ({
|
||||
return (
|
||||
<span className="relative block h-full w-full bg-black">
|
||||
<video
|
||||
src={`${api.previewUrl(id)}#t=0.1`}
|
||||
src={`${fileService.previewUrl(id)}#t=0.1`}
|
||||
preload="metadata"
|
||||
muted
|
||||
playsInline
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { cn } from "../ui/index.js";
|
||||
import { api } from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { ArrowLeftIcon, ArrowRightIcon, CloseIcon, DownloadIcon, FileIcon } from "./icons.js";
|
||||
|
||||
export interface MediaViewerItem {
|
||||
@@ -38,7 +38,7 @@ const TextViewer = ({ id }: { id: string }) => {
|
||||
let active = true;
|
||||
setText(null);
|
||||
setFailed(false);
|
||||
void fetch(api.previewUrl(id))
|
||||
void fetch(fileService.previewUrl(id))
|
||||
.then((response) => (response.ok ? response.text() : Promise.reject(new Error("failed"))))
|
||||
.then((body) => {
|
||||
if (active) setText(body);
|
||||
@@ -80,7 +80,7 @@ const Panel = ({
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{openable ? (
|
||||
<a
|
||||
href={api.previewUrl(item.id)}
|
||||
href={fileService.previewUrl(item.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={actionClass}
|
||||
@@ -88,7 +88,7 @@ const Panel = ({
|
||||
{t("Ouvrir")}
|
||||
</a>
|
||||
) : null}
|
||||
<a href={api.downloadUrl(item.id)} download={item.name} className={actionClass}>
|
||||
<a href={fileService.downloadUrl(item.id)} download={item.name} className={actionClass}>
|
||||
<DownloadIcon className="h-4 w-4" />
|
||||
{t("Télécharger")}
|
||||
</a>
|
||||
@@ -103,7 +103,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
|
||||
if (kind === "image") {
|
||||
return (
|
||||
<img
|
||||
src={api.previewUrl(item.id)}
|
||||
src={fileService.previewUrl(item.id)}
|
||||
alt={item.name}
|
||||
className="max-h-full max-w-full rounded-md object-contain shadow-2xl"
|
||||
/>
|
||||
@@ -112,7 +112,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
|
||||
if (kind === "video") {
|
||||
return (
|
||||
<video
|
||||
src={api.previewUrl(item.id)}
|
||||
src={fileService.previewUrl(item.id)}
|
||||
controls
|
||||
autoPlay
|
||||
className="max-h-full max-w-full rounded-md bg-black shadow-2xl"
|
||||
@@ -124,7 +124,7 @@ const Body = ({ item }: { item: MediaViewerItem }) => {
|
||||
<div className="flex w-full max-w-md flex-col items-center gap-4 rounded-lg bg-black/40 p-6">
|
||||
<FileIcon className="h-10 w-10 text-white/70" />
|
||||
<p className="max-w-full truncate text-sm text-white/90">{item.name}</p>
|
||||
<audio src={api.previewUrl(item.id)} controls autoPlay className="w-full" />
|
||||
<audio src={fileService.previewUrl(item.id)} controls autoPlay className="w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -173,7 +173,7 @@ export const MediaViewer = ({
|
||||
<p className="min-w-0 truncate text-sm font-medium">{current.name}</p>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<a
|
||||
href={api.downloadUrl(current.id)}
|
||||
href={fileService.downloadUrl(current.id)}
|
||||
download={current.name}
|
||||
className={controlClass}
|
||||
aria-label={t("Télécharger")}
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { Modal } from "./feedback.js";
|
||||
import { IconAction } from "./IconAction.js";
|
||||
import { CloseIcon, TrashIcon, MoveIcon } from "./icons.js";
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { Button, Input, cn } from "../ui/index.js";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type DirectoryUser,
|
||||
type Folder,
|
||||
type FolderPermission,
|
||||
} from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { directoryService } from "../services/directoryService.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { folderService } from "../services/folderService.js";
|
||||
import { formatDate } from "../utils/format.js";
|
||||
import type { DirectoryUser, Folder, FolderPermission } from "../types/index.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { Alert, Modal } from "./feedback.js";
|
||||
import { CloseIcon, MoveIcon, PenIcon, PlusIcon, TrashIcon } from "./icons.js";
|
||||
import { IconAction } from "./IconAction.js";
|
||||
@@ -48,7 +46,7 @@ export const CreateFolderDialog = ({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.createFolder(name, parentId);
|
||||
await folderService.createFolder(name, parentId);
|
||||
onCreated();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Création impossible.")));
|
||||
@@ -112,8 +110,8 @@ export const RenameDialog = ({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (target.type === "folder") await api.updateFolder(target.id, name);
|
||||
else await api.renameFile(target.id, name);
|
||||
if (target.type === "folder") await folderService.updateFolder(target.id, name);
|
||||
else await fileService.renameFile(target.id, name);
|
||||
onDone();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Renommage impossible.")));
|
||||
@@ -166,7 +164,7 @@ const loadTree = async (): Promise<TreeEntry[]> => {
|
||||
const entries: TreeEntry[] = [];
|
||||
const walk = async (parentId: string | null, prefix: string, depth: number): Promise<void> => {
|
||||
if (depth > 6) return;
|
||||
const { folders } = await api.folders(parentId);
|
||||
const { folders } = await folderService.folders(parentId);
|
||||
for (const folder of folders) {
|
||||
entries.push({ id: folder.id, label: `${prefix}${folder.name}` });
|
||||
await walk(folder.id, `${prefix}${folder.name} / `, depth + 1);
|
||||
@@ -209,8 +207,8 @@ export const MoveDialog = ({
|
||||
const parentId = destination === "" ? null : destination;
|
||||
try {
|
||||
for (const item of items) {
|
||||
if (item.type === "folder") await api.moveFolder(item.id, parentId);
|
||||
else await api.moveFile(item.id, parentId);
|
||||
if (item.type === "folder") await folderService.moveFolder(item.id, parentId);
|
||||
else await fileService.moveFile(item.id, parentId);
|
||||
}
|
||||
onDone();
|
||||
} catch (caught) {
|
||||
@@ -297,8 +295,8 @@ export const ShareDialog = ({
|
||||
const load = async () => {
|
||||
try {
|
||||
const [{ permissions: list }, { users }] = await Promise.all([
|
||||
api.folderPermissions(folder.id),
|
||||
api.directory(),
|
||||
folderService.folderPermissions(folder.id),
|
||||
directoryService.directory(),
|
||||
]);
|
||||
setPermissions(list);
|
||||
setMembers(users);
|
||||
@@ -324,7 +322,7 @@ export const ShareDialog = ({
|
||||
setError(null);
|
||||
try {
|
||||
const iso = expiresAt ? new Date(expiresAt).toISOString() : null;
|
||||
await api.grantPermission(folder.id, email, level, expiresAt ? iso : null);
|
||||
await folderService.grantPermission(folder.id, email, level, expiresAt ? iso : null);
|
||||
setEmail("");
|
||||
setExpiresAt("");
|
||||
await load();
|
||||
@@ -338,7 +336,7 @@ export const ShareDialog = ({
|
||||
const revoke = async (userId: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.revokePermission(folder.id, userId);
|
||||
await folderService.revokePermission(folder.id, userId);
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Révocation impossible.")));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { cn } from "../ui/index.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { CloseIcon } from "./icons.js";
|
||||
import { usePageHeader } from "./AppShell.js";
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { cn } from "../ui/index.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { CloseIcon } from "./icons.js";
|
||||
|
||||
type ToastTone = "success" | "error" | "info";
|
||||
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
useMemo,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import type { Language } from "./api.js";
|
||||
import { setLanguage } from "./locale.js";
|
||||
import type { Language } from "../types/index.js";
|
||||
import { setLanguage } from "../lib/locale.js";
|
||||
|
||||
const en: Record<string, string> = {
|
||||
"Annuler": "Cancel",
|
||||
@@ -7,7 +7,8 @@ import {
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { api, type User } from "./api.js";
|
||||
import type { User } from "../types/index.js";
|
||||
import { authService } from "../services/authService.js";
|
||||
|
||||
interface SessionValue {
|
||||
user: User | null;
|
||||
@@ -25,7 +26,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const { user: current } = await api.me();
|
||||
const { user: current } = await authService.me();
|
||||
setUser(current);
|
||||
} catch {
|
||||
setUser(null);
|
||||
@@ -39,7 +40,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
|
||||
}, [refresh]);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api.logout().catch(() => undefined);
|
||||
await authService.logout().catch(() => undefined);
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import type { Theme } from "./api.js";
|
||||
import type { Theme } from "../types/index.js";
|
||||
|
||||
const STORAGE_KEY = "cohaise-theme";
|
||||
|
||||
@@ -1,605 +0,0 @@
|
||||
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 UploadSession {
|
||||
uploadId: string;
|
||||
name: string;
|
||||
folderId: string | null;
|
||||
size: number;
|
||||
chunkSize: number;
|
||||
uploadedBytes: number;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
|
||||
|
||||
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;
|
||||
|
||||
const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
|
||||
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 = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "POST",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
const patch = <T>(path: string, payload: unknown): Promise<T> =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
|
||||
const put = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "PUT",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
|
||||
|
||||
const query = (params: Record<string, string | number | null | undefined>): 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}` : "";
|
||||
};
|
||||
|
||||
const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
|
||||
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;
|
||||
};
|
||||
|
||||
const resumeKey = (file: File, folderId: string | null): string =>
|
||||
`cohaise.upload:${folderId ?? "root"}:${file.name}:${file.size}:${file.lastModified}`;
|
||||
|
||||
const readResume = (key: string): string | null => {
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeResume = (key: string, uploadId: string): void => {
|
||||
try {
|
||||
window.localStorage.setItem(key, uploadId);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const clearResume = (key: string): void => {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const sendChunk = (
|
||||
uploadId: string,
|
||||
blob: Blob,
|
||||
onProgress: (loaded: number) => void,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("PUT", `${BASE}/uploads/${encodeURIComponent(uploadId)}/chunks`);
|
||||
xhr.withCredentials = true;
|
||||
xhr.setRequestHeader("content-type", "application/octet-stream");
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) onProgress(event.loaded);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
}
|
||||
reject(new ApiError(xhr.status, messageOf(parsed, "L'envoi du morceau a echoue.")));
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, "Serveur injoignable. Verifiez votre connexion."));
|
||||
xhr.onabort = () => reject(new ApiError(0, "Envoi interrompu."));
|
||||
xhr.send(blob);
|
||||
});
|
||||
|
||||
const sessionPath = (uploadId: string): string => `/uploads/${encodeURIComponent(uploadId)}`;
|
||||
|
||||
const uploadFileResumable = async (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
): Promise<{ file: UploadedFile }> => {
|
||||
const key = resumeKey(file, folderId);
|
||||
let upload: UploadSession | null = null;
|
||||
|
||||
const saved = readResume(key);
|
||||
if (saved !== null) {
|
||||
try {
|
||||
const result = await request<{ upload: UploadSession }>(sessionPath(saved));
|
||||
if (result.upload.name === file.name && result.upload.size === file.size) {
|
||||
upload = result.upload;
|
||||
} else {
|
||||
clearResume(key);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) clearResume(key);
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (upload === null) {
|
||||
const result = await post<{ upload: UploadSession }>("/uploads", {
|
||||
name: file.name,
|
||||
folderId,
|
||||
size: file.size,
|
||||
mimeType: file.type || null,
|
||||
});
|
||||
upload = result.upload;
|
||||
writeResume(key, upload.uploadId);
|
||||
}
|
||||
|
||||
const uploadId = upload.uploadId;
|
||||
let offset = upload.uploadedBytes;
|
||||
let attempts = 0;
|
||||
|
||||
while (offset < file.size) {
|
||||
const end = Math.min(offset + upload.chunkSize, file.size);
|
||||
try {
|
||||
await sendChunk(uploadId, file.slice(offset, end), (loaded) =>
|
||||
onProgress?.(offset + loaded, file.size),
|
||||
);
|
||||
offset = end;
|
||||
attempts = 0;
|
||||
} catch (error) {
|
||||
const transient =
|
||||
!(error instanceof ApiError) ||
|
||||
error.status === 0 ||
|
||||
error.status === 409 ||
|
||||
error.status >= 500;
|
||||
attempts += 1;
|
||||
if (!transient || attempts > 4) throw error;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 400 * attempts));
|
||||
const status = await request<{ upload: UploadSession }>(sessionPath(uploadId));
|
||||
if (status.upload.name !== file.name || status.upload.size !== file.size) {
|
||||
throw new ApiError(409, "La session d'envoi ne correspond plus au fichier.");
|
||||
}
|
||||
offset = status.upload.uploadedBytes;
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.(file.size, file.size);
|
||||
const result = await post<{ file: UploadedFile }>(`${sessionPath(uploadId)}/complete`);
|
||||
clearResume(key);
|
||||
return result;
|
||||
};
|
||||
|
||||
export const api = {
|
||||
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 }),
|
||||
|
||||
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"),
|
||||
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)}`,
|
||||
),
|
||||
|
||||
files: (folderId?: string | null) =>
|
||||
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
|
||||
uploadFile: (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
) => {
|
||||
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
|
||||
return uploadFileResumable(file, folderId, onProgress);
|
||||
}
|
||||
return putBinary<{ file: UploadedFile }>(
|
||||
`/files${query({ name: file.name, folderId })}`,
|
||||
file,
|
||||
file.type,
|
||||
).then((result) => {
|
||||
onProgress?.(file.size, file.size);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
uploadSession: (uploadId: string) =>
|
||||
request<{ upload: UploadSession }>(sessionPath(uploadId)),
|
||||
cancelUpload: (uploadId: string) => del<{ ok: boolean }>(sessionPath(uploadId)),
|
||||
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`,
|
||||
|
||||
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 })}`,
|
||||
),
|
||||
|
||||
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<string, number> }>("/chat/unread"),
|
||||
|
||||
adminStats: () => request<AdminStats>("/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",
|
||||
),
|
||||
};
|
||||
|
||||
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" }) : "—";
|
||||
|
||||
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",
|
||||
})
|
||||
: "—";
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Language } from "./api";
|
||||
import type { Language } from "../types/index.js";
|
||||
|
||||
let language: Language = "fr";
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@ import { StrictMode, type ReactNode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter } from "react-router-dom";
|
||||
import { App } from "./App.js";
|
||||
import { SessionProvider, useSession } from "./lib/session.js";
|
||||
import { I18nProvider } from "./lib/i18n.js";
|
||||
import { ThemeProvider } from "./lib/theme.js";
|
||||
import { SessionProvider, useSession } from "./contexts/SessionContext.js";
|
||||
import { I18nProvider } from "./contexts/I18nContext.js";
|
||||
import { ThemeProvider } from "./contexts/ThemeContext.js";
|
||||
import { ConfirmProvider } from "./components/confirm.js";
|
||||
import { ToastProvider } from "./components/toast.js";
|
||||
import "./styles/index.css";
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { Button, Input, Spinner } from "../ui/index.js";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatDate,
|
||||
type AdminStats,
|
||||
type AdminUser,
|
||||
type AuditEntry,
|
||||
type StorageLocation,
|
||||
} from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { adminService } from "../services/adminService.js";
|
||||
import { formatDate } from "../utils/format.js";
|
||||
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { getLocale } from "../lib/locale.js";
|
||||
import { Alert, Badge, EmptyState, Modal, PageHeader } from "../components/feedback.js";
|
||||
import { useConfirm } from "../components/confirm.js";
|
||||
@@ -63,7 +58,7 @@ export const AdminUsers = () => {
|
||||
termRef.current = term;
|
||||
setError(null);
|
||||
try {
|
||||
const { users: list } = await api.adminUsers(term || undefined);
|
||||
const { users: list } = await adminService.adminUsers(term || undefined);
|
||||
setUsers(list);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Chargement impossible.")));
|
||||
@@ -73,7 +68,7 @@ export const AdminUsers = () => {
|
||||
|
||||
useEffect(() => {
|
||||
void load("");
|
||||
api
|
||||
adminService
|
||||
.adminStats()
|
||||
.then(setStats)
|
||||
.catch(() => undefined);
|
||||
@@ -83,7 +78,7 @@ export const AdminUsers = () => {
|
||||
setBusy(user.id);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminUpdateUser(user.id, { is_active: !user.is_active });
|
||||
await adminService.adminUpdateUser(user.id, { is_active: !user.is_active });
|
||||
await load(termRef.current);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Mise à jour impossible.")));
|
||||
@@ -97,7 +92,7 @@ export const AdminUsers = () => {
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
try {
|
||||
await api.adminResetPassword(user.id);
|
||||
await adminService.adminResetPassword(user.id);
|
||||
setNotice(t("Mot de passe réinitialisé. Les identifiants ont été envoyés à {email}.", { email: user.email }));
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Réinitialisation impossible.")));
|
||||
@@ -119,7 +114,7 @@ export const AdminUsers = () => {
|
||||
setBusy(user.id);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminDeleteUser(user.id);
|
||||
await adminService.adminDeleteUser(user.id);
|
||||
await load(termRef.current);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Suppression impossible.")));
|
||||
@@ -298,7 +293,7 @@ const CreateUserDialog = ({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { user } = await api.adminCreateUser({
|
||||
const { user } = await adminService.adminCreateUser({
|
||||
email: email.trim(),
|
||||
first_name: firstName.trim(),
|
||||
last_name: lastName.trim(),
|
||||
@@ -416,7 +411,7 @@ const EditUserDialog = ({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminUpdateUser(user.id, {
|
||||
await adminService.adminUpdateUser(user.id, {
|
||||
first_name: firstName.trim(),
|
||||
last_name: lastName.trim(),
|
||||
role_slug: role,
|
||||
@@ -511,7 +506,7 @@ export const AdminStorage = () => {
|
||||
const load = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const { locations: list } = await api.adminStorageLocations();
|
||||
const { locations: list } = await adminService.adminStorageLocations();
|
||||
setLocations(list);
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Chargement impossible.")));
|
||||
@@ -526,7 +521,7 @@ export const AdminStorage = () => {
|
||||
const toggle = async (location: StorageLocation) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
|
||||
await adminService.adminUpdateStorageLocation(location.id, { is_active: !location.is_active });
|
||||
await load();
|
||||
} catch (caught) {
|
||||
setError(messageOf(caught, t("Mise à jour impossible.")));
|
||||
@@ -620,7 +615,7 @@ const CreateLocationDialog = ({
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.adminCreateStorageLocation({
|
||||
await adminService.adminCreateStorageLocation({
|
||||
name: name.trim(),
|
||||
slug: slug.trim(),
|
||||
mount_path: mountPath.trim(),
|
||||
@@ -706,7 +701,7 @@ export const AdminAudit = () => {
|
||||
const load = async (nextAction: string, nextUser: string) => {
|
||||
setError(null);
|
||||
try {
|
||||
const { entries: list } = await api.adminAudit(
|
||||
const { entries: list } = await adminService.adminAudit(
|
||||
100,
|
||||
0,
|
||||
nextAction || undefined,
|
||||
@@ -721,7 +716,7 @@ export const AdminAudit = () => {
|
||||
|
||||
useEffect(() => {
|
||||
void load("", "");
|
||||
void api
|
||||
void adminService
|
||||
.adminAuditFilters()
|
||||
.then(setFilters)
|
||||
.catch(() => undefined);
|
||||
@@ -739,7 +734,7 @@ export const AdminAudit = () => {
|
||||
setLoadingMore(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { entries: more } = await api.adminAudit(
|
||||
const { entries: more } = await adminService.adminAudit(
|
||||
100,
|
||||
entries.length,
|
||||
action || undefined,
|
||||
|
||||
@@ -6,15 +6,14 @@ import {
|
||||
type DragEvent,
|
||||
} from "react";
|
||||
import { Card, Spinner, cn } from "../ui/index.js";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatBytes,
|
||||
type Folder,
|
||||
type UploadedFile,
|
||||
} from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { chatService } from "../services/chatService.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { folderService } from "../services/folderService.js";
|
||||
import { formatBytes } from "../utils/format.js";
|
||||
import type { Folder, UploadedFile } from "../types/index.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { getLocale } from "../lib/locale.js";
|
||||
import { mediaKind } from "../lib/media.js";
|
||||
import { EmptyState, PageHeader } from "../components/feedback.js";
|
||||
@@ -114,8 +113,8 @@ export const Browser = () => {
|
||||
setError(null);
|
||||
try {
|
||||
const [folderResult, fileResult] = await Promise.all([
|
||||
api.folders(parentId),
|
||||
api.files(parentId),
|
||||
folderService.folders(parentId),
|
||||
fileService.files(parentId),
|
||||
]);
|
||||
if (sequence !== loadSeq.current) return;
|
||||
setFolders(folderResult.folders);
|
||||
@@ -141,7 +140,7 @@ export const Browser = () => {
|
||||
|
||||
const refreshUnread = useCallback(async () => {
|
||||
try {
|
||||
const { unread: counts } = await api.chatUnread();
|
||||
const { unread: counts } = await chatService.chatUnread();
|
||||
setUnread(counts);
|
||||
} catch {
|
||||
}
|
||||
@@ -205,7 +204,7 @@ export const Browser = () => {
|
||||
for (let i = 0; i < filesArr.length; i++) {
|
||||
const f = filesArr[i] as File;
|
||||
update(i + 1, 0);
|
||||
await api.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
|
||||
await fileService.uploadFile(f, current.id, (loaded) => update(i + 1, loaded));
|
||||
completedBytes += f.size;
|
||||
}
|
||||
void refresh();
|
||||
@@ -242,7 +241,7 @@ export const Browser = () => {
|
||||
for (let i = 0; i < filesArr.length; i++) {
|
||||
const f = filesArr[i] as File;
|
||||
update(i + 1, 0);
|
||||
await api.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
|
||||
await fileService.uploadFile(f, folderId, (loaded) => update(i + 1, loaded));
|
||||
completedBytes += f.size;
|
||||
}
|
||||
void refresh();
|
||||
@@ -345,9 +344,9 @@ export const Browser = () => {
|
||||
setError(null);
|
||||
try {
|
||||
if (target.type === "folder") {
|
||||
await api.deleteFolder(target.id);
|
||||
await folderService.deleteFolder(target.id);
|
||||
} else {
|
||||
await api.deleteFile(target.id);
|
||||
await fileService.deleteFile(target.id);
|
||||
void refresh();
|
||||
}
|
||||
await reload();
|
||||
@@ -376,8 +375,8 @@ export const Browser = () => {
|
||||
setError(null);
|
||||
try {
|
||||
for (const target of selectedItems) {
|
||||
if (target.type === "folder") await api.deleteFolder(target.id);
|
||||
else await api.deleteFile(target.id);
|
||||
if (target.type === "folder") await folderService.deleteFolder(target.id);
|
||||
else await fileService.deleteFile(target.id);
|
||||
}
|
||||
clearSelection();
|
||||
await reload();
|
||||
@@ -395,7 +394,7 @@ export const Browser = () => {
|
||||
const toggleStar = async (file: UploadedFile) => {
|
||||
setError(null);
|
||||
try {
|
||||
const { file: updated } = await api.starFile(file.id);
|
||||
const { file: updated } = await fileService.starFile(file.id);
|
||||
setFiles((previous) =>
|
||||
previous.map((item) => (item.id === updated.id ? updated : item)),
|
||||
);
|
||||
@@ -661,7 +660,7 @@ export const Browser = () => {
|
||||
}
|
||||
for (const target of files) {
|
||||
const link = document.createElement("a");
|
||||
link.href = api.downloadUrl(target.id);
|
||||
link.href = fileService.downloadUrl(target.id);
|
||||
link.download = target.name;
|
||||
link.click();
|
||||
}
|
||||
@@ -905,7 +904,7 @@ export const Browser = () => {
|
||||
/>
|
||||
|
||||
<a
|
||||
href={api.downloadUrl(file.id)}
|
||||
href={fileService.downloadUrl(file.id)}
|
||||
download={file.name}
|
||||
aria-label={t("Télécharger {name}", { name: file.name })}
|
||||
title={t("Télécharger {name}", { name: file.name })}
|
||||
|
||||
@@ -2,9 +2,10 @@ import { useState, type FormEvent } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { authService } from "../services/authService.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const ChangePassword = () => {
|
||||
const { user, refresh, logout } = useSession();
|
||||
@@ -25,7 +26,7 @@ export const ChangePassword = () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.changePassword(current, next);
|
||||
await authService.changePassword(current, next);
|
||||
await refresh();
|
||||
navigate("/files", { replace: true });
|
||||
} catch (caught) {
|
||||
|
||||
@@ -2,9 +2,10 @@ import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardHeader, CardTitle, Spinner } from "../ui/index.js";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { accountService } from "../services/accountService.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const ConfirmEmail = () => {
|
||||
const [params] = useSearchParams();
|
||||
@@ -23,7 +24,7 @@ export const ConfirmEmail = () => {
|
||||
setError(t("Ce lien est incomplet ou invalide."));
|
||||
return;
|
||||
}
|
||||
api
|
||||
accountService
|
||||
.confirmEmailChange(token)
|
||||
.then(() => {
|
||||
setState("success");
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Spinner } from "../ui/index.js";
|
||||
import { ApiError, api, formatBytes, type FavoriteFile } from "../lib/api.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { formatBytes } from "../utils/format.js";
|
||||
import type { FavoriteFile } from "../types/index.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";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const Favorites = () => {
|
||||
const { t } = useI18n();
|
||||
@@ -17,7 +20,7 @@ export const Favorites = () => {
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
void api
|
||||
void fileService
|
||||
.favorites()
|
||||
.then(({ files: list }) => {
|
||||
setFiles(list);
|
||||
@@ -33,7 +36,7 @@ export const Favorites = () => {
|
||||
const unstar = async (file: FavoriteFile) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.starFile(file.id);
|
||||
await fileService.starFile(file.id);
|
||||
setFiles((previous) => previous.filter((item) => item.id !== file.id));
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Action impossible."));
|
||||
@@ -90,7 +93,7 @@ export const Favorites = () => {
|
||||
/>
|
||||
|
||||
<a
|
||||
href={api.downloadUrl(file.id)}
|
||||
href={fileService.downloadUrl(file.id)}
|
||||
download={file.name}
|
||||
aria-label={t("Télécharger {name}", { name: file.name })}
|
||||
title={t("Télécharger {name}", { name: file.name })}
|
||||
|
||||
@@ -2,8 +2,9 @@ import { useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { accountService } from "../services/accountService.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const ForgotPassword = () => {
|
||||
const { t } = useI18n();
|
||||
@@ -17,7 +18,7 @@ export const ForgotPassword = () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.forgotPassword(email);
|
||||
await accountService.forgotPassword(email);
|
||||
setSent(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Demande impossible."));
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Button, Spinner, cn } from "../ui/index.js";
|
||||
import { ApiError, api, formatBytes, type MediaItem } from "../lib/api.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { mediaService } from "../services/mediaService.js";
|
||||
import { formatBytes } from "../utils/format.js";
|
||||
import type { MediaItem } from "../types/index.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { MediaViewer } from "../components/MediaViewer.js";
|
||||
import { MediaThumb } from "../components/MediaThumb.js";
|
||||
import { ImageIcon } from "../components/icons.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
const KINDS = [
|
||||
{ value: "", label: "Tout" },
|
||||
@@ -30,7 +33,7 @@ export const Gallery = () => {
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
void api
|
||||
void mediaService
|
||||
.gallery(kind, PAGE, 0)
|
||||
.then(({ items: first }) => {
|
||||
setItems(first);
|
||||
@@ -47,7 +50,7 @@ export const Gallery = () => {
|
||||
setLoadingMore(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { items: more } = await api.gallery(kind, PAGE, items.length);
|
||||
const { items: more } = await mediaService.gallery(kind, PAGE, items.length);
|
||||
setItems((previous) => [...previous, ...more]);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link, Navigate, useNavigate } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { authService } from "../services/authService.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const Login = () => {
|
||||
const { user, setUser } = useSession();
|
||||
@@ -21,7 +22,7 @@ export const Login = () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { user: current } = await api.login(email, password);
|
||||
const { user: current } = await authService.login(email, password);
|
||||
setUser(current);
|
||||
navigate(current.must_change_password ? "/change-password" : "/files", { replace: true });
|
||||
} catch (caught) {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from "react";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Spinner } from "../ui/index.js";
|
||||
import { ApiError, api, formatDate, type Language, type SessionInfo, type Theme } from "../lib/api.js";
|
||||
import { useSession } from "../lib/session.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { accountService } from "../services/accountService.js";
|
||||
import { formatDate } from "../utils/format.js";
|
||||
import type { Language, SessionInfo, Theme } from "../types/index.js";
|
||||
import { useSession } from "../contexts/SessionContext.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
import { Alert, Badge, PageHeader } from "../components/feedback.js";
|
||||
import { useConfirm } from "../components/confirm.js";
|
||||
import { IconAction } from "../components/IconAction.js";
|
||||
@@ -61,7 +64,7 @@ export const Profile = () => {
|
||||
const loadSessions = async () => {
|
||||
setSessionsError(null);
|
||||
try {
|
||||
const { sessions: list } = await api.sessions();
|
||||
const { sessions: list } = await accountService.sessions();
|
||||
setSessions(list);
|
||||
} catch (caught) {
|
||||
setSessionsError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
|
||||
@@ -79,7 +82,7 @@ export const Profile = () => {
|
||||
setProfileError(null);
|
||||
setProfileMessage(null);
|
||||
try {
|
||||
await api.updateProfile(firstName.trim(), lastName.trim());
|
||||
await accountService.updateProfile(firstName.trim(), lastName.trim());
|
||||
await refresh();
|
||||
setProfileMessage(t("Informations enregistrées."));
|
||||
} catch (caught) {
|
||||
@@ -95,7 +98,7 @@ export const Profile = () => {
|
||||
setPrefError(null);
|
||||
setPrefMessage(null);
|
||||
try {
|
||||
await api.updatePreferences(theme, language);
|
||||
await accountService.updatePreferences(theme, language);
|
||||
await refresh();
|
||||
setPrefMessage(t("Préférences enregistrées."));
|
||||
} catch (caught) {
|
||||
@@ -111,7 +114,7 @@ export const Profile = () => {
|
||||
setEmailError(null);
|
||||
setEmailMessage(null);
|
||||
try {
|
||||
await api.requestEmailChange(password, newEmail.trim());
|
||||
await accountService.requestEmailChange(password, newEmail.trim());
|
||||
setPassword("");
|
||||
setNewEmail("");
|
||||
setEmailMessage(t("Un e-mail de confirmation a été envoyé à la nouvelle adresse."));
|
||||
@@ -126,7 +129,7 @@ export const Profile = () => {
|
||||
if (!file) return;
|
||||
setAvatarError(null);
|
||||
try {
|
||||
await api.uploadAvatar(file);
|
||||
await accountService.uploadAvatar(file);
|
||||
await refresh();
|
||||
} catch (caught) {
|
||||
setAvatarError(caught instanceof ApiError ? caught.message : t("Envoi impossible."));
|
||||
@@ -138,7 +141,7 @@ export const Profile = () => {
|
||||
const removeAvatar = async () => {
|
||||
setAvatarError(null);
|
||||
try {
|
||||
await api.deleteAvatar();
|
||||
await accountService.deleteAvatar();
|
||||
await refresh();
|
||||
} catch (caught) {
|
||||
setAvatarError(caught instanceof ApiError ? caught.message : t("Suppression impossible."));
|
||||
@@ -158,7 +161,7 @@ export const Profile = () => {
|
||||
setRevoking(session.id);
|
||||
setSessionsError(null);
|
||||
try {
|
||||
await api.revokeSession(session.id);
|
||||
await accountService.revokeSession(session.id);
|
||||
if (session.current) {
|
||||
await refresh();
|
||||
return;
|
||||
@@ -174,7 +177,7 @@ export const Profile = () => {
|
||||
const revokeOthers = async () => {
|
||||
setSessionsError(null);
|
||||
try {
|
||||
await api.revokeOtherSessions();
|
||||
await accountService.revokeOtherSessions();
|
||||
setSessions((previous) => (previous ?? []).filter((item) => item.current));
|
||||
} catch (caught) {
|
||||
setSessionsError(caught instanceof ApiError ? caught.message : t("Révocation impossible."));
|
||||
@@ -305,7 +308,7 @@ export const Profile = () => {
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-full border border-border bg-surface-muted">
|
||||
<img
|
||||
src={`${api.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
|
||||
src={`${accountService.avatarUrl(user.id)}?v=${user.avatar_updated_at ?? ""}`}
|
||||
alt=""
|
||||
className="h-full w-full object-cover"
|
||||
onError={(event) => {
|
||||
|
||||
@@ -2,8 +2,9 @@ import { useState, type FormEvent } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Input } from "../ui/index.js";
|
||||
import { Alert } from "../components/feedback.js";
|
||||
import { ApiError, api } from "../lib/api.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { accountService } from "../services/accountService.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
export const ResetPassword = () => {
|
||||
const { t } = useI18n();
|
||||
@@ -24,7 +25,7 @@ export const ResetPassword = () => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await api.resetPassword(token, password);
|
||||
await accountService.resetPassword(token, password);
|
||||
setDone(true);
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Réinitialisation impossible."));
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Input, Spinner } from "../ui/index.js";
|
||||
import { ApiError, api, formatBytes, type Folder, type UploadedFile } from "../lib/api.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { fileService } from "../services/fileService.js";
|
||||
import { searchService } from "../services/searchService.js";
|
||||
import { formatBytes } from "../utils/format.js";
|
||||
import type { Folder, UploadedFile } from "../types/index.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { IconAction } from "../components/IconAction.js";
|
||||
import { DownloadIcon, FileIcon, FolderIcon, SearchIcon } from "../components/icons.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
interface Results {
|
||||
folders: Folder[];
|
||||
@@ -28,7 +32,7 @@ export const Search = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const { folders, files } = await api.search(query);
|
||||
const { folders, files } = await searchService.search(query);
|
||||
setResults({ folders, files });
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Recherche impossible."));
|
||||
@@ -126,7 +130,7 @@ export const Search = () => {
|
||||
</span>
|
||||
</span>
|
||||
<a
|
||||
href={api.downloadUrl(file.id)}
|
||||
href={fileService.downloadUrl(file.id)}
|
||||
download={file.name}
|
||||
aria-label={t("Télécharger {name}", { name: file.name })}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-surface-hover hover:text-foreground"
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Spinner } from "../ui/index.js";
|
||||
import {
|
||||
ApiError,
|
||||
api,
|
||||
formatBytes,
|
||||
formatDate,
|
||||
type TrashFile,
|
||||
type TrashFolder,
|
||||
} from "../lib/api.js";
|
||||
import { ApiError } from "../services/apiClient.js";
|
||||
import { trashService } from "../services/trashService.js";
|
||||
import { formatBytes, formatDate } from "../utils/format.js";
|
||||
import type { TrashFile, TrashFolder } from "../types/index.js";
|
||||
import { Alert, EmptyState, PageHeader } from "../components/feedback.js";
|
||||
import { useConfirm } from "../components/confirm.js";
|
||||
import { IconAction } from "../components/IconAction.js";
|
||||
import { FileIcon, FolderIcon, RestoreIcon, TrashEmptyIcon, TrashIcon } from "../components/icons.js";
|
||||
import { useI18n } from "../lib/i18n.js";
|
||||
import { useI18n } from "../contexts/I18nContext.js";
|
||||
|
||||
interface TrashData {
|
||||
retentionDays: number;
|
||||
@@ -32,7 +28,7 @@ export const Trash = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
setData(await api.trash());
|
||||
setData(await trashService.trash());
|
||||
} catch (caught) {
|
||||
setError(caught instanceof ApiError ? caught.message : t("Chargement impossible."));
|
||||
setData(null);
|
||||
@@ -67,7 +63,7 @@ export const Trash = () => {
|
||||
confirmIcon: <TrashEmptyIcon className="h-4 w-4" />,
|
||||
});
|
||||
if (!ok) return;
|
||||
void run("empty", () => api.emptyTrash());
|
||||
void run("empty", () => trashService.emptyTrash());
|
||||
};
|
||||
|
||||
const purge = async (key: string, name: string, action: () => Promise<unknown>) => {
|
||||
@@ -145,7 +141,7 @@ export const Trash = () => {
|
||||
icon={<RestoreIcon className="h-4 w-4" />}
|
||||
isLoading={busy === `restore-${folder.id}`}
|
||||
onClick={() =>
|
||||
void run(`restore-${folder.id}`, () => api.restoreFolder(folder.id))
|
||||
void run(`restore-${folder.id}`, () => trashService.restoreFolder(folder.id))
|
||||
}
|
||||
/>
|
||||
<IconAction
|
||||
@@ -155,7 +151,7 @@ export const Trash = () => {
|
||||
isLoading={busy === `purge-${folder.id}`}
|
||||
onClick={() =>
|
||||
void purge(`purge-${folder.id}`, folder.name, () =>
|
||||
api.purgeFolder(folder.id),
|
||||
trashService.purgeFolder(folder.id),
|
||||
)
|
||||
}
|
||||
/>
|
||||
@@ -190,7 +186,7 @@ export const Trash = () => {
|
||||
icon={<RestoreIcon className="h-4 w-4" />}
|
||||
isLoading={busy === `restore-${file.id}`}
|
||||
onClick={() =>
|
||||
void run(`restore-${file.id}`, () => api.restoreFile(file.id))
|
||||
void run(`restore-${file.id}`, () => trashService.restoreFile(file.id))
|
||||
}
|
||||
/>
|
||||
<IconAction
|
||||
@@ -199,7 +195,7 @@ export const Trash = () => {
|
||||
isLoading={busy === `purge-${file.id}`}
|
||||
tone="danger"
|
||||
onClick={() =>
|
||||
void purge(`purge-${file.id}`, file.name, () => api.purgeFile(file.id))
|
||||
void purge(`purge-${file.id}`, file.name, () => trashService.purgeFile(file.id))
|
||||
}
|
||||
/>
|
||||
</li>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { SessionInfo, Theme, Language } from "../types/index.js";
|
||||
import { BASE, del, get, patch, post, putBinary } from "./apiClient.js";
|
||||
|
||||
export const accountService = {
|
||||
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 }),
|
||||
|
||||
updateProfile: (first_name: string, last_name: string) =>
|
||||
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
|
||||
preferences: () => get<{ theme: Theme; language: Language }>("/account/preferences"),
|
||||
updatePreferences: (theme: Theme, language: Language) =>
|
||||
patch<{ theme: Theme; language: Language }>("/account/preferences", { theme, language }),
|
||||
sessions: () => get<{ 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"),
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { AdminStats, AdminUser, AuditEntry, StorageLocation } from "../types/index.js";
|
||||
import { del, get, patch, post, query } from "./apiClient.js";
|
||||
|
||||
export const adminService = {
|
||||
adminStats: () => get<AdminStats>("/admin/stats"),
|
||||
adminUsers: (q?: string) =>
|
||||
get<{ 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: () =>
|
||||
get<{ 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) =>
|
||||
get<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action, userId })}`),
|
||||
adminAuditFilters: () =>
|
||||
get<{ actions: string[]; users: { id: string; email: string | null }[] }>(
|
||||
"/admin/audit/filters",
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export const BASE = "/api/cloud";
|
||||
|
||||
/** Au-dela de ce seuil, l'envoi passe par des sessions morcelees. */
|
||||
export const LARGE_UPLOAD_THRESHOLD = 90 * 1024 * 1024;
|
||||
|
||||
const messageOf = (body: unknown, fallback: string): string =>
|
||||
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
|
||||
|
||||
export const request = async <T>(path: string, init?: RequestInit): Promise<T> => {
|
||||
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;
|
||||
};
|
||||
|
||||
export const get = <T>(path: string): Promise<T> => request<T>(path);
|
||||
|
||||
export const post = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "POST",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
export const patch = <T>(path: string, payload: unknown): Promise<T> =>
|
||||
request<T>(path, { method: "PATCH", body: JSON.stringify(payload) });
|
||||
|
||||
export const put = <T>(path: string, payload?: unknown): Promise<T> =>
|
||||
request<T>(path, {
|
||||
method: "PUT",
|
||||
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
||||
});
|
||||
|
||||
export const del = <T>(path: string): Promise<T> => request<T>(path, { method: "DELETE" });
|
||||
|
||||
export const query = (params: Record<string, string | number | null | undefined>): 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}` : "";
|
||||
};
|
||||
|
||||
export const putBinary = async <T>(path: string, body: BodyInit, type: string): Promise<T> => {
|
||||
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;
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { User } from "../types/index.js";
|
||||
import { get, post } from "./apiClient.js";
|
||||
|
||||
export const authService = {
|
||||
me: () => get<{ 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 }),
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ChatMember, ChatMessage } from "../types/index.js";
|
||||
import { del, get, patch, post, put, query } from "./apiClient.js";
|
||||
|
||||
export const chatService = {
|
||||
chatMembers: (folderId: string) =>
|
||||
get<{ members: ChatMember[] }>(`/folders/${encodeURIComponent(folderId)}/chat/members`),
|
||||
chatMessages: (folderId: string, after = 0, limit = 50, editedAfter?: string | null) =>
|
||||
get<{ 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) =>
|
||||
get<{ messages: ChatMessage[] }>(`/folders/${encodeURIComponent(folderId)}/chat/pins`),
|
||||
chatDeleteMessage: (folderId: string, id: number) =>
|
||||
del<{ ok: boolean }>(`/folders/${encodeURIComponent(folderId)}/chat/messages/${id}`),
|
||||
chatUnread: () => get<{ unread: Record<string, number> }>("/chat/unread"),
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { DirectoryUser } from "../types/index.js";
|
||||
import { get } from "./apiClient.js";
|
||||
|
||||
export const directoryService = {
|
||||
directory: () => get<{ users: DirectoryUser[] }>("/directory"),
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { FavoriteFile, UploadedFile } from "../types/index.js";
|
||||
import { BASE, del, get, patch, post, put, query, putBinary, LARGE_UPLOAD_THRESHOLD } from "./apiClient.js";
|
||||
import { uploadService } from "./uploadService.js";
|
||||
|
||||
export const fileService = {
|
||||
files: (folderId?: string | null) =>
|
||||
get<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
|
||||
uploadFile: (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
) => {
|
||||
if (file.size >= LARGE_UPLOAD_THRESHOLD) {
|
||||
return uploadService.uploadFileResumable(file, folderId, onProgress);
|
||||
}
|
||||
return putBinary<{ file: UploadedFile }>(
|
||||
`/files${query({ name: file.name, folderId })}`,
|
||||
file,
|
||||
file.type,
|
||||
).then((result) => {
|
||||
onProgress?.(file.size, file.size);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
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) =>
|
||||
put<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`),
|
||||
favorites: () => get<{ 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`,
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Folder, FolderPermission } from "../types/index.js";
|
||||
import { del, get, patch, post, query } from "./apiClient.js";
|
||||
|
||||
export const folderService = {
|
||||
folders: (parentId?: string | null) =>
|
||||
get<{ 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) =>
|
||||
get<{ 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)}`,
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { MediaItem } from "../types/index.js";
|
||||
import { get, query } from "./apiClient.js";
|
||||
|
||||
export const mediaService = {
|
||||
gallery: (kind: string, limit = 60, offset = 0) =>
|
||||
get<{ kind: string | null; items: MediaItem[] }>(
|
||||
`/media${query({ kind, limit, offset })}`,
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { Folder, UploadedFile } from "../types/index.js";
|
||||
import { get, query } from "./apiClient.js";
|
||||
|
||||
export const searchService = {
|
||||
search: (q: string) =>
|
||||
get<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TrashFile, TrashFolder } from "../types/index.js";
|
||||
import { del, get, post } from "./apiClient.js";
|
||||
|
||||
export const trashService = {
|
||||
trash: () =>
|
||||
get<{ 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"),
|
||||
};
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { UploadedFile, UploadSession } from "../types/index.js";
|
||||
import { ApiError, BASE, del, get, post, request } from "./apiClient.js";
|
||||
|
||||
const resumeKey = (file: File, folderId: string | null): string =>
|
||||
`cohaise.upload:${folderId ?? "root"}:${file.name}:${file.size}:${file.lastModified}`;
|
||||
|
||||
const readResume = (key: string): string | null => {
|
||||
try {
|
||||
return window.localStorage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeResume = (key: string, uploadId: string): void => {
|
||||
try {
|
||||
window.localStorage.setItem(key, uploadId);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const clearResume = (key: string): void => {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
const sendChunk = (
|
||||
uploadId: string,
|
||||
blob: Blob,
|
||||
onProgress: (loaded: number) => void,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("PUT", `${BASE}/uploads/${encodeURIComponent(uploadId)}/chunks`);
|
||||
xhr.withCredentials = true;
|
||||
xhr.setRequestHeader("content-type", "application/octet-stream");
|
||||
xhr.upload.onprogress = (event) => {
|
||||
if (event.lengthComputable) onProgress(event.loaded);
|
||||
};
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(xhr.responseText);
|
||||
} catch {
|
||||
}
|
||||
reject(new ApiError(xhr.status, messageOf(parsed, "L'envoi du morceau a echoue.")));
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError(0, "Serveur injoignable. Verifiez votre connexion."));
|
||||
xhr.onabort = () => reject(new ApiError(0, "Envoi interrompu."));
|
||||
xhr.send(blob);
|
||||
});
|
||||
|
||||
const messageOf = (body: unknown, fallback: string): string =>
|
||||
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
|
||||
|
||||
const sessionPath = (uploadId: string): string => `/uploads/${encodeURIComponent(uploadId)}`;
|
||||
|
||||
export const uploadService = {
|
||||
/** Envoi morcele avec reprise apres interruption. */
|
||||
uploadFileResumable: async (
|
||||
file: File,
|
||||
folderId: string | null,
|
||||
onProgress?: (loaded: number, total: number) => void,
|
||||
): Promise<{ file: UploadedFile }> => {
|
||||
const key = resumeKey(file, folderId);
|
||||
let upload: UploadSession | null = null;
|
||||
|
||||
const saved = readResume(key);
|
||||
if (saved !== null) {
|
||||
try {
|
||||
const result = await request<{ upload: UploadSession }>(sessionPath(saved));
|
||||
if (result.upload.name === file.name && result.upload.size === file.size) {
|
||||
upload = result.upload;
|
||||
} else {
|
||||
clearResume(key);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) clearResume(key);
|
||||
else throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (upload === null) {
|
||||
const result = await post<{ upload: UploadSession }>("/uploads", {
|
||||
name: file.name,
|
||||
folderId,
|
||||
size: file.size,
|
||||
mimeType: file.type || null,
|
||||
});
|
||||
upload = result.upload;
|
||||
writeResume(key, upload.uploadId);
|
||||
}
|
||||
|
||||
const uploadId = upload.uploadId;
|
||||
let offset = upload.uploadedBytes;
|
||||
let attempts = 0;
|
||||
|
||||
while (offset < file.size) {
|
||||
const end = Math.min(offset + upload.chunkSize, file.size);
|
||||
try {
|
||||
await sendChunk(uploadId, file.slice(offset, end), (loaded) =>
|
||||
onProgress?.(offset + loaded, file.size),
|
||||
);
|
||||
offset = end;
|
||||
attempts = 0;
|
||||
} catch (error) {
|
||||
const transient =
|
||||
!(error instanceof ApiError) ||
|
||||
error.status === 0 ||
|
||||
error.status === 409 ||
|
||||
error.status >= 500;
|
||||
attempts += 1;
|
||||
if (!transient || attempts > 4) throw error;
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 400 * attempts));
|
||||
const status = await request<{ upload: UploadSession }>(sessionPath(uploadId));
|
||||
if (status.upload.name !== file.name || status.upload.size !== file.size) {
|
||||
throw new ApiError(409, "La session d'envoi ne correspond plus au fichier.");
|
||||
}
|
||||
offset = status.upload.uploadedBytes;
|
||||
}
|
||||
}
|
||||
|
||||
onProgress?.(file.size, file.size);
|
||||
const result = await post<{ file: UploadedFile }>(
|
||||
`${sessionPath(uploadId)}/complete`,
|
||||
);
|
||||
clearResume(key);
|
||||
return result;
|
||||
},
|
||||
|
||||
uploadSession: (uploadId: string) =>
|
||||
get<{ upload: UploadSession }>(sessionPath(uploadId)),
|
||||
cancelUpload: (uploadId: string) => del<{ ok: boolean }>(sessionPath(uploadId)),
|
||||
};
|
||||
@@ -0,0 +1,196 @@
|
||||
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 UploadSession {
|
||||
uploadId: string;
|
||||
name: string;
|
||||
folderId: string | null;
|
||||
size: number;
|
||||
chunkSize: number;
|
||||
uploadedBytes: number;
|
||||
expiresAt: 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;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { getLanguage, getLocale } from "../lib/locale.js";
|
||||
|
||||
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" }) : "—";
|
||||
|
||||
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",
|
||||
})
|
||||
: "—";
|
||||
Reference in New Issue
Block a user