Files tab: multi-selection, drag-and-drop, keyboard shortcuts, custom confirm modal, SVG icons
This commit is contained in:
+288
-2
@@ -3,6 +3,7 @@ package files
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"verstak/internal/core/nodes"
|
||||
"verstak/internal/core/storage"
|
||||
"verstak/internal/core/util"
|
||||
)
|
||||
@@ -32,15 +34,25 @@ type Record struct {
|
||||
Missing bool `json:"missing"`
|
||||
}
|
||||
|
||||
// ImportSummary describes a scanned directory before import.
|
||||
type ImportSummary struct {
|
||||
Files int `json:"files"`
|
||||
Folders int `json:"folders"`
|
||||
TotalBytes int64 `json:"totalBytes"`
|
||||
IsDangerous bool `json:"isDangerous"`
|
||||
DangerReason string `json:"dangerReason,omitempty"`
|
||||
}
|
||||
|
||||
// Service provides file operations inside a vault.
|
||||
type Service struct {
|
||||
db *storage.DB
|
||||
vaultRoot string
|
||||
nodes *nodes.Repository
|
||||
}
|
||||
|
||||
// NewService creates a file service bound to a vault.
|
||||
func NewService(db *storage.DB, vaultRoot string) *Service {
|
||||
return &Service{db: db, vaultRoot: vaultRoot}
|
||||
func NewService(db *storage.DB, vaultRoot string, nodeRepo *nodes.Repository) *Service {
|
||||
return &Service{db: db, vaultRoot: vaultRoot, nodes: nodeRepo}
|
||||
}
|
||||
|
||||
// DB returns the underlying storage.
|
||||
@@ -166,6 +178,280 @@ func (s *Service) Open(id string) error {
|
||||
return openWithSystem(abs)
|
||||
}
|
||||
|
||||
// maxPreviewSize is the maximum file size (5 MB) for inline preview.
|
||||
const maxPreviewSize = 5 * 1024 * 1024
|
||||
|
||||
// ReadText reads a file's content as text, up to maxPreviewSize.
|
||||
func (s *Service) ReadText(id string) (string, error) {
|
||||
rec, err := s.Get(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if rec.Size > maxPreviewSize {
|
||||
return "", fmt.Errorf("file too large for preview (%d bytes)", rec.Size)
|
||||
}
|
||||
var abs string
|
||||
if rec.StorageMode == "vault" {
|
||||
abs = filepath.Join(s.vaultRoot, rec.Path)
|
||||
} else {
|
||||
abs = rec.Path
|
||||
}
|
||||
b, err := os.ReadFile(abs)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read: %w", err)
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// ReadBase64 reads a file and returns a data URI (base64-encoded).
|
||||
func (s *Service) ReadBase64(id string) (string, error) {
|
||||
rec, err := s.Get(id)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if rec.Size > maxPreviewSize {
|
||||
return "", fmt.Errorf("file too large for preview (%d bytes)", rec.Size)
|
||||
}
|
||||
var abs string
|
||||
if rec.StorageMode == "vault" {
|
||||
abs = filepath.Join(s.vaultRoot, rec.Path)
|
||||
} else {
|
||||
abs = rec.Path
|
||||
}
|
||||
b, err := os.ReadFile(abs)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read: %w", err)
|
||||
}
|
||||
mime := rec.MIME
|
||||
if mime == "" {
|
||||
mime = "application/octet-stream"
|
||||
}
|
||||
return fmt.Sprintf("data:%s;base64,%s", mime, base64.StdEncoding.EncodeToString(b)), nil
|
||||
}
|
||||
|
||||
// CreateEmptyFile creates a file node and an empty vault file.
|
||||
func (s *Service) CreateEmptyFile(parentID, filename string) (*nodes.Node, error) {
|
||||
filename = s.uniqueTitle(parentID, filename)
|
||||
node, err := s.nodes.Create(parentID, nodes.TypeFile, filename, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dir := filepath.Join(s.vaultRoot, "spaces", node.Slug)
|
||||
if err := os.MkdirAll(dir, 0o750); err != nil {
|
||||
return nil, fmt.Errorf("mkdir: %w", err)
|
||||
}
|
||||
dest := filepath.Join(dir, filename)
|
||||
f, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create file: %w", err)
|
||||
}
|
||||
f.Close()
|
||||
relPath, _ := filepath.Rel(s.vaultRoot, dest)
|
||||
_, err = s.insertRecord(node.ID, filename, relPath, "vault", 0, "")
|
||||
return node, err
|
||||
}
|
||||
|
||||
// Duplicate creates a copy of a node and its file record under the same parent.
|
||||
func (s *Service) Duplicate(nodeID string) (*nodes.Node, error) {
|
||||
original, err := s.nodes.GetActive(nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentID := ""
|
||||
if original.ParentID != nil {
|
||||
parentID = *original.ParentID
|
||||
}
|
||||
newName := s.uniqueTitle(parentID, original.Title)
|
||||
node, err := s.nodes.Create(parentID, original.Type, newName, original.Section)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if original.Type == nodes.TypeFile {
|
||||
records, _ := s.ListByNode(original.ID)
|
||||
if len(records) > 0 {
|
||||
src := &records[0]
|
||||
if src.StorageMode == "vault" {
|
||||
srcPath := filepath.Join(s.vaultRoot, src.Path)
|
||||
dir := filepath.Join(s.vaultRoot, "spaces", node.Slug)
|
||||
os.MkdirAll(dir, 0o750)
|
||||
dst := filepath.Join(dir, newName)
|
||||
hash, err := copyAndHash(srcPath, dst)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("copy file: %w", err)
|
||||
}
|
||||
relPath, _ := filepath.Rel(s.vaultRoot, dst)
|
||||
_, err = s.insertRecord(node.ID, newName, relPath, "vault", src.Size, hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// External file: create a new record pointing to the same absolute path.
|
||||
_, err = s.insertRecord(node.ID, newName, src.Path, "external", src.Size, src.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return node, nil
|
||||
}
|
||||
|
||||
// AddPathCopy copies sourcePath (file or directory) into the vault under nodeID.
|
||||
func (s *Service) AddPathCopy(nodeID, sourcePath string) ([]nodes.Node, error) {
|
||||
return s.importPath(nodeID, sourcePath, true)
|
||||
}
|
||||
|
||||
// AddPathLink links sourcePath (file or directory) without copying into vault.
|
||||
func (s *Service) AddPathLink(nodeID, sourcePath string) ([]nodes.Node, error) {
|
||||
return s.importPath(nodeID, sourcePath, false)
|
||||
}
|
||||
|
||||
// PreviewImport scans sourcePath and returns a summary without importing.
|
||||
func (s *Service) PreviewImport(sourcePath string) (*ImportSummary, error) {
|
||||
info, err := os.Stat(sourcePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stat: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return &ImportSummary{Files: 1, TotalBytes: info.Size()}, nil
|
||||
}
|
||||
|
||||
var sum ImportSummary
|
||||
err = filepath.Walk(sourcePath, func(path string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
if fi.IsDir() {
|
||||
sum.Folders++
|
||||
name := strings.ToLower(fi.Name())
|
||||
if name == ".git" || name == "node_modules" || name == ".cache" {
|
||||
sum.IsDangerous = true
|
||||
sum.DangerReason = fmt.Sprintf("содержит %s", fi.Name())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
sum.Files++
|
||||
sum.TotalBytes += fi.Size()
|
||||
return nil
|
||||
})
|
||||
if sum.Files > 1000 && !sum.IsDangerous {
|
||||
sum.IsDangerous = true
|
||||
sum.DangerReason = "более 1000 файлов"
|
||||
}
|
||||
if sum.TotalBytes > 1<<30 && !sum.IsDangerous {
|
||||
sum.IsDangerous = true
|
||||
sum.DangerReason = "более 1 GB"
|
||||
}
|
||||
return &sum, err
|
||||
}
|
||||
|
||||
// DeleteNodeAndChildren soft-deletes a node and all descendants,
|
||||
// moving vault files to trash.
|
||||
func (s *Service) DeleteNodeAndChildren(nodeID string) error {
|
||||
children, _ := s.nodes.ListChildren(nodeID, false)
|
||||
for i := range children {
|
||||
if err := s.DeleteNodeAndChildren(children[i].ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_ = s.deleteFileRecords(nodeID)
|
||||
return s.nodes.SoftDelete(nodeID)
|
||||
}
|
||||
|
||||
func (s *Service) deleteFileRecords(nodeID string) error {
|
||||
records, err := s.ListByNode(nodeID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range records {
|
||||
_ = s.DeleteToTrash(r.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) importPath(parentID, sourcePath string, copyMode bool) ([]nodes.Node, error) {
|
||||
info, err := os.Stat(sourcePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stat: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
title := s.uniqueTitle(parentID, filepath.Base(sourcePath))
|
||||
node, err := s.nodes.Create(parentID, nodes.TypeFile, title, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if copyMode {
|
||||
_, err = s.CopyIntoVault(node.ID, sourcePath, node.Slug)
|
||||
} else {
|
||||
_, err = s.AddExternal(node.ID, sourcePath)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []nodes.Node{*node}, nil
|
||||
}
|
||||
return s.importDir(parentID, sourcePath, info.Name(), copyMode)
|
||||
}
|
||||
|
||||
func (s *Service) importDir(parentID, sourcePath, dirName string, copyMode bool) ([]nodes.Node, error) {
|
||||
dirName = s.uniqueTitle(parentID, dirName)
|
||||
folderNode, err := s.nodes.Create(parentID, nodes.TypeFolder, dirName, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(sourcePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var all []nodes.Node
|
||||
all = append(all, *folderNode)
|
||||
|
||||
for _, entry := range entries {
|
||||
childPath := filepath.Join(sourcePath, entry.Name())
|
||||
if entry.IsDir() {
|
||||
children, err := s.importDir(folderNode.ID, childPath, entry.Name(), copyMode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, children...)
|
||||
} else {
|
||||
childNode, err := s.nodes.Create(folderNode.ID, nodes.TypeFile, entry.Name(), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if copyMode {
|
||||
_, err = s.CopyIntoVault(childNode.ID, childPath, childNode.Slug)
|
||||
} else {
|
||||
_, err = s.AddExternal(childNode.ID, childPath)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all = append(all, *childNode)
|
||||
}
|
||||
}
|
||||
return all, nil
|
||||
}
|
||||
|
||||
func (s *Service) uniqueTitle(parentID, desired string) string {
|
||||
children, _ := s.nodes.ListChildren(parentID, false)
|
||||
used := make(map[string]bool, len(children))
|
||||
for i := range children {
|
||||
used[children[i].Title] = true
|
||||
}
|
||||
if !used[desired] {
|
||||
return desired
|
||||
}
|
||||
for n := 2; ; n++ {
|
||||
c := fmt.Sprintf("%s (%d)", desired, n)
|
||||
if !used[c] {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- implementation details ---
|
||||
|
||||
func (s *Service) insertRecord(nodeID, filename, path, mode string, size int64, sha string) (*Record, error) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"verstak/internal/core/nodes"
|
||||
"verstak/internal/core/storage"
|
||||
)
|
||||
|
||||
@@ -23,7 +24,7 @@ func TestAddExternal(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
// Run migration 002 manually since storage.Open already applied it.
|
||||
// We can verify the table exists by inserting.
|
||||
filesSvc := NewService(db, t.TempDir())
|
||||
filesSvc := NewService(db, t.TempDir(), nodes.NewRepository(db))
|
||||
|
||||
// Create a real temp file to register.
|
||||
tmpDir := t.TempDir()
|
||||
@@ -62,7 +63,7 @@ func TestAddExternal(t *testing.T) {
|
||||
func TestCopyIntoVault(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
svc := NewService(db, vaultRoot)
|
||||
svc := NewService(db, vaultRoot, nodes.NewRepository(db))
|
||||
|
||||
// Source file.
|
||||
srcDir := t.TempDir()
|
||||
@@ -88,7 +89,7 @@ func TestCopyIntoVault(t *testing.T) {
|
||||
|
||||
func TestListByNode(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
svc := NewService(db, t.TempDir())
|
||||
svc := NewService(db, t.TempDir(), nodes.NewRepository(db))
|
||||
|
||||
os.WriteFile(filepath.Join(t.TempDir(), "a.txt"), []byte("a"), 0o640)
|
||||
f1 := filepath.Join(t.TempDir(), "a1.txt")
|
||||
@@ -111,7 +112,7 @@ func TestListByNode(t *testing.T) {
|
||||
func TestDeleteToTrash(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
svc := NewService(db, vaultRoot)
|
||||
svc := NewService(db, vaultRoot, nodes.NewRepository(db))
|
||||
|
||||
src := filepath.Join(t.TempDir(), "important.pdf")
|
||||
os.WriteFile(src, []byte("important data"), 0o640)
|
||||
@@ -140,6 +141,170 @@ func TestDeleteToTrash(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddPathCopySingleFile(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
svc := NewService(db, vaultRoot, nodeRepo)
|
||||
|
||||
parent, _ := nodeRepo.Create("", "case", "Test Case", "")
|
||||
src := filepath.Join(t.TempDir(), "doc.pdf")
|
||||
os.WriteFile(src, []byte("file content"), 0o640)
|
||||
|
||||
nodes, err := svc.AddPathCopy(parent.ID, src)
|
||||
if err != nil {
|
||||
t.Fatalf("AddPathCopy: %v", err)
|
||||
}
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("got %d nodes, want 1", len(nodes))
|
||||
}
|
||||
if nodes[0].Type != "file" {
|
||||
t.Errorf("type = %q", nodes[0].Type)
|
||||
}
|
||||
// Source intact.
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
t.Error("source should remain intact")
|
||||
}
|
||||
// File record created.
|
||||
records, _ := svc.ListByNode(nodes[0].ID)
|
||||
if len(records) != 1 {
|
||||
t.Errorf("file records = %d", len(records))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddPathLinkSingleFile(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
svc := NewService(db, vaultRoot, nodeRepo)
|
||||
|
||||
parent, _ := nodeRepo.Create("", "case", "Test Case", "")
|
||||
src := filepath.Join(t.TempDir(), "linked.pdf")
|
||||
os.WriteFile(src, []byte("linked"), 0o640)
|
||||
|
||||
nodes, err := svc.AddPathLink(parent.ID, src)
|
||||
if err != nil {
|
||||
t.Fatalf("AddPathLink: %v", err)
|
||||
}
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("got %d nodes, want 1", len(nodes))
|
||||
}
|
||||
// File record should have external storage mode.
|
||||
records, _ := svc.ListByNode(nodes[0].ID)
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("file records = %d", len(records))
|
||||
}
|
||||
if records[0].StorageMode != "external" {
|
||||
t.Errorf("storage mode = %q, want external", records[0].StorageMode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddPathCopyDirectory(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
svc := NewService(db, vaultRoot, nodeRepo)
|
||||
|
||||
parent, _ := nodeRepo.Create("", "case", "Test Case", "")
|
||||
srcDir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(srcDir, "sub"), 0o750)
|
||||
os.WriteFile(filepath.Join(srcDir, "a.txt"), []byte("a"), 0o640)
|
||||
os.WriteFile(filepath.Join(srcDir, "sub", "b.txt"), []byte("bb"), 0o640)
|
||||
|
||||
nodes, err := svc.AddPathCopy(parent.ID, srcDir)
|
||||
if err != nil {
|
||||
t.Fatalf("AddPathCopy dir: %v", err)
|
||||
}
|
||||
// Should create: folder node + file node + sub folder node + file node in sub.
|
||||
if len(nodes) < 3 {
|
||||
t.Errorf("expected 3+ nodes, got %d", len(nodes))
|
||||
}
|
||||
// Verify structure: root folder + children.
|
||||
var folders, files int
|
||||
for i := range nodes {
|
||||
if nodes[i].Type == "folder" {
|
||||
folders++
|
||||
} else {
|
||||
files++
|
||||
}
|
||||
}
|
||||
if folders < 1 {
|
||||
t.Error("expected at least 1 folder")
|
||||
}
|
||||
if files < 1 {
|
||||
t.Error("expected at least 1 file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteNodeAndChildren(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
svc := NewService(db, vaultRoot, nodeRepo)
|
||||
|
||||
parent, _ := nodeRepo.Create("", "case", "To Delete", "")
|
||||
child, _ := nodeRepo.Create(parent.ID, "file", "child.txt", "")
|
||||
// Add file record to child.
|
||||
src := filepath.Join(t.TempDir(), "child.txt")
|
||||
os.WriteFile(src, []byte("data"), 0o640)
|
||||
svc.CopyIntoVault(child.ID, src, child.Slug)
|
||||
|
||||
if err := svc.DeleteNodeAndChildren(parent.ID); err != nil {
|
||||
t.Fatalf("DeleteNodeAndChildren: %v", err)
|
||||
}
|
||||
// Parent should be soft-deleted.
|
||||
if _, err := nodeRepo.GetActive(parent.ID); err == nil {
|
||||
t.Error("parent should be deleted")
|
||||
}
|
||||
// Child should be soft-deleted.
|
||||
if _, err := nodeRepo.GetActive(child.ID); err == nil {
|
||||
t.Error("child should be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameConflict(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
svc := NewService(db, vaultRoot, nodeRepo)
|
||||
|
||||
parent, _ := nodeRepo.Create("", "case", "Test", "")
|
||||
src := filepath.Join(t.TempDir(), "conflict.pdf")
|
||||
os.WriteFile(src, []byte("data"), 0o640)
|
||||
|
||||
// Import twice with same filename.
|
||||
n1, _ := svc.AddPathCopy(parent.ID, src)
|
||||
n2, _ := svc.AddPathCopy(parent.ID, src)
|
||||
if n1[0].Title == n2[0].Title {
|
||||
t.Error("expected unique name on conflict")
|
||||
}
|
||||
if n2[0].Title == "conflict.pdf" {
|
||||
t.Errorf("title unchanged = %q", n2[0].Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewImportDir(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
vaultRoot := t.TempDir()
|
||||
svc := NewService(db, vaultRoot, nodes.NewRepository(db))
|
||||
|
||||
srcDir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(srcDir, "sub"), 0o750)
|
||||
os.WriteFile(filepath.Join(srcDir, "f1.txt"), []byte("hello"), 0o640)
|
||||
os.WriteFile(filepath.Join(srcDir, "f2.txt"), []byte("world"), 0o640)
|
||||
|
||||
sum, err := svc.PreviewImport(srcDir)
|
||||
if err != nil {
|
||||
t.Fatalf("PreviewImport: %v", err)
|
||||
}
|
||||
if sum.Files != 2 {
|
||||
t.Errorf("files = %d, want 2", sum.Files)
|
||||
}
|
||||
if sum.Folders != 2 { // root + sub
|
||||
t.Errorf("folders = %d, want 2", sum.Folders)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuessMIME(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"a.md": "text/plain",
|
||||
|
||||
@@ -21,7 +21,7 @@ func setupService(t *testing.T) (*Service, *nodes.Repository, string) {
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
nodeRepo := nodes.NewRepository(db)
|
||||
fileSvc := files.NewService(db, dir)
|
||||
fileSvc := files.NewService(db, dir, nodeRepo)
|
||||
svc := NewService(db, dir, nodeRepo, fileSvc)
|
||||
return svc, nodeRepo, dir
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user