streaming d'un fichier

This commit is contained in:
venture
2026-09-25 15:34:28 +02:00
parent 9e8b01b135
commit b869f70922
23 changed files with 856 additions and 1 deletions
+1
View File
@@ -17,6 +17,7 @@ var expectedRoutes = []string{
"GET /api/v1/files/folders",
"GET /api/v1/files/:id",
"GET /api/v1/files/:id/ocr",
"GET /api/v1/files/:id/content",
"DELETE /api/v1/files/:id",
"POST /api/v1/files/upload",
+27
View File
@@ -107,6 +107,33 @@ func FilesGetOcr(c *gin.Context) {
api.OK(c, dto)
}
// FilesContent streame les octets physiques d'un fichier visible (viewer+,
// 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")
+61
View File
@@ -686,3 +686,64 @@ func TestSearchQTooLong(t *testing.T) {
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/search?q="+string(long), token, nil, "")
expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "search-q-too-long")
}
func TestFilesContentStreaming(t *testing.T) {
r, _, repo := setup(t)
ownerDevice := repository.NewID()
ownerToken, owner := registerAndLogin(t, r, repo, testUserUsername(ownerDevice, "ct"), "content-test-password", ownerDevice)
granteeDevice := repository.NewID()
granteeToken, grantee := registerAndLogin(t, r, repo, testUserUsername(granteeDevice, "cg"), "content-test-password-b", granteeDevice)
outsiderDevice := repository.NewID()
outsiderToken, _ := registerAndLogin(t, r, repo, testUserUsername(outsiderDevice, "ch"), "content-test-password-c", outsiderDevice)
// Ressource metadata-only (outbox) puis upload ciblé des octets (≤10o, cf. setup).
fileID := repository.NewID()
if err := repo.Resources.InsertFile(owner, fileID, "note.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert file: %v", err)
}
rec := uploadMultipartToResource(t, r, ownerToken, fileID, "note.txt", []byte("hello"))
if rec.Code != http.StatusOK {
t.Fatalf("upload ciblé: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
// Owner : octets + Content-Type.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", ownerToken, nil, "")
if rec.Code != http.StatusOK {
t.Fatalf("content-owner: attendu 200, got %d body=%s", rec.Code, rec.Body.String())
}
if rec.Body.String() != "hello" {
t.Errorf("content-owner = %q, attendu %q", rec.Body.String(), "hello")
}
if ct := rec.Header().Get("Content-Type"); ct == "" {
t.Errorf("content-owner: Content-Type manquant")
}
// Grantée viewer : mêmes octets (résolution dir owner, pas requester).
if err := repo.Shares.Upsert(fileID, grantee, "viewer", false, nil, owner); err != nil {
t.Fatalf("share: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", granteeToken, nil, "")
if rec.Code != http.StatusOK || rec.Body.String() != "hello" {
t.Errorf("content-grantee: attendu 200 hello, got %d %q", rec.Code, rec.Body.String())
}
// Outsider : 404 (pas d'énumération).
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", outsiderToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-outsider")
// Metadata-only sans octets : 404 (jamais uploadé).
bareID := repository.NewID()
if err := repo.Resources.InsertFile(owner, bareID, "vide.txt", "", 0, nil, nil); err != nil {
t.Fatalf("insert bare: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+bareID+"/content", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-no-bytes")
// ID invalide → 404 ; sans token → 401.
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/not-hex/content", ownerToken, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "content-invalid-id")
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+fileID+"/content", "", nil, "")
if rec.Code != http.StatusUnauthorized {
t.Errorf("content-sans-token: attendu 401, got %d", rec.Code)
}
}
+1
View File
@@ -33,6 +33,7 @@ func RegisterRoutes(r *gin.Engine) {
protected.GET("/files/folders", FoldersList)
protected.GET("/files/:id", FilesGet)
protected.GET("/files/:id/ocr", FilesGetOcr)
protected.GET("/files/:id/content", FilesContent)
protected.DELETE("/files/:id", FilesDelete)
protected.POST("/files/upload", FilesUpload)
+60
View File
@@ -146,6 +146,66 @@ type FileOcrDTO struct {
UpdatedAt string `json:"updatedAt,omitempty"`
}
// ContentInfo describes the physical bytes of a file the user can see
// (viewer+, own or shared) for GET /files/:id/content (streaming lecture,
// jamais persisté côté client en V1 streaming).
type ContentInfo struct {
Path string
Name string
MimeType string
Size int64
}
// OpenContent resolves the physical file of a visible resource. Auth is
// viewer+ (GetFileVisible, own or shared) ; the bytes live under the OWNER
// dir (UPLOAD_DIR/<owner_id>/<resource_id>.<ext>), never under the requester.
// No physical file (metadata-only outbox resource, never uploaded) →
// repository.ErrNotFound (handler maps to 404 NOT_FOUND, same as invisible).
func (s *Resources) OpenContent(userID, resourceID string) (ContentInfo, error) {
row, err := s.Repo.GetFileVisible(userID, resourceID)
if err != nil {
return ContentInfo{}, err
}
ownerID, err := s.Repo.GetResourceOwner(resourceID)
if err != nil {
return ContentInfo{}, err
}
if !idPattern.MatchString(ownerID) || !idPattern.MatchString(resourceID) {
return ContentInfo{}, repository.ErrNotFound
}
base, err := filepath.EvalSymlinks(s.UploadDir)
if err != nil {
return ContentInfo{}, repository.ErrNotFound
}
matches, err := filepath.Glob(filepath.Join(s.UploadDir, ownerID, resourceID+".*"))
if err != nil {
return ContentInfo{}, repository.ErrNotFound
}
for _, m := range matches {
if !strings.HasPrefix(filepath.Base(m), resourceID+".") {
continue
}
fi, err := os.Lstat(m)
if err != nil || !fi.Mode().IsRegular() {
continue
}
resolved, err := filepath.EvalSymlinks(m)
if err != nil {
continue
}
rel, err := filepath.Rel(base, resolved)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
continue
}
mime := row.MimeType
if mime == "" {
mime = "application/octet-stream"
}
return ContentInfo{Path: resolved, Name: row.Name, MimeType: mime, Size: fi.Size()}, nil
}
return ContentInfo{}, repository.ErrNotFound
}
// GetFileOcr returns the OCR text of a file the user can see (viewer+, own or
// shared). Absent text → Text empty ("") with 200 (the caller decides).
func (s *Resources) GetFileOcr(ownerID, id string) (FileOcrDTO, error) {