add document service and acitons

This commit is contained in:
venture
2026-11-14 11:37:27 +01:00
parent 9d4f827d38
commit 03da7d9fff
13 changed files with 2177 additions and 5 deletions
+493
View File
@@ -90,6 +90,118 @@ func (q *Queries) CreateAccount(ctx context.Context, arg CreateAccountParams) (A
return i, err
}
const createDocument = `-- name: CreateDocument :one
INSERT INTO document (
id,
kind,
owner_id,
created_by,
parent_id,
name,
name_key,
path,
depth,
position,
head_version_id,
metadata,
policy_id,
visibility,
acl_inherit,
rev,
created_at,
updated_at
) VALUES (
?1,
?2,
?3,
?4,
?5,
?6,
?7,
?8,
?9,
?10,
?11,
?12,
?13,
?14,
?15,
?16,
?17,
?18
)
RETURNING id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
`
type CreateDocumentParams struct {
ID ident.UUID
Kind string
OwnerID ident.UUID
CreatedBy ident.UUID
ParentID *ident.UUID
Name string
NameKey string
Path string
Depth int64
Position sql.NullString
HeadVersionID *ident.UUID
Metadata string
PolicyID *ident.UUID
Visibility sql.NullString
AclInherit int64
Rev int64
CreatedAt int64
UpdatedAt int64
}
func (q *Queries) CreateDocument(ctx context.Context, arg CreateDocumentParams) (Document, error) {
row := q.db.QueryRowContext(ctx, createDocument,
arg.ID,
arg.Kind,
arg.OwnerID,
arg.CreatedBy,
arg.ParentID,
arg.Name,
arg.NameKey,
arg.Path,
arg.Depth,
arg.Position,
arg.HeadVersionID,
arg.Metadata,
arg.PolicyID,
arg.Visibility,
arg.AclInherit,
arg.Rev,
arg.CreatedAt,
arg.UpdatedAt,
)
var i Document
err := row.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
)
return i, err
}
const createMembership = `-- name: CreateMembership :one
INSERT INTO membership (
@@ -585,6 +697,33 @@ func (q *Queries) GetSessionByTokenHash(ctx context.Context, tokenHash []byte) (
return i, err
}
const getStoragePolicy = `-- name: GetStoragePolicy :one
SELECT id, name, mode, min_remote_replicas, replicate_history, cache_ttl_s, cache_max_bytes, version_retention, created_at
FROM storage_policy
WHERE id = ?1
`
// ============================================================================
// storage_policy
// ============================================================================
func (q *Queries) GetStoragePolicy(ctx context.Context, id ident.UUID) (StoragePolicy, error) {
row := q.db.QueryRowContext(ctx, getStoragePolicy, id)
var i StoragePolicy
err := row.Scan(
&i.ID,
&i.Name,
&i.Mode,
&i.MinRemoteReplicas,
&i.ReplicateHistory,
&i.CacheTtlS,
&i.CacheMaxBytes,
&i.VersionRetention,
&i.CreatedAt,
)
return i, err
}
const incrementFailedAttempts = `-- name: IncrementFailedAttempts :one
UPDATE account
SET failed_attempts = failed_attempts + 1
@@ -697,6 +836,117 @@ func (q *Queries) ListActivePrincipals(ctx context.Context) ([]Principal, error)
return items, nil
}
const listDocumentChildren = `-- name: ListDocumentChildren :many
SELECT id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
FROM document
WHERE parent_id = ?1
AND deleted_at IS NULL
ORDER BY COALESCE(position, ''), name_key
`
func (q *Queries) ListDocumentChildren(ctx context.Context, parentID *ident.UUID) ([]Document, error) {
rows, err := q.db.QueryContext(ctx, listDocumentChildren, parentID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Document
for rows.Next() {
var i Document
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listDocumentDescendants = `-- name: ListDocumentDescendants :many
SELECT id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
FROM document
WHERE path LIKE CAST(?1 AS TEXT) || '%'
AND id <> ?2
ORDER BY depth
`
type ListDocumentDescendantsParams struct {
Prefix string
RootID ident.UUID
}
func (q *Queries) ListDocumentDescendants(ctx context.Context, arg ListDocumentDescendantsParams) ([]Document, error) {
rows, err := q.db.QueryContext(ctx, listDocumentDescendants, arg.Prefix, arg.RootID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Document
for rows.Next() {
var i Document
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listGroupMembers = `-- name: ListGroupMembers :many
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
FROM membership m
@@ -780,6 +1030,59 @@ func (q *Queries) ListGroupMembersWithRole(ctx context.Context, groupID ident.UU
return items, nil
}
const listLibraries = `-- name: ListLibraries :many
SELECT id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
FROM document
WHERE parent_id IS NULL
AND deleted_at IS NULL
ORDER BY name_key
`
func (q *Queries) ListLibraries(ctx context.Context) ([]Document, error) {
rows, err := q.db.QueryContext(ctx, listLibraries)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Document
for rows.Next() {
var i Document
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMemberGroups = `-- name: ListMemberGroups :many
SELECT p.id, p.kind, p.name, p.public_key, p.status, p.successor_id, p.created_at, p.disabled_at
FROM membership m
@@ -1085,6 +1388,61 @@ func (q *Queries) LockAccount(ctx context.Context, arg LockAccountParams) (Accou
return i, err
}
const moveDocument = `-- name: MoveDocument :one
UPDATE document
SET parent_id = ?1,
path = ?2,
depth = ?3,
rev = rev + 1,
updated_at = ?4
WHERE id = ?5
AND deleted_at IS NULL
RETURNING id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
`
type MoveDocumentParams struct {
ParentID *ident.UUID
Path string
Depth int64
UpdatedAt int64
ID ident.UUID
}
func (q *Queries) MoveDocument(ctx context.Context, arg MoveDocumentParams) (Document, error) {
row := q.db.QueryRowContext(ctx, moveDocument,
arg.ParentID,
arg.Path,
arg.Depth,
arg.UpdatedAt,
arg.ID,
)
var i Document
err := row.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
)
return i, err
}
const recordLogin = `-- name: RecordLogin :one
UPDATE account
SET last_login_at = ?1,
@@ -1185,6 +1543,30 @@ func (q *Queries) ResetFailedAttempts(ctx context.Context, principalID ident.UUI
return i, err
}
const restoreDocumentBatch = `-- name: RestoreDocumentBatch :execrows
UPDATE document
SET deleted_at = NULL,
deleted_by = NULL,
trash_batch = NULL,
rev = rev + 1,
updated_at = ?1
WHERE trash_batch = ?2
AND deleted_at IS NOT NULL
`
type RestoreDocumentBatchParams struct {
UpdatedAt int64
TrashBatch []byte
}
func (q *Queries) RestoreDocumentBatch(ctx context.Context, arg RestoreDocumentBatchParams) (int64, error) {
result, err := q.db.ExecContext(ctx, restoreDocumentBatch, arg.UpdatedAt, arg.TrashBatch)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
const revokeACLEntry = `-- name: RevokeACLEntry :one
UPDATE acl_entry
SET revoked_at = ?1
@@ -1315,6 +1697,39 @@ func (q *Queries) TouchSession(ctx context.Context, arg TouchSessionParams) (Ses
return i, err
}
const trashDocumentSubtree = `-- name: TrashDocumentSubtree :execrows
UPDATE document
SET deleted_at = ?1,
deleted_by = ?2,
trash_batch = ?3,
rev = rev + 1,
updated_at = ?4
WHERE path LIKE CAST(?5 AS TEXT) || '%'
AND deleted_at IS NULL
`
type TrashDocumentSubtreeParams struct {
DeletedAt sql.NullInt64
DeletedBy *ident.UUID
TrashBatch []byte
UpdatedAt int64
Prefix string
}
func (q *Queries) TrashDocumentSubtree(ctx context.Context, arg TrashDocumentSubtreeParams) (int64, error) {
result, err := q.db.ExecContext(ctx, trashDocumentSubtree,
arg.DeletedAt,
arg.DeletedBy,
arg.TrashBatch,
arg.UpdatedAt,
arg.Prefix,
)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
const unlockAccount = `-- name: UnlockAccount :one
UPDATE account
SET state = 'active',
@@ -1374,6 +1789,84 @@ func (q *Queries) UpdateAccountState(ctx context.Context, arg UpdateAccountState
return i, err
}
const updateDocumentLocation = `-- name: UpdateDocumentLocation :exec
UPDATE document
SET path = ?1,
depth = ?2,
rev = rev + 1,
updated_at = ?3
WHERE id = ?4
`
type UpdateDocumentLocationParams struct {
Path string
Depth int64
UpdatedAt int64
ID ident.UUID
}
func (q *Queries) UpdateDocumentLocation(ctx context.Context, arg UpdateDocumentLocationParams) error {
_, err := q.db.ExecContext(ctx, updateDocumentLocation,
arg.Path,
arg.Depth,
arg.UpdatedAt,
arg.ID,
)
return err
}
const updateDocumentName = `-- name: UpdateDocumentName :one
UPDATE document
SET name = ?1,
name_key = ?2,
rev = rev + 1,
updated_at = ?3
WHERE id = ?4
AND deleted_at IS NULL
RETURNING id, kind, owner_id, created_by, parent_id, name, name_key, path, depth, position, head_version_id, metadata, policy_id, visibility, acl_inherit, rev, created_at, updated_at, deleted_at, deleted_by, trash_batch
`
type UpdateDocumentNameParams struct {
Name string
NameKey string
UpdatedAt int64
ID ident.UUID
}
func (q *Queries) UpdateDocumentName(ctx context.Context, arg UpdateDocumentNameParams) (Document, error) {
row := q.db.QueryRowContext(ctx, updateDocumentName,
arg.Name,
arg.NameKey,
arg.UpdatedAt,
arg.ID,
)
var i Document
err := row.Scan(
&i.ID,
&i.Kind,
&i.OwnerID,
&i.CreatedBy,
&i.ParentID,
&i.Name,
&i.NameKey,
&i.Path,
&i.Depth,
&i.Position,
&i.HeadVersionID,
&i.Metadata,
&i.PolicyID,
&i.Visibility,
&i.AclInherit,
&i.Rev,
&i.CreatedAt,
&i.UpdatedAt,
&i.DeletedAt,
&i.DeletedBy,
&i.TrashBatch,
)
return i, err
}
const updateMembershipRole = `-- name: UpdateMembershipRole :one
UPDATE membership
SET role = ?1
+121
View File
@@ -352,6 +352,15 @@ DELETE FROM session
WHERE expires_at <= sqlc.arg(now)
OR idle_expires_at <= sqlc.arg(now);
-- ============================================================================
-- storage_policy
-- ============================================================================
-- name: GetStoragePolicy :one
SELECT *
FROM storage_policy
WHERE id = sqlc.arg(id);
-- ============================================================================
-- document
-- ============================================================================
@@ -361,6 +370,118 @@ SELECT *
FROM document
WHERE id = sqlc.arg(id);
-- name: CreateDocument :one
INSERT INTO document (
id,
kind,
owner_id,
created_by,
parent_id,
name,
name_key,
path,
depth,
position,
head_version_id,
metadata,
policy_id,
visibility,
acl_inherit,
rev,
created_at,
updated_at
) VALUES (
sqlc.arg(id),
sqlc.arg(kind),
sqlc.arg(owner_id),
sqlc.arg(created_by),
sqlc.narg(parent_id),
sqlc.arg(name),
sqlc.arg(name_key),
sqlc.arg(path),
sqlc.arg(depth),
sqlc.narg(position),
sqlc.narg(head_version_id),
sqlc.arg(metadata),
sqlc.narg(policy_id),
sqlc.narg(visibility),
sqlc.arg(acl_inherit),
sqlc.arg(rev),
sqlc.arg(created_at),
sqlc.arg(updated_at)
)
RETURNING *;
-- name: ListDocumentChildren :many
SELECT *
FROM document
WHERE parent_id = sqlc.arg(parent_id)
AND deleted_at IS NULL
ORDER BY COALESCE(position, ''), name_key;
-- name: ListLibraries :many
SELECT *
FROM document
WHERE parent_id IS NULL
AND deleted_at IS NULL
ORDER BY name_key;
-- name: UpdateDocumentName :one
UPDATE document
SET name = sqlc.arg(name),
name_key = sqlc.arg(name_key),
rev = rev + 1,
updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id)
AND deleted_at IS NULL
RETURNING *;
-- name: MoveDocument :one
UPDATE document
SET parent_id = sqlc.arg(parent_id),
path = sqlc.arg(path),
depth = sqlc.arg(depth),
rev = rev + 1,
updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id)
AND deleted_at IS NULL
RETURNING *;
-- name: ListDocumentDescendants :many
SELECT *
FROM document
WHERE path LIKE CAST(sqlc.arg(prefix) AS TEXT) || '%'
AND id <> sqlc.arg(root_id)
ORDER BY depth;
-- name: UpdateDocumentLocation :exec
UPDATE document
SET path = sqlc.arg(path),
depth = sqlc.arg(depth),
rev = rev + 1,
updated_at = sqlc.arg(updated_at)
WHERE id = sqlc.arg(id);
-- name: TrashDocumentSubtree :execrows
UPDATE document
SET deleted_at = sqlc.arg(deleted_at),
deleted_by = sqlc.arg(deleted_by),
trash_batch = sqlc.arg(trash_batch),
rev = rev + 1,
updated_at = sqlc.arg(updated_at)
WHERE path LIKE CAST(sqlc.arg(prefix) AS TEXT) || '%'
AND deleted_at IS NULL;
-- name: RestoreDocumentBatch :execrows
UPDATE document
SET deleted_at = NULL,
deleted_by = NULL,
trash_batch = NULL,
rev = rev + 1,
updated_at = sqlc.arg(updated_at)
WHERE trash_batch = sqlc.arg(trash_batch)
AND deleted_at IS NOT NULL;
-- ============================================================================
-- acl_entry
-- ============================================================================
+118
View File
@@ -0,0 +1,118 @@
package document
import (
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"mediarr/database"
"mediarr/ident"
)
func (s *Service) CreateLibrary(ctx context.Context, params CreateLibraryParams) (*Document, error) {
name, nameKey, err := normalizeName(params.Name)
if err != nil {
return nil, err
}
visibility, err := normalizeVisibility(params.Visibility)
if err != nil {
return nil, err
}
if _, err := s.db.Queries.GetStoragePolicy(ctx, params.PolicyID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%w: %s", ErrPolicyNotFound, params.PolicyID)
}
return nil, err
}
id, err := ident.NewV7()
if err != nil {
return nil, err
}
now := nowMillis()
created, err := s.db.WriteQueries.CreateDocument(ctx, database.CreateDocumentParams{
ID: id,
Kind: KindLibrary,
OwnerID: params.OwnerID,
CreatedBy: params.CreatedBy,
ParentID: nil,
Name: name,
NameKey: nameKey,
Path: hex.EncodeToString(id[:]) + "/",
Depth: 0,
Metadata: metadataValue(params.Metadata),
PolicyID: &params.PolicyID,
Visibility: sql.NullString{String: visibility, Valid: true},
AclInherit: aclInheritValue(params.ACLInherit),
Rev: 1,
CreatedAt: now,
UpdatedAt: now,
})
if err != nil {
if isUniqueViolation(err) {
return nil, fmt.Errorf("%w: %s", ErrNameTaken, name)
}
return nil, err
}
return documentFromDB(created), nil
}
func (s *Service) CreateFolder(ctx context.Context, params CreateFolderParams) (*Document, error) {
name, nameKey, err := normalizeName(params.Name)
if err != nil {
return nil, err
}
parent, err := s.getDocument(ctx, params.ParentID)
if err != nil {
if errors.Is(err, ErrDocumentNotFound) {
return nil, fmt.Errorf("%w: %s", ErrParentNotFound, params.ParentID)
}
return nil, err
}
if parent.DeletedAt.Valid {
return nil, fmt.Errorf("%w: %s", ErrParentDeleted, params.ParentID)
}
if !isContainerKind(parent.Kind) {
return nil, fmt.Errorf("%w: %s", ErrInvalidParent, parent.Kind)
}
id, err := ident.NewV7()
if err != nil {
return nil, err
}
now := nowMillis()
created, err := s.db.WriteQueries.CreateDocument(ctx, database.CreateDocumentParams{
ID: id,
Kind: KindFolder,
OwnerID: params.OwnerID,
CreatedBy: params.CreatedBy,
ParentID: &params.ParentID,
Name: name,
NameKey: nameKey,
Path: parent.Path + hex.EncodeToString(id[:]) + "/",
Depth: parent.Depth + 1,
Metadata: metadataValue(params.Metadata),
AclInherit: aclInheritValue(params.ACLInherit),
Rev: 1,
CreatedAt: now,
UpdatedAt: now,
})
if err != nil {
if isUniqueViolation(err) {
return nil, fmt.Errorf("%w: %s", ErrNameTaken, name)
}
return nil, err
}
return documentFromDB(created), nil
}
+282
View File
@@ -0,0 +1,282 @@
package document
import (
"context"
"encoding/hex"
"errors"
"strings"
"testing"
"mediarr/ident"
)
func TestCreateLibrary(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library, err := service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "Photos",
PolicyID: testPolicyID,
})
if err != nil {
t.Fatalf("CreateLibrary : %v", err)
}
if library.Kind != KindLibrary {
t.Fatalf("kind = %q, attendu %q", library.Kind, KindLibrary)
}
if library.Name != "Photos" || library.NameKey != "photos" {
t.Fatalf("nom = %q/%q, attendu Photos/photos", library.Name, library.NameKey)
}
if library.ParentID != nil {
t.Fatalf("parent = %v, attendu nil", library.ParentID)
}
if library.Depth != 0 {
t.Fatalf("depth = %d, attendu 0", library.Depth)
}
if library.Path != hex.EncodeToString(library.ID[:])+"/" {
t.Fatalf("path = %q", library.Path)
}
if library.PolicyID == nil || *library.PolicyID != testPolicyID {
t.Fatalf("policy = %v, attendu %s", library.PolicyID, testPolicyID)
}
if library.Visibility != VisibilityPrivate {
t.Fatalf("visibility = %q, attendu %q", library.Visibility, VisibilityPrivate)
}
if !library.ACLInherit {
t.Fatal("acl_inherit = false, attendu true")
}
if library.Rev != 1 {
t.Fatalf("rev = %d, attendu 1", library.Rev)
}
if library.Metadata != "{}" {
t.Fatalf("metadata = %q, attendu {}", library.Metadata)
}
if library.CreatedAt == 0 || library.UpdatedAt == 0 {
t.Fatal("timestamps non renseignés")
}
}
func TestCreateLibraryExplicitOptions(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
aclInherit := false
library, err := service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "Films",
PolicyID: testPolicyID,
Visibility: VisibilityCluster,
ACLInherit: &aclInherit,
Metadata: `{"genre":"test"}`,
})
if err != nil {
t.Fatalf("CreateLibrary : %v", err)
}
if library.Visibility != VisibilityCluster {
t.Fatalf("visibility = %q, attendu %q", library.Visibility, VisibilityCluster)
}
if library.ACLInherit {
t.Fatal("acl_inherit = true, attendu false")
}
if library.Metadata != `{"genre":"test"}` {
t.Fatalf("metadata = %q", library.Metadata)
}
}
func TestCreateLibraryRejectsInvalidName(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
cases := []string{"", " ", "a/b", strings.Repeat("a", 256)}
for _, name := range cases {
_, err := service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: name,
PolicyID: testPolicyID,
})
if !errors.Is(err, ErrInvalidName) {
t.Fatalf("nom %q : erreur = %v, attendu ErrInvalidName", name, err)
}
}
}
func TestCreateLibraryRejectsInvalidVisibility(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
_, err := service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "Photos",
PolicyID: testPolicyID,
Visibility: "SECRET",
})
if !errors.Is(err, ErrInvalidVisibility) {
t.Fatalf("erreur = %v, attendu ErrInvalidVisibility", err)
}
}
func TestCreateLibraryRejectsMissingPolicy(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
missing, err := ident.NewV7()
if err != nil {
t.Fatalf("NewV7 : %v", err)
}
_, err = service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "Photos",
PolicyID: missing,
})
if !errors.Is(err, ErrPolicyNotFound) {
t.Fatalf("erreur = %v, attendu ErrPolicyNotFound", err)
}
}
func TestCreateLibraryRejectsDuplicateName(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
mustLibrary(t, service, owner, "Photos")
_, err := service.CreateLibrary(ctx, CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "photos",
PolicyID: testPolicyID,
})
if !errors.Is(err, ErrNameTaken) {
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
}
}
func TestCreateFolder(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder, err := service.CreateFolder(ctx, CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: library.ID,
Name: "Vacances",
})
if err != nil {
t.Fatalf("CreateFolder : %v", err)
}
if folder.Kind != KindFolder {
t.Fatalf("kind = %q, attendu %q", folder.Kind, KindFolder)
}
if folder.ParentID == nil || *folder.ParentID != library.ID {
t.Fatalf("parent = %v, attendu %s", folder.ParentID, library.ID)
}
if folder.Depth != 1 {
t.Fatalf("depth = %d, attendu 1", folder.Depth)
}
if folder.Path != library.Path+hex.EncodeToString(folder.ID[:])+"/" {
t.Fatalf("path = %q", folder.Path)
}
if folder.Visibility != "" {
t.Fatalf("visibility = %q, attendu vide", folder.Visibility)
}
if folder.PolicyID != nil {
t.Fatalf("policy = %v, attendu nil", folder.PolicyID)
}
if !folder.ACLInherit {
t.Fatal("acl_inherit = false, attendu true")
}
}
func TestCreateFolderRejectsMissingParent(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
missing, err := ident.NewV7()
if err != nil {
t.Fatalf("NewV7 : %v", err)
}
_, err = service.CreateFolder(ctx, CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: missing,
Name: "Vacances",
})
if !errors.Is(err, ErrParentNotFound) {
t.Fatalf("erreur = %v, attendu ErrParentNotFound", err)
}
}
func TestCreateFolderRejectsDeletedParent(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
if _, err := service.Trash(ctx, library.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
_, err := service.CreateFolder(ctx, CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: library.ID,
Name: "Vacances",
})
if !errors.Is(err, ErrParentDeleted) {
t.Fatalf("erreur = %v, attendu ErrParentDeleted", err)
}
}
func TestCreateFolderRejectsInvalidParent(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
movie := mustKindDocument(t, service, owner, library, "movie", "Film")
_, err := service.CreateFolder(ctx, CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: movie.ID,
Name: "Extras",
})
if !errors.Is(err, ErrInvalidParent) {
t.Fatalf("erreur = %v, attendu ErrInvalidParent", err)
}
}
func TestCreateFolderRejectsDuplicateSibling(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
mustFolder(t, service, owner, library.ID, "Vacances")
_, err := service.CreateFolder(ctx, CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: library.ID,
Name: "vacances",
})
if !errors.Is(err, ErrNameTaken) {
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
}
}
+63 -3
View File
@@ -1,5 +1,11 @@
package document
import (
"errors"
"mediarr/ident"
)
const (
VisibilityPrivate = "PRIVATE"
VisibilityCluster = "CLUSTER"
@@ -7,11 +13,65 @@ const (
VisibilityPublic = "PUBLIC"
)
const (
KindLibrary = "library"
KindFolder = "folder"
)
type Document struct {
ID ident.UUID
Kind string
Hidden string
OwnerID ident.UUID
CreatedBy ident.UUID
ParentID *ident.UUID
Name string
NameKey string
Path string
Depth int64
Position *string
HeadVersionID *ident.UUID
Metadata string
PolicyID *ident.UUID
Visibility string
ACLInherit bool
Rev int64
CreatedAt int64
UpdatedAt int64
DeletedAt *int64
DeletedBy *ident.UUID
TrashBatch []byte
}
func NewDocument() {
type CreateLibraryParams struct {
OwnerID ident.UUID
CreatedBy ident.UUID
Name string
PolicyID ident.UUID
Visibility string
ACLInherit *bool
Metadata string
}
type CreateFolderParams struct {
OwnerID ident.UUID
CreatedBy ident.UUID
ParentID ident.UUID
Name string
ACLInherit *bool
Metadata string
}
var (
ErrInvalidName = errors.New("nom de document invalide")
ErrNameTaken = errors.New("nom de document déjà utilisé")
ErrDocumentNotFound = errors.New("document introuvable")
ErrDocumentDeleted = errors.New("document supprimé")
ErrParentNotFound = errors.New("parent introuvable")
ErrParentDeleted = errors.New("parent supprimé")
ErrInvalidParent = errors.New("parent invalide : bibliothèque ou dossier attendu")
ErrCannotMoveRoot = errors.New("déplacement d'une bibliothèque racine interdit")
ErrInvalidMove = errors.New("déplacement invalide")
ErrInvalidVisibility = errors.New("visibilité invalide")
ErrPolicyNotFound = errors.New("politique de stockage introuvable")
ErrInvalidTrashBatch = errors.New("lot de corbeille invalide")
)
+116
View File
@@ -0,0 +1,116 @@
package document
import (
"context"
"encoding/hex"
"strings"
"testing"
"mediarr/database"
"mediarr/ident"
"mediarr/identity"
)
var testPolicyID = ident.MustParse("00000000-0000-7000-8000-000000000101")
func newTestService(t *testing.T) *Service {
t.Helper()
t.Chdir(t.TempDir())
err, db := database.NewDatabase(database.NewDatabaseParams{})
if err != nil {
t.Fatalf("NewDatabase : %v", err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil {
t.Errorf("Close : %v", err)
}
})
return NewService(*db)
}
func mustPrincipal(t *testing.T, service *Service, kind, name string) *identity.Principal {
t.Helper()
principal, err := identity.NewService(service.db).CreatePrincipal(context.Background(), identity.CreatePrincipalParams{
Kind: kind,
Name: name,
})
if err != nil {
t.Fatalf("CreatePrincipal(%q) : %v", name, err)
}
return principal
}
func mustUser(t *testing.T, service *Service, name string) *identity.Principal {
return mustPrincipal(t, service, identity.KindUser, name)
}
func mustLibrary(t *testing.T, service *Service, owner *identity.Principal, name string) *Document {
t.Helper()
library, err := service.CreateLibrary(context.Background(), CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: name,
PolicyID: testPolicyID,
})
if err != nil {
t.Fatalf("CreateLibrary(%q) : %v", name, err)
}
return library
}
func mustFolder(t *testing.T, service *Service, owner *identity.Principal, parentID ident.UUID, name string) *Document {
t.Helper()
folder, err := service.CreateFolder(context.Background(), CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: parentID,
Name: name,
})
if err != nil {
t.Fatalf("CreateFolder(%q) : %v", name, err)
}
return folder
}
func mustKindDocument(t *testing.T, service *Service, owner *identity.Principal, parent *Document, kind, name string) *Document {
t.Helper()
id, err := ident.NewV7()
if err != nil {
t.Fatalf("NewV7 : %v", err)
}
now := nowMillis()
created, err := service.db.WriteQueries.CreateDocument(context.Background(), database.CreateDocumentParams{
ID: id,
Kind: kind,
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: &parent.ID,
Name: name,
NameKey: strings.ToLower(name),
Path: parent.Path + hex.EncodeToString(id[:]) + "/",
Depth: parent.Depth + 1,
Metadata: "{}",
AclInherit: 1,
Rev: 1,
CreatedAt: now,
UpdatedAt: now,
})
if err != nil {
t.Fatalf("CreateDocument(%q) : %v", name, err)
}
return documentFromDB(created)
}
+203
View File
@@ -0,0 +1,203 @@
package document
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"strings"
"mediarr/database"
"mediarr/ident"
)
func (s *Service) Rename(ctx context.Context, documentID ident.UUID, name string) (*Document, error) {
if _, err := s.getActiveDocument(ctx, documentID); err != nil {
return nil, err
}
normalized, nameKey, err := normalizeName(name)
if err != nil {
return nil, err
}
updated, err := s.db.WriteQueries.UpdateDocumentName(ctx, database.UpdateDocumentNameParams{
Name: normalized,
NameKey: nameKey,
UpdatedAt: nowMillis(),
ID: documentID,
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%w: %s", ErrDocumentNotFound, documentID)
}
if isUniqueViolation(err) {
return nil, fmt.Errorf("%w: %s", ErrNameTaken, normalized)
}
return nil, err
}
return documentFromDB(updated), nil
}
func (s *Service) Move(ctx context.Context, documentID, newParentID ident.UUID) (*Document, error) {
document, err := s.getActiveDocument(ctx, documentID)
if err != nil {
return nil, err
}
if document.ParentID == nil {
return nil, ErrCannotMoveRoot
}
if *document.ParentID == newParentID {
return documentFromDB(*document), nil
}
if document.ID == newParentID {
return nil, ErrInvalidMove
}
parent, err := s.getDocument(ctx, newParentID)
if err != nil {
if errors.Is(err, ErrDocumentNotFound) {
return nil, fmt.Errorf("%w: %s", ErrParentNotFound, newParentID)
}
return nil, err
}
if parent.DeletedAt.Valid {
return nil, fmt.Errorf("%w: %s", ErrParentDeleted, newParentID)
}
if !isContainerKind(parent.Kind) {
return nil, fmt.Errorf("%w: %s", ErrInvalidParent, parent.Kind)
}
if strings.HasPrefix(parent.Path, document.Path) {
return nil, ErrInvalidMove
}
newPath := parent.Path + hex.EncodeToString(document.ID[:]) + "/"
newDepth := parent.Depth + 1
depthDelta := newDepth - document.Depth
now := nowMillis()
var moved database.Document
err = s.withTx(ctx, func(q *database.Queries) error {
updated, err := q.MoveDocument(ctx, database.MoveDocumentParams{
ParentID: &newParentID,
Path: newPath,
Depth: newDepth,
UpdatedAt: now,
ID: documentID,
})
if err != nil {
return err
}
moved = updated
descendants, err := q.ListDocumentDescendants(ctx, database.ListDocumentDescendantsParams{
Prefix: document.Path,
RootID: documentID,
})
if err != nil {
return err
}
for _, descendant := range descendants {
relativePath := strings.TrimPrefix(descendant.Path, document.Path)
if err := q.UpdateDocumentLocation(ctx, database.UpdateDocumentLocationParams{
Path: newPath + relativePath,
Depth: descendant.Depth + depthDelta,
UpdatedAt: now,
ID: descendant.ID,
}); err != nil {
return err
}
}
return nil
})
if err != nil {
if isUniqueViolation(err) {
return nil, fmt.Errorf("%w: %s", ErrNameTaken, document.Name)
}
return nil, err
}
return documentFromDB(moved), nil
}
func (s *Service) Trash(ctx context.Context, documentID, deletedBy ident.UUID) (*Document, error) {
document, err := s.getActiveDocument(ctx, documentID)
if err != nil {
return nil, err
}
batch, err := ident.NewV7()
if err != nil {
return nil, err
}
now := nowMillis()
deleted, err := s.db.WriteQueries.TrashDocumentSubtree(ctx, database.TrashDocumentSubtreeParams{
DeletedAt: sql.NullInt64{
Int64: now,
Valid: true,
},
DeletedBy: &deletedBy,
TrashBatch: batch.Bytes(),
UpdatedAt: now,
Prefix: document.Path,
})
if err != nil {
return nil, err
}
if deleted == 0 {
return nil, fmt.Errorf("%w: %s", ErrDocumentNotFound, documentID)
}
return s.Get(ctx, documentID)
}
func (s *Service) Restore(ctx context.Context, documentID ident.UUID) (*Document, error) {
document, err := s.getDocument(ctx, documentID)
if err != nil {
return nil, err
}
if !document.DeletedAt.Valid {
return documentFromDB(*document), nil
}
if len(document.TrashBatch) == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidTrashBatch, documentID)
}
for parentID := document.ParentID; parentID != nil; {
parent, err := s.getDocument(ctx, *parentID)
if err != nil {
if errors.Is(err, ErrDocumentNotFound) {
return nil, fmt.Errorf("%w: %s", ErrParentNotFound, *parentID)
}
return nil, err
}
if parent.DeletedAt.Valid && !bytes.Equal(parent.TrashBatch, document.TrashBatch) {
return nil, fmt.Errorf("%w: %s", ErrParentDeleted, *parentID)
}
parentID = parent.ParentID
}
restored, err := s.db.WriteQueries.RestoreDocumentBatch(ctx, database.RestoreDocumentBatchParams{
UpdatedAt: nowMillis(),
TrashBatch: document.TrashBatch,
})
if err != nil {
if isUniqueViolation(err) {
return nil, fmt.Errorf("%w: %s", ErrNameTaken, document.Name)
}
return nil, err
}
if restored == 0 {
return nil, fmt.Errorf("%w: %s", ErrDocumentNotFound, documentID)
}
return s.Get(ctx, documentID)
}
+402
View File
@@ -0,0 +1,402 @@
package document
import (
"bytes"
"context"
"encoding/hex"
"errors"
"testing"
)
func TestRename(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
renamed, err := service.Rename(ctx, folder.ID, "Aventure")
if err != nil {
t.Fatalf("Rename : %v", err)
}
if renamed.Name != "Aventure" || renamed.NameKey != "aventure" {
t.Fatalf("nom = %q/%q, attendu Aventure/aventure", renamed.Name, renamed.NameKey)
}
if renamed.Rev != folder.Rev+1 {
t.Fatalf("rev = %d, attendu %d", renamed.Rev, folder.Rev+1)
}
if _, err := service.Rename(ctx, folder.ID, "a/b"); !errors.Is(err, ErrInvalidName) {
t.Fatalf("erreur = %v, attendu ErrInvalidName", err)
}
other := mustFolder(t, service, owner, library.ID, "Drame")
if _, err := service.Rename(ctx, other.ID, "aventure"); !errors.Is(err, ErrNameTaken) {
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
}
if _, err := service.Trash(ctx, other.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
if _, err := service.Rename(ctx, other.ID, "Autre"); !errors.Is(err, ErrDocumentDeleted) {
t.Fatalf("erreur = %v, attendu ErrDocumentDeleted", err)
}
}
func TestMove(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
libraryA := mustLibrary(t, service, owner, "Photos")
libraryB := mustLibrary(t, service, owner, "Films")
folder := mustFolder(t, service, owner, libraryA.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
moved, err := service.Move(ctx, folder.ID, libraryB.ID)
if err != nil {
t.Fatalf("Move : %v", err)
}
if moved.ParentID == nil || *moved.ParentID != libraryB.ID {
t.Fatalf("parent = %v, attendu %s", moved.ParentID, libraryB.ID)
}
if moved.Path != libraryB.Path+hex.EncodeToString(folder.ID[:])+"/" {
t.Fatalf("path = %q", moved.Path)
}
if moved.Depth != 1 {
t.Fatalf("depth = %d, attendu 1", moved.Depth)
}
if moved.Rev != folder.Rev+1 {
t.Fatalf("rev = %d, attendu %d", moved.Rev, folder.Rev+1)
}
movedChild, err := service.Get(ctx, child.ID)
if err != nil {
t.Fatalf("Get(child) : %v", err)
}
if movedChild.ParentID == nil || *movedChild.ParentID != folder.ID {
t.Fatalf("parent enfant = %v, attendu %s", movedChild.ParentID, folder.ID)
}
if movedChild.Path != moved.Path+hex.EncodeToString(child.ID[:])+"/" {
t.Fatalf("path enfant = %q", movedChild.Path)
}
if movedChild.Depth != 2 {
t.Fatalf("depth enfant = %d, attendu 2", movedChild.Depth)
}
if movedChild.Rev != child.Rev+1 {
t.Fatalf("rev enfant = %d, attendu %d", movedChild.Rev, child.Rev+1)
}
children, err := service.ListChildren(ctx, libraryB.ID)
if err != nil {
t.Fatalf("ListChildren : %v", err)
}
if len(children) != 1 || children[0].ID != folder.ID {
t.Fatalf("enfants = %+v", children)
}
}
func TestMoveRootRejected(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
other := mustLibrary(t, service, owner, "Films")
_, err := service.Move(ctx, library.ID, other.ID)
if !errors.Is(err, ErrCannotMoveRoot) {
t.Fatalf("erreur = %v, attendu ErrCannotMoveRoot", err)
}
}
func TestMoveIntoDescendantRejected(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
_, err := service.Move(ctx, folder.ID, child.ID)
if !errors.Is(err, ErrInvalidMove) {
t.Fatalf("erreur = %v, attendu ErrInvalidMove", err)
}
}
func TestMoveIntoItselfRejected(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
_, err := service.Move(ctx, folder.ID, folder.ID)
if !errors.Is(err, ErrInvalidMove) {
t.Fatalf("erreur = %v, attendu ErrInvalidMove", err)
}
}
func TestMoveToInvalidParentRejected(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
movie := mustKindDocument(t, service, owner, library, "movie", "Film")
_, err := service.Move(ctx, folder.ID, movie.ID)
if !errors.Is(err, ErrInvalidParent) {
t.Fatalf("erreur = %v, attendu ErrInvalidParent", err)
}
}
func TestMoveToSameParentIsNoop(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
moved, err := service.Move(ctx, folder.ID, library.ID)
if err != nil {
t.Fatalf("Move : %v", err)
}
if moved.Rev != folder.Rev {
t.Fatalf("rev = %d, attendu %d", moved.Rev, folder.Rev)
}
}
func TestMoveDuplicateNameRejected(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
libraryA := mustLibrary(t, service, owner, "Photos")
libraryB := mustLibrary(t, service, owner, "Films")
folder := mustFolder(t, service, owner, libraryA.ID, "Action")
mustFolder(t, service, owner, libraryB.ID, "action")
_, err := service.Move(ctx, folder.ID, libraryB.ID)
if !errors.Is(err, ErrNameTaken) {
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
}
}
func TestMoveRejectsDeletedDocument(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
libraryA := mustLibrary(t, service, owner, "Photos")
libraryB := mustLibrary(t, service, owner, "Films")
folder := mustFolder(t, service, owner, libraryA.ID, "Action")
if _, err := service.Trash(ctx, folder.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
_, err := service.Move(ctx, folder.ID, libraryB.ID)
if !errors.Is(err, ErrDocumentDeleted) {
t.Fatalf("erreur = %v, attendu ErrDocumentDeleted", err)
}
}
func TestMoveRejectsDeletedParent(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
libraryA := mustLibrary(t, service, owner, "Photos")
libraryB := mustLibrary(t, service, owner, "Films")
folder := mustFolder(t, service, owner, libraryA.ID, "Action")
if _, err := service.Trash(ctx, libraryB.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
_, err := service.Move(ctx, folder.ID, libraryB.ID)
if !errors.Is(err, ErrParentDeleted) {
t.Fatalf("erreur = %v, attendu ErrParentDeleted", err)
}
}
func TestTrashAndRestore(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
trashed, err := service.Trash(ctx, folder.ID, owner.ID)
if err != nil {
t.Fatalf("Trash : %v", err)
}
if trashed.DeletedAt == nil {
t.Fatal("deleted_at non renseigné")
}
if trashed.DeletedBy == nil || *trashed.DeletedBy != owner.ID {
t.Fatalf("deleted_by = %v, attendu %s", trashed.DeletedBy, owner.ID)
}
if len(trashed.TrashBatch) == 0 {
t.Fatal("trash_batch non renseigné")
}
trashedChild, err := service.Get(ctx, child.ID)
if err != nil {
t.Fatalf("Get(child) : %v", err)
}
if trashedChild.DeletedAt == nil {
t.Fatal("enfant non supprimé")
}
if !bytes.Equal(trashedChild.TrashBatch, trashed.TrashBatch) {
t.Fatal("l’enfant n’appartient pas au même lot de corbeille")
}
children, err := service.ListChildren(ctx, library.ID)
if err != nil {
t.Fatalf("ListChildren : %v", err)
}
if len(children) != 0 {
t.Fatalf("enfants = %d, attendu 0", len(children))
}
restored, err := service.Restore(ctx, folder.ID)
if err != nil {
t.Fatalf("Restore : %v", err)
}
if restored.DeletedAt != nil || restored.DeletedBy != nil || len(restored.TrashBatch) != 0 {
t.Fatalf("document restauré avec des champs de corbeille : %+v", restored)
}
restoredChild, err := service.Get(ctx, child.ID)
if err != nil {
t.Fatalf("Get(child restauré) : %v", err)
}
if restoredChild.DeletedAt != nil {
t.Fatal("enfant non restauré")
}
children, err = service.ListChildren(ctx, library.ID)
if err != nil {
t.Fatalf("ListChildren après restauration : %v", err)
}
if len(children) != 1 || children[0].ID != folder.ID {
t.Fatalf("enfants après restauration = %+v", children)
}
}
func TestRestoreNonDeletedIsNoop(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
restored, err := service.Restore(ctx, library.ID)
if err != nil {
t.Fatalf("Restore : %v", err)
}
if restored.ID != library.ID || restored.DeletedAt != nil {
t.Fatalf("document = %+v", restored)
}
}
func TestTrashAlreadyDeleted(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
if _, err := service.Trash(ctx, library.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
if _, err := service.Trash(ctx, library.ID, owner.ID); !errors.Is(err, ErrDocumentDeleted) {
t.Fatalf("erreur = %v, attendu ErrDocumentDeleted", err)
}
}
func TestRestoreConflict(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
if _, err := service.Trash(ctx, folder.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
mustFolder(t, service, owner, library.ID, "Action")
if _, err := service.Restore(ctx, folder.ID); !errors.Is(err, ErrNameTaken) {
t.Fatalf("erreur = %v, attendu ErrNameTaken", err)
}
}
func TestRestoreParentDeletedInDifferentBatch(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
if _, err := service.Trash(ctx, child.ID, owner.ID); err != nil {
t.Fatalf("Trash(child) : %v", err)
}
if _, err := service.Trash(ctx, folder.ID, owner.ID); err != nil {
t.Fatalf("Trash(folder) : %v", err)
}
if _, err := service.Restore(ctx, child.ID); !errors.Is(err, ErrParentDeleted) {
t.Fatalf("erreur = %v, attendu ErrParentDeleted", err)
}
}
func TestRestoreRejectsDeletedAncestor(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
folder := mustFolder(t, service, owner, library.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
if _, err := service.Trash(ctx, folder.ID, owner.ID); err != nil {
t.Fatalf("Trash(folder) : %v", err)
}
if _, err := service.Trash(ctx, library.ID, owner.ID); err != nil {
t.Fatalf("Trash(library) : %v", err)
}
if _, err := service.Restore(ctx, child.ID); !errors.Is(err, ErrParentDeleted) {
t.Fatalf("erreur = %v, attendu ErrParentDeleted", err)
}
}
func TestMoveUpdatesTrashedDescendants(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
libraryA := mustLibrary(t, service, owner, "Photos")
libraryB := mustLibrary(t, service, owner, "Films")
folder := mustFolder(t, service, owner, libraryA.ID, "Action")
child := mustFolder(t, service, owner, folder.ID, "Extras")
if _, err := service.Trash(ctx, child.ID, owner.ID); err != nil {
t.Fatalf("Trash(child) : %v", err)
}
moved, err := service.Move(ctx, folder.ID, libraryB.ID)
if err != nil {
t.Fatalf("Move : %v", err)
}
restored, err := service.Restore(ctx, child.ID)
if err != nil {
t.Fatalf("Restore(child) : %v", err)
}
if restored.Path != moved.Path+hex.EncodeToString(child.ID[:])+"/" {
t.Fatalf("path = %q, attendu %q", restored.Path, moved.Path+hex.EncodeToString(child.ID[:])+"/")
}
if restored.Depth != 2 {
t.Fatalf("depth = %d, attendu 2", restored.Depth)
}
}
+48
View File
@@ -0,0 +1,48 @@
package document
import (
"context"
"mediarr/ident"
)
func (s *Service) Get(ctx context.Context, id ident.UUID) (*Document, error) {
document, err := s.getDocument(ctx, id)
if err != nil {
return nil, err
}
return documentFromDB(*document), nil
}
func (s *Service) ListChildren(ctx context.Context, parentID ident.UUID) ([]Document, error) {
if _, err := s.getActiveDocument(ctx, parentID); err != nil {
return nil, err
}
rows, err := s.db.Queries.ListDocumentChildren(ctx, &parentID)
if err != nil {
return nil, err
}
documents := make([]Document, 0, len(rows))
for _, row := range rows {
documents = append(documents, *documentFromDB(row))
}
return documents, nil
}
func (s *Service) ListLibraries(ctx context.Context) ([]Document, error) {
rows, err := s.db.Queries.ListLibraries(ctx)
if err != nil {
return nil, err
}
documents := make([]Document, 0, len(rows))
for _, row := range rows {
documents = append(documents, *documentFromDB(row))
}
return documents, nil
}
+110
View File
@@ -0,0 +1,110 @@
package document
import (
"context"
"errors"
"testing"
"mediarr/ident"
)
func TestListLibraries(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
mustLibrary(t, service, owner, "Photos")
mustLibrary(t, service, owner, "Films")
libraries, err := service.ListLibraries(ctx)
if err != nil {
t.Fatalf("ListLibraries : %v", err)
}
if len(libraries) != 2 {
t.Fatalf("bibliothèques = %d, attendu 2", len(libraries))
}
if libraries[0].Name != "Films" || libraries[1].Name != "Photos" {
t.Fatalf("ordre = %q, %q", libraries[0].Name, libraries[1].Name)
}
}
func TestListChildren(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
mustFolder(t, service, owner, library.ID, "B")
a := mustFolder(t, service, owner, library.ID, "A")
children, err := service.ListChildren(ctx, library.ID)
if err != nil {
t.Fatalf("ListChildren : %v", err)
}
if len(children) != 2 || children[0].Name != "A" || children[1].Name != "B" {
t.Fatalf("enfants = %+v", children)
}
if _, err := service.Trash(ctx, a.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
children, err = service.ListChildren(ctx, library.ID)
if err != nil {
t.Fatalf("ListChildren après trash : %v", err)
}
if len(children) != 1 || children[0].Name != "B" {
t.Fatalf("enfants après trash = %+v", children)
}
}
func TestGetDeletedDocument(t *testing.T) {
service := newTestService(t)
ctx := context.Background()
owner := mustUser(t, service, "owner")
library := mustLibrary(t, service, owner, "Photos")
if _, err := service.Trash(ctx, library.ID, owner.ID); err != nil {
t.Fatalf("Trash : %v", err)
}
deleted, err := service.Get(ctx, library.ID)
if err != nil {
t.Fatalf("Get : %v", err)
}
if deleted.DeletedAt == nil {
t.Fatal("deleted_at non renseigné")
}
if deleted.DeletedBy == nil || *deleted.DeletedBy != owner.ID {
t.Fatalf("deleted_by = %v, attendu %s", deleted.DeletedBy, owner.ID)
}
if len(deleted.TrashBatch) == 0 {
t.Fatal("trash_batch non renseigné")
}
}
func TestGetMissingDocument(t *testing.T) {
service := newTestService(t)
missing, err := ident.NewV7()
if err != nil {
t.Fatalf("NewV7 : %v", err)
}
_, err = service.Get(context.Background(), missing)
if !errors.Is(err, ErrDocumentNotFound) {
t.Fatalf("erreur = %v, attendu ErrDocumentNotFound", err)
}
}
func TestListChildrenMissingParent(t *testing.T) {
service := newTestService(t)
missing, err := ident.NewV7()
if err != nil {
t.Fatalf("NewV7 : %v", err)
}
_, err = service.ListChildren(context.Background(), missing)
if !errors.Is(err, ErrDocumentNotFound) {
t.Fatalf("erreur = %v, attendu ErrDocumentNotFound", err)
}
}
+152
View File
@@ -0,0 +1,152 @@
package document
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"mediarr/database"
"mediarr/ident"
)
type Service struct {
db database.DatabaseClient
}
func NewService(db database.DatabaseClient) *Service {
return &Service{db: db}
}
func (s *Service) withTx(ctx context.Context, fn func(*database.Queries) error) error {
tx, err := s.db.WriteDB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() {
_ = tx.Rollback()
}()
if err := fn(s.db.WriteQueries.WithTx(tx)); err != nil {
return err
}
return tx.Commit()
}
func (s *Service) getDocument(ctx context.Context, id ident.UUID) (*database.Document, error) {
document, err := s.db.Queries.GetDocument(ctx, id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%w: %s", ErrDocumentNotFound, id)
}
return nil, err
}
return &document, nil
}
func (s *Service) getActiveDocument(ctx context.Context, id ident.UUID) (*database.Document, error) {
document, err := s.getDocument(ctx, id)
if err != nil {
return nil, err
}
if document.DeletedAt.Valid {
return nil, fmt.Errorf("%w: %s", ErrDocumentDeleted, id)
}
return document, nil
}
func normalizeName(name string) (string, string, error) {
normalized := strings.TrimSpace(name)
if normalized == "" || len(normalized) > 255 || strings.Contains(normalized, "/") || strings.ContainsRune(normalized, 0) {
return "", "", fmt.Errorf("%w: %q", ErrInvalidName, name)
}
return normalized, strings.ToLower(normalized), nil
}
func normalizeVisibility(visibility string) (string, error) {
if visibility == "" {
return VisibilityPrivate, nil
}
switch visibility {
case VisibilityPrivate, VisibilityCluster, VisibilityFederated, VisibilityPublic:
return visibility, nil
default:
return "", fmt.Errorf("%w: %q", ErrInvalidVisibility, visibility)
}
}
func metadataValue(metadata string) string {
if metadata == "" {
return "{}"
}
return metadata
}
func aclInheritValue(value *bool) int64 {
if value == nil || *value {
return 1
}
return 0
}
func isContainerKind(kind string) bool {
return kind == KindLibrary || kind == KindFolder
}
func isUniqueViolation(err error) bool {
return err != nil && strings.Contains(strings.ToLower(err.Error()), "unique constraint failed")
}
func documentFromDB(document database.Document) *Document {
visibility := ""
if document.Visibility.Valid {
visibility = document.Visibility.String
}
var position *string
if document.Position.Valid {
value := document.Position.String
position = &value
}
var deletedAt *int64
if document.DeletedAt.Valid {
value := document.DeletedAt.Int64
deletedAt = &value
}
return &Document{
ID: document.ID,
Kind: document.Kind,
OwnerID: document.OwnerID,
CreatedBy: document.CreatedBy,
ParentID: document.ParentID,
Name: document.Name,
NameKey: document.NameKey,
Path: document.Path,
Depth: document.Depth,
Position: position,
HeadVersionID: document.HeadVersionID,
Metadata: document.Metadata,
PolicyID: document.PolicyID,
Visibility: visibility,
ACLInherit: document.AclInherit != 0,
Rev: document.Rev,
CreatedAt: document.CreatedAt,
UpdatedAt: document.UpdatedAt,
DeletedAt: deletedAt,
DeletedBy: document.DeletedBy,
TrashBatch: document.TrashBatch,
}
}
func nowMillis() int64 {
return time.Now().UnixMilli()
}
+3 -1
View File
@@ -1,5 +1,7 @@
package node
func (n *Node) AddDocument() {
import "mediarr/document"
func (n *Node) Documents() *document.Service {
return document.NewService(n.db)
}
+65
View File
@@ -0,0 +1,65 @@
package node
import (
"context"
"testing"
"mediarr/document"
"mediarr/ident"
"mediarr/identity"
)
func TestNodeDocuments(t *testing.T) {
t.Chdir(t.TempDir())
err, node := NewNode(NewNodeParams{DatabaseName: "documents"})
if err != nil {
t.Fatalf("NewNode : %v", err)
}
t.Cleanup(func() {
if err := node.Close(); err != nil {
t.Errorf("Close : %v", err)
}
})
if err := node.Up(); err != nil {
t.Fatalf("Up : %v", err)
}
ctx := context.Background()
owner, err := node.Identity().CreatePrincipal(ctx, identity.CreatePrincipalParams{
Kind: identity.KindUser,
Name: "alice",
})
if err != nil {
t.Fatalf("CreatePrincipal : %v", err)
}
policyID := ident.MustParse("00000000-0000-7000-8000-000000000101")
library, err := node.Documents().CreateLibrary(ctx, document.CreateLibraryParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
Name: "Photos",
PolicyID: policyID,
})
if err != nil {
t.Fatalf("CreateLibrary : %v", err)
}
if library.Kind != document.KindLibrary {
t.Fatalf("kind = %q, attendu %q", library.Kind, document.KindLibrary)
}
folder, err := node.Documents().CreateFolder(ctx, document.CreateFolderParams{
OwnerID: owner.ID,
CreatedBy: owner.ID,
ParentID: library.ID,
Name: "Vacances",
})
if err != nil {
t.Fatalf("CreateFolder : %v", err)
}
if folder.ParentID == nil || *folder.ParentID != library.ID {
t.Fatalf("parent = %v, attendu %s", folder.ParentID, library.ID)
}
}