CD — Déploiement / deploy (push) Successful in 20s
/auth/me renvoie desormais has_avatar et avatar_updated_at (LEFT JOIN user_avatars). Le header affiche l'avatar avec un cache-buster sur updated_at, et retombe sur les initiales en cas d'absence ou d'echec. Le profil rafraichit la session apres ajout/retrait de l'avatar pour que le header se mette a jour immediatement. --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #6 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
373 lines
13 KiB
TypeScript
373 lines
13 KiB
TypeScript
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;
|
|
has_avatar: boolean;
|
|
avatar_updated_at: string | null;
|
|
}
|
|
|
|
export interface Folder {
|
|
id: string;
|
|
parent_id: string | null;
|
|
name: string;
|
|
description: string | null;
|
|
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 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;
|
|
description: string | null;
|
|
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 class ApiError extends Error {
|
|
readonly status: number;
|
|
|
|
constructor(status: number, message: string) {
|
|
super(message);
|
|
this.name = "ApiError";
|
|
this.status = status;
|
|
}
|
|
}
|
|
|
|
const BASE = "/api/cloud";
|
|
|
|
const messageOf = (body: unknown, fallback: string): string =>
|
|
(body as { error?: { message?: string } } | null)?.error?.message ?? fallback;
|
|
|
|
/**
|
|
* Un seul point d'entree HTTP. Le cookie de session est envoye
|
|
* automatiquement (same-origin), et toute erreur non-2xx devient une
|
|
* ApiError portant le message serveur, jamais un corps brut.
|
|
*/
|
|
const request = async <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 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}` : "";
|
|
};
|
|
|
|
/** Envoi d'un corps brut (fichier, image), hors JSON. */
|
|
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;
|
|
};
|
|
|
|
export const api = {
|
|
// --- Session -----------------------------------------------------------
|
|
me: () => request<{ user: User }>("/auth/me"),
|
|
login: (email: string, password: string) =>
|
|
post<{ user: User }>("/auth/login", { email, password }),
|
|
logout: () => post<{ ok: boolean }>("/auth/logout"),
|
|
changePassword: (current: string, next: string) =>
|
|
post<{ ok: boolean }>("/auth/change-password", { current, next }),
|
|
forgotPassword: (email: string) => post<{ ok: boolean }>("/account/forgot-password", { email }),
|
|
resetPassword: (token: string, password: string) =>
|
|
post<{ ok: boolean }>("/account/reset-password", { token, password }),
|
|
requestEmailChange: (password: string, new_email: string) =>
|
|
post<{ ok: boolean }>("/account/email-change", { password, new_email }),
|
|
confirmEmailChange: (token: string) =>
|
|
post<{ ok: boolean; email: string }>("/account/email-change/confirm", { token }),
|
|
|
|
// --- Compte ------------------------------------------------------------
|
|
updateProfile: (first_name: string, last_name: string) =>
|
|
patch<{ ok: boolean }>("/account/profile", { first_name, last_name }),
|
|
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"),
|
|
|
|
// --- Dossiers ----------------------------------------------------------
|
|
folders: (parentId?: string | null) =>
|
|
request<{ parentId: string | null; folders: Folder[] }>(
|
|
`/folders${query({ parentId })}`,
|
|
),
|
|
createFolder: (name: string, parentId?: string | null, description?: string) =>
|
|
post<{ folder: Folder }>("/folders", { name, parentId: parentId ?? null, description }),
|
|
updateFolder: (id: string, payload: { name?: string; description?: string | null }) =>
|
|
patch<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}`, payload),
|
|
moveFolder: (id: string, parentId: string | null) =>
|
|
post<{ folder: Folder }>(`/folders/${encodeURIComponent(id)}/move`, { parentId }),
|
|
deleteFolder: (id: string) => del<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}`),
|
|
folderPermissions: (id: string) =>
|
|
request<{ permissions: FolderPermission[] }>(
|
|
`/folders/${encodeURIComponent(id)}/permissions`,
|
|
),
|
|
grantPermission: (id: string, email: string, level: string, expiresAt: string | null) =>
|
|
post<{ ok: boolean }>(`/folders/${encodeURIComponent(id)}/permissions`, {
|
|
email,
|
|
level,
|
|
expiresAt,
|
|
}),
|
|
revokePermission: (id: string, userId: string) =>
|
|
del<{ ok: boolean }>(
|
|
`/folders/${encodeURIComponent(id)}/permissions/${encodeURIComponent(userId)}`,
|
|
),
|
|
|
|
// --- Fichiers ----------------------------------------------------------
|
|
files: (folderId?: string | null) =>
|
|
request<{ folderId: string | null; files: UploadedFile[] }>(`/files${query({ folderId })}`),
|
|
uploadFile: (file: File, folderId: string | null) =>
|
|
putBinary<{ file: UploadedFile }>(
|
|
`/files${query({ name: file.name, folderId })}`,
|
|
file,
|
|
file.type,
|
|
),
|
|
renameFile: (id: string, name: string) =>
|
|
patch<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}`, { name }),
|
|
moveFile: (id: string, folderId: string | null) =>
|
|
post<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/move`, { folderId }),
|
|
starFile: (id: string) =>
|
|
request<{ file: UploadedFile }>(`/files/${encodeURIComponent(id)}/star`, { method: "PUT" }),
|
|
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`,
|
|
|
|
// --- Corbeille, recherche, galerie ------------------------------------
|
|
trash: () =>
|
|
request<{ retentionDays: number; folders: TrashFolder[]; files: TrashFile[] }>("/trash"),
|
|
restoreFolder: (id: string) =>
|
|
post<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}/restore`),
|
|
restoreFile: (id: string) =>
|
|
post<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}/restore`),
|
|
purgeFolder: (id: string) => del<{ ok: boolean }>(`/trash/folders/${encodeURIComponent(id)}`),
|
|
purgeFile: (id: string) => del<{ ok: boolean }>(`/trash/files/${encodeURIComponent(id)}`),
|
|
emptyTrash: () => del<{ ok: boolean }>("/trash"),
|
|
|
|
search: (q: string) =>
|
|
request<{ query: string; folders: Folder[]; files: UploadedFile[] }>(`/search${query({ q })}`),
|
|
gallery: (kind: string, limit = 60, offset = 0) =>
|
|
request<{ kind: string | null; items: MediaItem[] }>(
|
|
`/media${query({ kind, limit, offset })}`,
|
|
),
|
|
|
|
// --- Administration ----------------------------------------------------
|
|
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; password: string }>("/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<{ password: string }>(`/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) =>
|
|
request<{ entries: AuditEntry[] }>(`/admin/audit${query({ limit, offset, action })}`),
|
|
};
|
|
|
|
/** Octets en lecture humaine, sans precision inutile. */
|
|
export const formatBytes = (bytes: number): string => {
|
|
if (bytes < 1024) return `${bytes} o`;
|
|
const units = ["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("fr-FR", { maximumFractionDigits: value < 10 ? 1 : 0 })} ${units[index]}`;
|
|
};
|
|
|
|
export const formatDate = (value: string | null): string =>
|
|
value ? new Date(value).toLocaleString("fr-FR", { dateStyle: "medium", timeStyle: "short" }) : "—";
|