Files
Kazier/backend/handlers/files.go
T
venture ac8bd9acb4 V3 S3 : correction des faits (fiche document + correct_facts)
Backend : CorrectFacts (editor+, validation Go -> 400 jamais 500),
op outbox correct_facts (full-replace jeu user), PATCH
/files/:id/facts (renvoie jeu complet). Tests service + sync + handlers.

Mobile (Room v20) : table resource_facts + FactsDao, FactsRepository
(sync remplace-en-bloc, correction optimiste + outbox atomique),
fiche « Ce qu'on a compris » sur le viewer (chips, suggéré grisé,
édition par type, reset auto), bouton viewer si processed, FR/EN.

Contrat docs/api-v1.md, V3.md (S1-S3 livrés, FTS -> v21).
2026-09-26 10:28:33 +02:00

418 lines
12 KiB
Go

package handlers
import (
"errors"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
"github.com/kazier/backend/service"
)
// parsePageParams valide page/pageSize (400 si garbage, cf. FEEDBACK A7/A16)
// au lieu du fallback silencieux. Cap pageSize 200 et offset 100000.
func parsePageParams(c *gin.Context) (page, pageSize int, ok bool) {
page = 1
pageSize = 50
if v := c.Query("page"); v != "" {
p, err := strconv.Atoi(v)
if err != nil || p < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `page`")
return 0, 0, false
}
page = p
}
if v := c.Query("pageSize"); v != "" {
ps, err := strconv.Atoi(v)
if err != nil || ps < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `pageSize`")
return 0, 0, false
}
pageSize = ps
}
if pageSize > 200 {
pageSize = 200
}
if (page-1)*pageSize > 100000 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "page offset too large")
return 0, 0, false
}
return page, pageSize, true
}
func FilesList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
folderID := c.Query("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `folderId`")
return
}
files, total, err := Store.ListFiles(userID, folderID, page, pageSize, c.Query("sort"), c.Query("order"))
if err != nil {
writeError(c, err)
return
}
api.OKList(c, files, page, pageSize, total)
}
func FilesGet(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
file, err := Store.GetFile(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, file)
}
// FilesGetOcr expose l'extrait OCR server-side d'un fichier visible (viewer+,
// own ou shared) : GET /files/:id/ocr. Réponse { text } ("" si pas encore
// extrait) + updatedAt. Permet à un second device de récupérer le texte déjà
// calculé sans re-téléverser les octets (cf. docs/api-v1.md §5).
func FilesGetOcr(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
dto, err := Store.GetFileOcr(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, dto)
}
// FilesGetFacts expose les faits génériques d'un fichier visible (V3 S2) :
// GET /files/:id/facts. Même portée que l'OCR (viewer+, own ou shared) —
// les faits dérivent du texte. `[]` si rien d'extractible (jamais 404 pour
// un fichier visible sans faits) ; 404 si trashé/absent/étranger.
func FilesGetFacts(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
facts, err := Store.GetFacts(userID, id)
if err != nil {
writeError(c, err)
return
}
if facts == nil {
facts = []service.FactDTO{}
}
api.OK(c, facts)
}
// FilesCorrectFacts remplace le jeu `user` des faits (V3 S3) :
// PATCH /files/:id/facts `{ facts: [...] }` (full-replace, jamais de diff).
// Nécessite editor+ (comme update_metadata) ; viewer- → 404 NOT_FOUND.
// Corps invalide (type inconnu, date non ISO, fait sans valeur) → 400.
func FilesCorrectFacts(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
var req struct {
Facts []service.FactDTO `json:"facts"`
}
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body (expected { facts: [...] })")
return
}
if req.Facts == nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing required field `facts`")
return
}
if len(req.Facts) > 100 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "`facts` too long (max 100)")
return
}
if err := Store.CorrectFacts(userID, id, req.Facts); err != nil {
// Erreurs de validation (type/date/valeur) → 400 explicite, pas 500 :
// ce sont des fautes client, jamais des pannes (cf. FEEDBACK #8).
if errors.Is(err, service.ErrInvalidFact) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", err.Error())
return
}
writeError(c, err)
return
}
facts, err := Store.GetFacts(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, facts)
}
// own ou shared) : GET /files/:id/content. Réponse binaire (Content-Type du
// fichier, Content-Disposition inline) — jamais d'enveloppe {data}. Supporte
// Range via http.ServeContent (Gin c.File). Sans bytes serveur (ressource
// metadata-only jamais uploadée) → 404 NOT_FOUND, comme invisible (pas
// d'énumération). V1 streaming : le client ne persiste rien.
func FilesContent(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
info, err := Store.OpenContent(userID, id)
if err != nil {
writeError(c, err)
return
}
c.Header("Content-Type", info.MimeType)
c.Header("Content-Disposition", "inline; filename=\""+info.Name+"\"")
c.File(info.Path)
}
func FilesDelete(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
// V3 corbeille : DELETE = trash par défaut ; ?mode=purge = destruction
// définitive (lignes + versions + octets). Mode inconnu → 400.
var deletedID string
var err error
switch c.Query("mode") {
case "", "trash":
deletedID, err = Store.Trash(userID, id)
case "purge":
deletedID, err = Store.Purge(userID, id)
default:
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `mode` (trash|purge)")
return
}
if err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": deletedID})
}
// FilesRestore restaure une ressource trashée (POST /files/:id/restore).
// Absente/étrangère → 404 NOT_FOUND ; déjà vivante → succès idempotent.
func FilesRestore(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
restoredID, err := Store.Restore(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": restoredID})
}
// TrashList expose la corbeille (GET /trash) : ressources trashées du user,
// les plus récentes d'abord, paginé comme les autres listes.
func TrashList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
items, total, err := Store.ListTrashed(userID, page, pageSize)
if err != nil {
writeError(c, err)
return
}
api.OKList(c, items, page, pageSize, total)
}
// VersionsList expose l'historique des octets (GET /files/:id/versions),
// le plus récent d'abord. Ressource trashée/absente/étrangère → 404.
func VersionsList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
versions, err := Store.ListVersions(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, versions)
}
// VersionRestore recopie la génération n vers le live
// (POST /files/:id/versions/:n/restore). Génération inconnue → 404.
func VersionRestore(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
id := c.Param("id")
if !deviceIDPattern.MatchString(id) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
n, err := strconv.Atoi(c.Param("n"))
if err != nil || n < 1 {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "version not found")
return
}
dto, err := Store.RestoreVersion(userID, id, n)
if err != nil {
writeError(c, err)
return
}
api.OK(c, dto)
}
func FilesUpload(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
folderID := c.PostForm("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `folderId`")
return
}
// resourceId optionnel : cible un fichier déjà connu (metadata-only de
// l'outbox) pour lui attacher ses octets physiques (ex. OCR serveur).
resourceID := c.PostForm("resourceId")
if resourceID != "" && !deviceIDPattern.MatchString(resourceID) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, Store.MaxFileSize+1)
file, err := c.FormFile("file")
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
api.Error(c, http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
return
}
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing multipart field `file`")
return
}
if file.Size > Store.MaxFileSize {
api.Error(c, http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
return
}
dto, err := Store.Upload(userID, file, folderID, resourceID)
if err != nil {
// Nom/extension rejetés côté service (TrimSpace, cap 255,
// anti-slash/retour-ligne, cf. FEEDBACK A16) → 400, jamais 500.
if errors.Is(err, service.ErrInvalidUpload) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid file name")
return
}
writeError(c, err)
return
}
api.OK(c, dto)
}
func FoldersList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
folders, err := Store.ListRootFolders(userID)
if err != nil {
writeError(c, err)
return
}
api.OK(c, folders)
}
func FilesSearch(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
q := strings.TrimSpace(c.Query("q"))
if q == "" {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing required query param `q`")
return
}
if len(q) > 200 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `q` too long (max 200)")
return
}
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
files, total, err := Store.SearchFiles(userID, q, page, pageSize)
if err != nil {
writeError(c, err)
return
}
api.OKList(c, files, page, pageSize, total)
}