api + cli

This commit is contained in:
venture
2026-11-16 13:12:36 +01:00
parent 4f18d94158
commit 8d48fadd01
7 changed files with 1909 additions and 7 deletions
+56
View File
@@ -0,0 +1,56 @@
package api
import (
"net/http"
"mediarr/node"
)
type Server struct {
node *node.Node
}
func NewServer(n *node.Node) *Server {
return &Server{node: n}
}
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/health", s.handleHealth)
mux.HandleFunc("POST /api/login", s.handleLogin)
mux.Handle("POST /api/logout", s.requireAuth(http.HandlerFunc(s.handleLogout)))
mux.Handle("GET /api/me", s.requireAuth(http.HandlerFunc(s.handleMe)))
mux.Handle("POST /api/users", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.handleCreateUser))))
mux.Handle("GET /api/libraries", s.requireAuth(http.HandlerFunc(s.handleListLibraries)))
mux.Handle("POST /api/libraries", s.requireAuth(http.HandlerFunc(s.handleCreateLibrary)))
mux.Handle("GET /api/documents/{id}", s.requireAuth(http.HandlerFunc(s.handleGetDocument)))
mux.Handle("GET /api/documents/{id}/children", s.requireAuth(http.HandlerFunc(s.handleListChildren)))
mux.Handle("POST /api/documents/{id}/children", s.requireAuth(http.HandlerFunc(s.handleCreateChild)))
mux.Handle("POST /api/documents/{id}/rename", s.requireAuth(http.HandlerFunc(s.handleRename)))
mux.Handle("PUT /api/documents/{id}/metadata", s.requireAuth(http.HandlerFunc(s.handleSetMetadata)))
mux.Handle("POST /api/documents/{id}/move", s.requireAuth(http.HandlerFunc(s.handleMove)))
mux.Handle("DELETE /api/documents/{id}", s.requireAuth(http.HandlerFunc(s.handleTrash)))
mux.Handle("POST /api/documents/{id}/restore", s.requireAuth(http.HandlerFunc(s.handleRestore)))
mux.Handle("GET /api/documents/{id}/versions", s.requireAuth(http.HandlerFunc(s.handleListVersions)))
mux.Handle("POST /api/documents/{id}/versions", s.requireAuth(http.HandlerFunc(s.handleUploadVersion)))
mux.Handle("GET /api/documents/{id}/head", s.requireAuth(http.HandlerFunc(s.handleGetHead)))
mux.Handle("POST /api/documents/{id}/head", s.requireAuth(http.HandlerFunc(s.handleSetHead)))
mux.Handle("POST /api/documents/{id}/retention", s.requireAuth(http.HandlerFunc(s.handleApplyRetention)))
mux.Handle("GET /api/versions/{id}", s.requireAuth(http.HandlerFunc(s.handleDownloadVersion)))
mux.Handle("DELETE /api/versions/{id}", s.requireAuth(http.HandlerFunc(s.handlePurgeVersion)))
mux.Handle("POST /api/versions/{id}/verify", s.requireAuth(http.HandlerFunc(s.handleVerifyVersion)))
mux.Handle("POST /api/maintenance/gc", s.requireAuth(s.requireAdmin(http.HandlerFunc(s.handleCollectGarbage))))
return mux
}
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
+411
View File
@@ -0,0 +1,411 @@
package api
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"mediarr/auth"
"mediarr/ident"
"mediarr/identity"
"mediarr/node"
)
type apiTestEnv struct {
node node.Node
server *httptest.Server
}
func newAPITestEnv(t *testing.T) *apiTestEnv {
t.Helper()
t.Chdir(t.TempDir())
err, n := node.NewNode(node.NewNodeParams{
DatabaseName: "api",
StoragePath: "store",
ClusterKeyPath: "cluster.key",
})
if err != nil {
t.Fatalf("NewNode : %v", err)
}
t.Cleanup(func() {
if err := n.Close(); err != nil {
t.Errorf("Close : %v", err)
}
})
if err := n.Up(); err != nil {
t.Fatalf("Up : %v", err)
}
server := httptest.NewServer(NewServer(&n).Handler())
t.Cleanup(server.Close)
return &apiTestEnv{node: n, server: server}
}
func TestAPIWorkflow(t *testing.T) {
env := newAPITestEnv(t)
ctx := context.Background()
client := env.server.Client()
if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{
Login: "admin",
Password: "password123",
Role: identity.RoleAdmin,
}); err != nil {
t.Fatalf("CreateUser(admin) : %v", err)
}
response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/health", "", nil)
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", "", nil)
requireStatus(t, response, body, http.StatusUnauthorized)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "admin",
"password": "password123",
})
requireStatus(t, response, body, http.StatusOK)
login := decodeBody[loginResponse](t, body)
if login.Token == "" || login.Principal.ID == "" || login.Account.Login != "admin" {
t.Fatalf("login = %+v", login)
}
if len(response.Cookies()) == 0 {
t.Fatal("cookie de session absent")
}
token := login.Token
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil)
requireStatus(t, response, body, http.StatusOK)
me := decodeBody[userDTO](t, body)
if me.Principal.ID != login.Principal.ID || me.Account.Login != "admin" {
t.Fatalf("me = %+v", me)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/libraries", token, map[string]any{
"name": "Films",
})
requireStatus(t, response, body, http.StatusCreated)
library := decodeBody[documentDTO](t, body)
if library.Kind != "library" || library.Name != "Films" || library.PolicyID == nil {
t.Fatalf("bibliothèque = %+v", library)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/libraries", token, nil)
requireStatus(t, response, body, http.StatusOK)
libraries := decodeBody[[]documentDTO](t, body)
if len(libraries) != 1 || libraries[0].ID != library.ID {
t.Fatalf("bibliothèques = %+v", libraries)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{
"kind": "video",
"name": "film.mkv",
})
requireStatus(t, response, body, http.StatusCreated)
video := decodeBody[documentDTO](t, body)
if video.Kind != "video" || video.ParentID == nil || *video.ParentID != library.ID {
t.Fatalf("vidéo = %+v", video)
}
response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v1"))
requireStatus(t, response, body, http.StatusCreated)
first := decodeBody[versionDTO](t, body)
if first.Seq != 1 || first.Size != int64(len("contenu v1")) || first.DocumentID != video.ID {
t.Fatalf("version 1 = %+v", first)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/versions", token, nil)
requireStatus(t, response, body, http.StatusOK)
versions := decodeBody[[]versionDTO](t, body)
if len(versions) != 1 || versions[0].ID != first.ID {
t.Fatalf("versions = %+v", versions)
}
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+video.ID+"/head", token, nil)
requireStatus(t, response, body, http.StatusOK)
head := decodeBody[struct {
Version *versionDTO `json:"version"`
}](t, body)
if head.Version == nil || head.Version.ID != first.ID {
t.Fatalf("head = %+v", head)
}
response, downloaded := doRaw(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil, "")
requireStatus(t, response, downloaded, http.StatusOK)
if string(downloaded) != "contenu v1" {
t.Fatalf("contenu téléchargé = %q", downloaded)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{
"version_id": first.ID,
})
requireStatus(t, response, body, http.StatusOK)
if decodeBody[versionDTO](t, body).ID != first.ID {
t.Fatal("version tête incohérente")
}
response, body = doUpload(t, client, env.server.URL+"/api/documents/"+video.ID+"/versions", token, "film.mkv", []byte("contenu v2"))
requireStatus(t, response, body, http.StatusCreated)
second := decodeBody[versionDTO](t, body)
if second.Seq != 2 {
t.Fatalf("version 2 = %+v", second)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/head", token, map[string]string{
"version_id": second.ID,
})
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/versions/"+first.ID, token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/versions/"+first.ID, token, nil)
requireStatus(t, response, body, http.StatusGone)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/retention", token, nil)
requireStatus(t, response, body, http.StatusOK)
retention := decodeBody[retentionDTO](t, body)
if retention.Kept < 1 {
t.Fatalf("rétention = %+v", retention)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/versions/"+second.ID+"/verify", token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/rename", token, map[string]string{
"name": "film-renamed.mkv",
})
requireStatus(t, response, body, http.StatusOK)
if decodeBody[documentDTO](t, body).Name != "film-renamed.mkv" {
t.Fatal("renommage incohérent")
}
response, body = doJSON(t, client, http.MethodPut, env.server.URL+"/api/documents/"+video.ID+"/metadata", token, map[string]any{
"metadata": map[string]any{"tag": "test"},
})
requireStatus(t, response, body, http.StatusOK)
if string(decodeBody[documentDTO](t, body).Metadata) != `{"tag":"test"}` {
t.Fatalf("métadonnées = %s", body)
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+library.ID+"/children", token, map[string]any{
"kind": "folder",
"name": "Dossier",
})
requireStatus(t, response, body, http.StatusCreated)
folder := decodeBody[documentDTO](t, body)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/move", token, map[string]string{
"parent_id": folder.ID,
})
requireStatus(t, response, body, http.StatusOK)
moved := decodeBody[documentDTO](t, body)
if moved.ParentID == nil || *moved.ParentID != folder.ID {
t.Fatalf("déplacement = %+v", moved)
}
response, body = doJSON(t, client, http.MethodDelete, env.server.URL+"/api/documents/"+video.ID, token, nil)
requireStatus(t, response, body, http.StatusOK)
trashed := decodeBody[documentDTO](t, body)
if trashed.DeletedAt == nil {
t.Fatal("document non mis à la corbeille")
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/documents/"+video.ID+"/restore", token, nil)
requireStatus(t, response, body, http.StatusOK)
if decodeBody[documentDTO](t, body).DeletedAt != nil {
t.Fatal("document non restauré")
}
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/users", token, map[string]string{
"login": "member",
"password": "password123",
"role": identity.RoleMember,
})
requireStatus(t, response, body, http.StatusCreated)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "member",
"password": "password123",
})
requireStatus(t, response, body, http.StatusOK)
memberToken := decodeBody[loginResponse](t, body).Token
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", memberToken, nil)
requireStatus(t, response, body, http.StatusForbidden)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/maintenance/gc", token, nil)
requireStatus(t, response, body, http.StatusOK)
response, body = doJSON(t, client, http.MethodPost, env.server.URL+"/api/logout", token, nil)
requireStatus(t, response, body, http.StatusNoContent)
response, body = doJSON(t, client, http.MethodGet, env.server.URL+"/api/me", token, nil)
requireStatus(t, response, body, http.StatusUnauthorized)
}
func TestAPILoginRejectsInvalidCredentials(t *testing.T) {
env := newAPITestEnv(t)
client := env.server.Client()
response, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "missing",
"password": "password123",
})
requireStatus(t, response, body, http.StatusUnauthorized)
}
func TestAPIDocumentNotFound(t *testing.T) {
env := newAPITestEnv(t)
ctx := context.Background()
client := env.server.Client()
if _, err := env.node.Auth().CreateUser(ctx, auth.CreateUserParams{
Login: "admin",
Password: "password123",
Role: identity.RoleAdmin,
}); err != nil {
t.Fatalf("CreateUser : %v", err)
}
_, body := doJSON(t, client, http.MethodPost, env.server.URL+"/api/login", "", map[string]string{
"login": "admin",
"password": "password123",
})
token := decodeBody[loginResponse](t, body).Token
missing := ident.MustParse("00000000-0000-7000-8000-000000000999").String()
response, body := doJSON(t, client, http.MethodGet, env.server.URL+"/api/documents/"+missing, token, nil)
requireStatus(t, response, body, http.StatusNotFound)
}
func doJSON(t *testing.T, client *http.Client, method, url, token string, body any) (*http.Response, []byte) {
t.Helper()
var reader io.Reader
if body != nil {
encoded, err := json.Marshal(body)
if err != nil {
t.Fatalf("Marshal : %v", err)
}
reader = bytes.NewReader(encoded)
}
request, err := http.NewRequest(method, url, reader)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
if body != nil {
request.Header.Set("Content-Type", "application/json")
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s : %v", method, url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func doUpload(t *testing.T, client *http.Client, url, token, filename string, content []byte) (*http.Response, []byte) {
t.Helper()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", filename)
if err != nil {
t.Fatalf("CreateFormFile : %v", err)
}
if _, err := part.Write(content); err != nil {
t.Fatalf("Write : %v", err)
}
if err := writer.WriteField("message", "test"); err != nil {
t.Fatalf("WriteField : %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("Close : %v", err)
}
request, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
request.Header.Set("Content-Type", writer.FormDataContentType())
request.Header.Set("Authorization", "Bearer "+token)
response, err := client.Do(request)
if err != nil {
t.Fatalf("POST %s : %v", url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func doRaw(t *testing.T, client *http.Client, method, url, token string, body io.Reader, contentType string) (*http.Response, []byte) {
t.Helper()
request, err := http.NewRequest(method, url, body)
if err != nil {
t.Fatalf("NewRequest : %v", err)
}
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("%s %s : %v", method, url, err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
_ = response.Body.Close()
t.Fatalf("ReadAll : %v", err)
}
_ = response.Body.Close()
return response, data
}
func decodeBody[T any](t *testing.T, body []byte) T {
t.Helper()
var value T
if err := json.Unmarshal(body, &value); err != nil {
t.Fatalf("Unmarshal %s : %v", body, err)
}
return value
}
func requireStatus(t *testing.T, response *http.Response, body []byte, want int) {
t.Helper()
if response.StatusCode != want {
t.Fatalf("status = %d, attendu %d: %s", response.StatusCode, want, body)
}
}
+262
View File
@@ -0,0 +1,262 @@
package api
import (
"context"
"errors"
"net/http"
"strings"
"time"
"mediarr/auth"
"mediarr/identity"
)
const sessionCookieName = "mediarr_session"
type contextKey int
const (
userContextKey contextKey = iota
tokenContextKey
)
type loginRequest struct {
Login string `json:"login"`
Password string `json:"password"`
Label string `json:"label,omitempty"`
}
type loginResponse struct {
Token string `json:"token"`
Principal principalDTO `json:"principal"`
Account accountDTO `json:"account"`
}
type createUserRequest struct {
Login string `json:"login"`
Password string `json:"password"`
Role string `json:"role,omitempty"`
}
type userDTO struct {
Principal principalDTO `json:"principal"`
Account accountDTO `json:"account"`
}
type principalDTO struct {
ID string `json:"id"`
Kind string `json:"kind"`
Name string `json:"name"`
Status string `json:"status"`
CreatedAt int64 `json:"created_at"`
Groups []groupDTO `json:"groups"`
}
type groupDTO struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
Role string `json:"role"`
}
type accountDTO struct {
Login string `json:"login"`
State string `json:"state"`
MustChangePassword bool `json:"must_change_password"`
LastLoginAt *int64 `json:"last_login_at,omitempty"`
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
var request loginRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
user, err := s.node.Auth().Authenticate(r.Context(), request.Login, request.Password)
if err != nil {
writeErrorFor(w, err)
return
}
_, token, err := s.node.Auth().CreateSession(r.Context(), auth.CreateSessionParams{
PrincipalID: user.Principal.ID,
Kind: "web",
Label: request.Label,
UserAgent: r.UserAgent(),
})
if err != nil {
writeErrorFor(w, err)
return
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: token,
Path: "/",
MaxAge: int((30 * 24 * time.Hour).Seconds()),
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
dto := userDTOFrom(user)
writeJSON(w, http.StatusOK, loginResponse{
Token: token,
Principal: dto.Principal,
Account: dto.Account,
})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
token := currentToken(r)
if token != "" {
if err := s.node.Auth().RevokeSessionByToken(r.Context(), token); err != nil && !errors.Is(err, auth.ErrInvalidSession) {
writeErrorFor(w, err)
return
}
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
})
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user == nil {
writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error())
return
}
writeJSON(w, http.StatusOK, userDTOFrom(user))
}
func (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
var request createUserRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
role := request.Role
if role == "" {
role = identity.RoleMember
}
created, err := s.node.Auth().CreateUser(r.Context(), auth.CreateUserParams{
Login: request.Login,
Password: request.Password,
Role: role,
})
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusCreated, userDTOFrom(created))
}
func (s *Server) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := extractToken(r)
if token == "" {
writeError(w, http.StatusUnauthorized, auth.ErrInvalidSession.Error())
return
}
_, user, err := s.node.Auth().ValidateSession(r.Context(), token)
if err != nil {
writeErrorFor(w, err)
return
}
ctx := context.WithValue(r.Context(), userContextKey, user)
ctx = context.WithValue(ctx, tokenContextKey, token)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *Server) requireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := currentUser(r)
if user == nil || !isAdmin(user) {
writeError(w, http.StatusForbidden, "droits administrateur requis")
return
}
next.ServeHTTP(w, r)
})
}
func extractToken(r *http.Request) string {
if header := r.Header.Get("Authorization"); header != "" {
if strings.HasPrefix(strings.ToLower(header), "bearer ") {
return strings.TrimSpace(header[len("bearer "):])
}
return ""
}
cookie, err := r.Cookie(sessionCookieName)
if err != nil {
return ""
}
return cookie.Value
}
func currentUser(r *http.Request) *auth.AuthenticatedUser {
user, _ := r.Context().Value(userContextKey).(*auth.AuthenticatedUser)
return user
}
func currentToken(r *http.Request) string {
token, _ := r.Context().Value(tokenContextKey).(string)
return token
}
func isAdmin(user *auth.AuthenticatedUser) bool {
for _, group := range user.Principal.Groups {
if group.Role == identity.RoleAdmin || group.Name == "admins" {
return true
}
}
return false
}
func userDTOFrom(user *auth.AuthenticatedUser) userDTO {
groups := make([]groupDTO, 0, len(user.Principal.Groups))
for _, group := range user.Principal.Groups {
groups = append(groups, groupDTO{
ID: group.ID.String(),
Name: group.Name,
Status: group.Status,
Role: group.Role,
})
}
var lastLoginAt *int64
if user.Account.LastLoginAt.Valid {
value := user.Account.LastLoginAt.Int64
lastLoginAt = &value
}
return userDTO{
Principal: principalDTO{
ID: user.Principal.ID.String(),
Kind: user.Principal.Kind,
Name: user.Principal.Name,
Status: user.Principal.Status,
CreatedAt: user.Principal.CreatedAt,
Groups: groups,
},
Account: accountDTO{
Login: user.Account.Login,
State: user.Account.State,
MustChangePassword: user.Account.MustChangePassword,
LastLoginAt: lastLoginAt,
},
}
}
+284
View File
@@ -0,0 +1,284 @@
package api
import (
"encoding/hex"
"fmt"
"io"
"mime"
"net/http"
"path/filepath"
"strconv"
"strings"
"mediarr/content"
"mediarr/ident"
)
type versionDTO struct {
ID string `json:"id"`
DocumentID string `json:"document_id"`
Seq int64 `json:"seq"`
ContentRoot string `json:"content_root"`
Size int64 `json:"size"`
Mime string `json:"mime,omitempty"`
AuthorID string `json:"author_id"`
Origin string `json:"origin"`
Message string `json:"message,omitempty"`
Pinned bool `json:"pinned"`
ContentPurgedAt *int64 `json:"content_purged_at,omitempty"`
CreatedAt int64 `json:"created_at"`
}
type setHeadRequest struct {
VersionID string `json:"version_id"`
}
type retentionDTO struct {
Purged []string `json:"purged"`
Kept int `json:"kept"`
}
type garbageCollectionDTO struct {
Blobs int `json:"blobs"`
Locations int `json:"locations"`
Bytes int64 `json:"bytes"`
}
func (s *Server) handleListVersions(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
versions, err := s.node.Content().ListVersions(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
result := make([]versionDTO, 0, len(versions))
for i := range versions {
result = append(result, versionDTOFrom(&versions[i]))
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) handleUploadVersion(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBody)
defer func() {
if r.MultipartForm != nil {
_ = r.MultipartForm.RemoveAll()
}
}()
file, header, err := r.FormFile("file")
if err != nil {
writeError(w, http.StatusBadRequest, "fichier requis")
return
}
defer file.Close()
origin := r.FormValue("origin")
if origin == "" {
origin = content.OriginUpload
}
if origin != content.OriginUpload && origin != content.OriginRestore {
writeError(w, http.StatusBadRequest, "origine invalide")
return
}
mimeType := strings.TrimSpace(r.FormValue("mime"))
if mimeType == "" {
mimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(header.Filename)))
}
if mimeType == "" {
mimeType = "application/octet-stream"
}
pinned := false
if raw := r.FormValue("pinned"); raw != "" {
parsed, err := strconv.ParseBool(raw)
if err != nil {
writeError(w, http.StatusBadRequest, "pinned invalide")
return
}
pinned = parsed
}
version, err := s.node.Content().CreateVersion(r.Context(), actorID(r), documentID, content.CreateVersionParams{
Source: file,
Mime: mimeType,
Origin: origin,
Message: r.FormValue("message"),
Pinned: pinned,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/versions/"+version.ID.String())
writeJSON(w, http.StatusCreated, versionDTOFrom(version))
}
func (s *Server) handleDownloadVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
reader, version, err := s.node.Content().OpenVersion(r.Context(), actorID(r), versionID)
if err != nil {
writeErrorFor(w, err)
return
}
defer reader.Close()
contentType := version.Mime
if contentType == "" {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(version.Size, 10))
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fmt.Sprintf("version-%d", version.Seq)))
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, reader)
}
func (s *Server) handleGetHead(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
version, err := s.node.Content().HeadVersion(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
if version == nil {
writeJSON(w, http.StatusOK, map[string]any{"version": nil})
return
}
writeJSON(w, http.StatusOK, map[string]any{"version": versionDTOFrom(version)})
}
func (s *Server) handleSetHead(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request setHeadRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
versionID, err := ident.Parse(request.VersionID)
if err != nil {
writeError(w, http.StatusBadRequest, "version_id invalide")
return
}
version, err := s.node.Content().SetHeadVersion(r.Context(), actorID(r), documentID, versionID)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, versionDTOFrom(version))
}
func (s *Server) handleApplyRetention(w http.ResponseWriter, r *http.Request) {
documentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
result, err := s.node.Content().ApplyRetention(r.Context(), actorID(r), documentID)
if err != nil {
writeErrorFor(w, err)
return
}
purged := make([]string, 0, len(result.Purged))
for _, id := range result.Purged {
purged = append(purged, id.String())
}
writeJSON(w, http.StatusOK, retentionDTO{Purged: purged, Kept: result.Kept})
}
func (s *Server) handlePurgeVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
if err := s.node.Content().PurgeVersion(r.Context(), actorID(r), versionID); err != nil {
writeErrorFor(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleVerifyVersion(w http.ResponseWriter, r *http.Request) {
versionID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
if err := s.node.Content().VerifyVersion(r.Context(), actorID(r), versionID); err != nil {
writeErrorFor(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleCollectGarbage(w http.ResponseWriter, r *http.Request) {
result, err := s.node.Content().CollectGarbage(r.Context())
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, garbageCollectionDTO{
Blobs: result.Blobs,
Locations: result.Locations,
Bytes: result.Bytes,
})
}
func versionDTOFrom(version *content.Version) versionDTO {
return versionDTO{
ID: version.ID.String(),
DocumentID: version.DocumentID.String(),
Seq: version.Seq,
ContentRoot: hex.EncodeToString(version.ContentRoot),
Size: version.Size,
Mime: version.Mime,
AuthorID: version.AuthorID.String(),
Origin: version.Origin,
Message: version.Message,
Pinned: version.Pinned,
ContentPurgedAt: version.ContentPurgedAt,
CreatedAt: version.CreatedAt,
}
}
+338
View File
@@ -0,0 +1,338 @@
package api
import (
"encoding/json"
"net/http"
"mediarr/document"
"mediarr/ident"
)
const defaultStoragePolicyID = "00000000-0000-7000-8000-000000000101"
type documentDTO struct {
ID string `json:"id"`
Kind string `json:"kind"`
OwnerID string `json:"owner_id"`
CreatedBy string `json:"created_by"`
ParentID *string `json:"parent_id,omitempty"`
Name string `json:"name"`
Path string `json:"path"`
Depth int64 `json:"depth"`
HeadVersionID *string `json:"head_version_id,omitempty"`
Metadata json.RawMessage `json:"metadata"`
PolicyID *string `json:"policy_id,omitempty"`
Visibility string `json:"visibility,omitempty"`
ACLInherit bool `json:"acl_inherit"`
Rev int64 `json:"rev"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
DeletedAt *int64 `json:"deleted_at,omitempty"`
}
type createLibraryRequest struct {
Name string `json:"name"`
PolicyID string `json:"policy_id,omitempty"`
Visibility string `json:"visibility,omitempty"`
ACLInherit *bool `json:"acl_inherit,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
type createChildRequest struct {
Kind string `json:"kind"`
Name string `json:"name"`
ACLInherit *bool `json:"acl_inherit,omitempty"`
Metadata json.RawMessage `json:"metadata,omitempty"`
}
type renameRequest struct {
Name string `json:"name"`
}
type metadataRequest struct {
Metadata json.RawMessage `json:"metadata"`
}
type moveRequest struct {
ParentID string `json:"parent_id"`
}
func (s *Server) handleListLibraries(w http.ResponseWriter, r *http.Request) {
libraries, err := s.node.Documents().ListLibraries(r.Context(), actorID(r))
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentsDTO(libraries))
}
func (s *Server) handleCreateLibrary(w http.ResponseWriter, r *http.Request) {
var request createLibraryRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
policyID := request.PolicyID
if policyID == "" {
policyID = defaultStoragePolicyID
}
parsedPolicyID, err := ident.Parse(policyID)
if err != nil {
writeError(w, http.StatusBadRequest, "policy_id invalide")
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
created, err := s.node.Documents().CreateLibrary(r.Context(), actorID(r), document.CreateLibraryParams{
OwnerID: actorID(r),
CreatedBy: actorID(r),
Name: request.Name,
PolicyID: parsedPolicyID,
Visibility: request.Visibility,
ACLInherit: request.ACLInherit,
Metadata: metadata,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/documents/"+created.ID.String())
writeJSON(w, http.StatusCreated, documentDTOFrom(created))
}
func (s *Server) handleGetDocument(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
found, err := s.node.Documents().Get(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(found))
}
func (s *Server) handleListChildren(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
children, err := s.node.Documents().ListChildren(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentsDTO(children))
}
func (s *Server) handleCreateChild(w http.ResponseWriter, r *http.Request) {
parentID, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request createChildRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
created, err := s.node.Documents().CreateChild(r.Context(), actorID(r), document.CreateChildParams{
Kind: request.Kind,
OwnerID: actorID(r),
CreatedBy: actorID(r),
ParentID: parentID,
Name: request.Name,
ACLInherit: request.ACLInherit,
Metadata: metadata,
})
if err != nil {
writeErrorFor(w, err)
return
}
w.Header().Set("Location", "/api/documents/"+created.ID.String())
writeJSON(w, http.StatusCreated, documentDTOFrom(created))
}
func (s *Server) handleRename(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request renameRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
updated, err := s.node.Documents().Rename(r.Context(), actorID(r), id, request.Name)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(updated))
}
func (s *Server) handleSetMetadata(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request metadataRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
metadata, err := metadataString(request.Metadata)
if err != nil {
writeErrorFor(w, err)
return
}
updated, err := s.node.Documents().SetMetadata(r.Context(), actorID(r), id, metadata)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(updated))
}
func (s *Server) handleMove(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
var request moveRequest
if err := decodeJSON(w, r, &request); err != nil {
writeErrorFor(w, err)
return
}
parentID, err := ident.Parse(request.ParentID)
if err != nil {
writeError(w, http.StatusBadRequest, "parent_id invalide")
return
}
moved, err := s.node.Documents().Move(r.Context(), actorID(r), id, parentID)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(moved))
}
func (s *Server) handleTrash(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
trashed, err := s.node.Documents().Trash(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(trashed))
}
func (s *Server) handleRestore(w http.ResponseWriter, r *http.Request) {
id, err := idParam(r, "id")
if err != nil {
writeErrorFor(w, err)
return
}
restored, err := s.node.Documents().Restore(r.Context(), actorID(r), id)
if err != nil {
writeErrorFor(w, err)
return
}
writeJSON(w, http.StatusOK, documentDTOFrom(restored))
}
func actorID(r *http.Request) ident.UUID {
user := currentUser(r)
if user == nil {
return ident.UUID{}
}
return user.Principal.ID
}
func documentsDTO(documents []document.Document) []documentDTO {
result := make([]documentDTO, 0, len(documents))
for i := range documents {
result = append(result, documentDTOFrom(&documents[i]))
}
return result
}
func documentDTOFrom(doc *document.Document) documentDTO {
dto := documentDTO{
ID: doc.ID.String(),
Kind: doc.Kind,
OwnerID: doc.OwnerID.String(),
CreatedBy: doc.CreatedBy.String(),
Name: doc.Name,
Path: doc.Path,
Depth: doc.Depth,
Metadata: json.RawMessage(doc.Metadata),
Visibility: doc.Visibility,
ACLInherit: doc.ACLInherit,
Rev: doc.Rev,
CreatedAt: doc.CreatedAt,
UpdatedAt: doc.UpdatedAt,
DeletedAt: doc.DeletedAt,
}
if doc.ParentID != nil {
value := doc.ParentID.String()
dto.ParentID = &value
}
if doc.HeadVersionID != nil {
value := doc.HeadVersionID.String()
dto.HeadVersionID = &value
}
if doc.PolicyID != nil {
value := doc.PolicyID.String()
dto.PolicyID = &value
}
return dto
}
+149
View File
@@ -0,0 +1,149 @@
package api
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"mediarr/auth"
"mediarr/content"
"mediarr/document"
"mediarr/ident"
"mediarr/identity"
"mediarr/storage"
)
const (
maxJSONBody = 1 << 20
maxUploadBody = 2 << 30
)
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if status == http.StatusNoContent {
return
}
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
if message == "" {
message = http.StatusText(status)
}
writeJSON(w, status, map[string]string{"error": message})
}
func writeErrorFor(w http.ResponseWriter, err error) {
status := statusForError(err)
message := err.Error()
switch status {
case http.StatusInternalServerError:
message = "erreur interne"
case http.StatusRequestEntityTooLarge:
message = "requête trop volumineuse"
}
writeError(w, status, message)
}
func statusForError(err error) int {
var maxBytes *http.MaxBytesError
if errors.As(err, &maxBytes) {
return http.StatusRequestEntityTooLarge
}
switch {
case errors.Is(err, auth.ErrInvalidCredentials),
errors.Is(err, auth.ErrInvalidSession):
return http.StatusUnauthorized
case errors.Is(err, auth.ErrAccountLocked),
errors.Is(err, auth.ErrAccountDisabled),
errors.Is(err, document.ErrPermissionDenied):
return http.StatusForbidden
case errors.Is(err, document.ErrDocumentNotFound),
errors.Is(err, document.ErrParentNotFound),
errors.Is(err, document.ErrPolicyNotFound),
errors.Is(err, content.ErrVersionNotFound),
errors.Is(err, content.ErrContentUnavailable),
errors.Is(err, storage.ErrNotFound):
return http.StatusNotFound
case errors.Is(err, document.ErrNameTaken),
errors.Is(err, document.ErrDocumentDeleted),
errors.Is(err, document.ErrParentDeleted),
errors.Is(err, auth.ErrLoginTaken),
errors.Is(err, content.ErrVersionIsHead),
errors.Is(err, content.ErrVersionMismatch),
errors.Is(err, content.ErrBlobUnavailable),
errors.Is(err, content.ErrBlobCorrupt):
return http.StatusConflict
case errors.Is(err, content.ErrContentPurged):
return http.StatusGone
case errors.Is(err, content.ErrStorageNotConfigured),
errors.Is(err, content.ErrStorageBackendMissing):
return http.StatusServiceUnavailable
case errors.Is(err, document.ErrInvalidName),
errors.Is(err, document.ErrInvalidKind),
errors.Is(err, document.ErrInvalidMetadata),
errors.Is(err, document.ErrInvalidParent),
errors.Is(err, document.ErrInvalidMove),
errors.Is(err, document.ErrCannotMoveRoot),
errors.Is(err, document.ErrInvalidVisibility),
errors.Is(err, document.ErrInvalidTrashBatch),
errors.Is(err, auth.ErrInvalidLogin),
errors.Is(err, auth.ErrWeakPassword),
errors.Is(err, identity.ErrInvalidRole),
errors.Is(err, content.ErrInvalidOrigin),
errors.Is(err, content.ErrInvalidSource),
errors.Is(err, content.ErrNoContentKind),
errors.Is(err, content.ErrNoStoragePolicy),
errors.Is(err, content.ErrInvalidRetention):
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) error {
r.Body = http.MaxBytesReader(w, r.Body, maxJSONBody)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
if errors.Is(err, io.EOF) {
return errors.New("corps JSON requis")
}
return err
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
return errors.New("corps JSON invalide")
}
return nil
}
func metadataString(raw json.RawMessage) (string, error) {
if len(raw) == 0 {
return "{}", nil
}
if !json.Valid(raw) {
return "", fmt.Errorf("%w", document.ErrInvalidMetadata)
}
return string(raw), nil
}
func idParam(r *http.Request, name string) (ident.UUID, error) {
value := r.PathValue(name)
if value == "" {
return ident.UUID{}, errors.New("identifiant manquant")
}
id, err := ident.Parse(value)
if err != nil {
return ident.UUID{}, fmt.Errorf("identifiant invalide: %w", err)
}
return id, nil
}