Improve disk UI and build performance

This commit is contained in:
2026-04-23 22:51:36 +03:00
parent 31bac2b5d8
commit e7917b41b5
15 changed files with 651 additions and 154 deletions
+7
View File
@@ -0,0 +1,7 @@
.git
.gitignore
.DS_Store
bin
dist
tmp
.tmp
+12 -3
View File
@@ -1,11 +1,20 @@
FROM golang:1.25-alpine AS builder
# syntax=docker/dockerfile:1.7
FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS builder
WORKDIR /src
ARG VERSION=dev
ARG TARGETOS
ARG TARGETARCH
COPY go.mod go.sum ./
RUN go mod download
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" \
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w -X main.Version=${VERSION}" \
-o /out/jukebox ./cmd/jukebox
FROM alpine:3.19
+8 -4
View File
@@ -19,6 +19,8 @@ import (
"jukebox_maker/internal/watcher"
)
var Version = "dev"
func main() {
configPath := flag.String("config", "/config/config.json", "path to config file")
addr := flag.String("addr", ":8080", "HTTP listen address")
@@ -106,6 +108,7 @@ func main() {
srv, err := api.New(api.Deps{
Config: cfg,
ConfigPath: *configPath,
Version: Version,
Watcher: w,
Copier: cp,
Tasks: taskStore,
@@ -147,13 +150,14 @@ func main() {
}
func triggerAutoCopy(cp *copier.Copier, cfg *config.Config, info disk.DiskInfo, mediaPath string) {
var sources []string
hasEnabledSources := false
for _, s := range cfg.Sources {
if s.Enabled {
sources = append(sources, s.Path)
hasEnabledSources = true
break
}
}
if len(sources) == 0 {
if !hasEnabledSources {
return
}
go func() {
@@ -162,7 +166,7 @@ func triggerAutoCopy(cp *copier.Copier, cfg *config.Config, info disk.DiskInfo,
MountPath: info.MountPath,
MediaPath: mediaPath,
DestFolder: cfg.DestFolder,
EnabledSources: sources,
SourceRules: cfg.Sources,
ReserveFreeGB: cfg.ReserveFreeGB,
OverwriteMode: cfg.OverwriteMode,
FileSelectMode: cfg.FileSelectMode,
+39 -7
View File
@@ -2,8 +2,12 @@ package api
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"jukebox_maker/internal/config"
"jukebox_maker/internal/copier"
"jukebox_maker/internal/disk"
)
@@ -12,19 +16,47 @@ func (s *Server) handleCopyStart(w http.ResponseWriter, r *http.Request) {
diskID := r.PathValue("diskID")
diskInfo, ok := s.deps.Watcher.DiskByID(diskID)
if !ok || diskInfo.State != disk.DiskKnown {
jsonErr(w, http.StatusUnprocessableEntity, "no known disk connected")
jsonErr(w, http.StatusUnprocessableEntity, "no initialized disk connected")
return
}
cfg := s.deps.Config
var enabledSources []string
hasEnabledSources := false
for _, src := range cfg.Sources {
if src.Enabled {
enabledSources = append(enabledSources, src.Path)
hasEnabledSources = true
break
}
}
if len(enabledSources) == 0 {
jsonErr(w, http.StatusUnprocessableEntity, "no sources enabled")
if !hasEnabledSources {
jsonErr(w, http.StatusUnprocessableEntity, "no source folders selected")
return
}
var req struct {
Mode string `json:"mode"`
}
if r.Body != nil {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
jsonErr(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
}
overwriteMode := cfg.OverwriteMode
switch req.Mode {
case "", "add":
overwriteMode = config.OverwriteSkip
case "replace":
overwriteMode = config.OverwriteDelete
default:
jsonErr(w, http.StatusBadRequest, "invalid copy mode")
return
}
reserveBytes := int64(cfg.ReserveFreeGB * 1e9)
if diskInfo.FreeBytes <= reserveBytes {
jsonErr(w, http.StatusUnprocessableEntity, "free space is below reserve threshold")
return
}
@@ -33,9 +65,9 @@ func (s *Server) handleCopyStart(w http.ResponseWriter, r *http.Request) {
MountPath: diskInfo.MountPath,
MediaPath: s.deps.MediaPath,
DestFolder: cfg.DestFolder,
EnabledSources: enabledSources,
SourceRules: cfg.Sources,
ReserveFreeGB: cfg.ReserveFreeGB,
OverwriteMode: cfg.OverwriteMode,
OverwriteMode: overwriteMode,
FileSelectMode: cfg.FileSelectMode,
}
+5
View File
@@ -3,6 +3,7 @@ package api
import (
"encoding/json"
"net/http"
"time"
"jukebox_maker/internal/disk"
)
@@ -14,6 +15,7 @@ func (s *Server) handleDiskStatus(w http.ResponseWriter, r *http.Request) {
TotalBytes int64 `json:"total_bytes"`
FreeBytes int64 `json:"free_bytes"`
MountPath string `json:"mount_path"`
LastCopiedAt string `json:"last_copied_at,omitempty"`
ActiveTaskID string `json:"active_task_id,omitempty"`
}
@@ -28,6 +30,9 @@ func (s *Server) handleDiskStatus(w http.ResponseWriter, r *http.Request) {
MountPath: info.MountPath,
}
if info.DiskID != "" {
if lastCopiedAt, ok, err := s.deps.Copier.LastCopiedAt(info.DiskID); err == nil && ok {
item.LastCopiedAt = lastCopiedAt.Format(time.RFC3339)
}
if t, ok := s.deps.Tasks.ActiveTaskByDisk(info.DiskID); ok {
item.ActiveTaskID = t.ID
}
+64 -11
View File
@@ -1,26 +1,79 @@
package api
import (
"errors"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
)
func (s *Server) handleSources(w http.ResponseWriter, r *http.Request) {
entries, err := os.ReadDir(s.deps.MediaPath)
relPath, err := normalizeSourcePath(r.URL.Query().Get("path"))
if err != nil {
jsonOK(w, map[string][]string{"items": {}})
jsonErr(w, http.StatusBadRequest, err.Error())
return
}
var items []string
for _, e := range entries {
if e.IsDir() && e.Name()[0] != '.' {
items = append(items, e.Name())
}
}
if items == nil {
items = []string{}
absPath := s.deps.MediaPath
if relPath != "" {
absPath = filepath.Join(absPath, relPath)
}
jsonOK(w, map[string][]string{"items": items})
entries, err := os.ReadDir(absPath)
if err != nil {
jsonOK(w, map[string]any{"path": relPath, "items": []map[string]string{}})
return
}
type item struct {
Name string `json:"name"`
Path string `json:"path"`
}
var items []item
for _, e := range entries {
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
continue
}
childPath := e.Name()
if relPath != "" {
childPath = filepath.Join(relPath, childPath)
}
items = append(items, item{
Name: e.Name(),
Path: filepath.ToSlash(childPath),
})
}
sort.Slice(items, func(i, j int) bool {
return strings.ToLower(items[i].Name) < strings.ToLower(items[j].Name)
})
jsonOK(w, map[string]any{
"path": relPath,
"items": items,
})
}
func normalizeSourcePath(raw string) (string, error) {
raw, _ = url.QueryUnescape(raw)
raw = strings.TrimSpace(raw)
raw = filepath.ToSlash(raw)
raw = strings.TrimPrefix(raw, "/")
if raw == "" || raw == "." {
return "", nil
}
clean := filepath.Clean(raw)
clean = filepath.ToSlash(clean)
if clean == "." {
return "", nil
}
if clean == ".." || strings.HasPrefix(clean, "../") {
return "", errors.New("invalid source path")
}
return clean, nil
}
+9 -2
View File
@@ -16,6 +16,7 @@ import (
type Deps struct {
Config *config.Config
ConfigPath string
Version string
Watcher *watcher.Watcher
Copier *copier.Copier
Tasks *task.Store
@@ -77,7 +78,7 @@ func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) handleSettings(w http.ResponseWriter, r *http.Request) {
s.render(w, s.settings, map[string]any{"Title": "Настройки", "Page": "settings"})
s.render(w, s.settings, map[string]any{"Title": "Settings", "Page": "settings"})
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
@@ -86,7 +87,13 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
func (s *Server) render(w http.ResponseWriter, tmpl *template.Template, data any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.ExecuteTemplate(w, "layout", data); err != nil {
payload := map[string]any{"Version": s.deps.Version}
if incoming, ok := data.(map[string]any); ok {
for k, v := range incoming {
payload[k] = v
}
}
if err := tmpl.ExecuteTemplate(w, "layout", payload); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
+115 -14
View File
@@ -8,6 +8,8 @@ import (
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
@@ -22,7 +24,7 @@ type Options struct {
MountPath string
MediaPath string
DestFolder string // subfolder on disk, default "media"
EnabledSources []string
SourceRules []config.SourceFolder
ReserveFreeGB float64
OverwriteMode config.OverwriteMode
FileSelectMode config.FileSelectMode
@@ -62,6 +64,14 @@ func (c *Copier) getDB(diskID string) *db.DB {
return c.dbs[diskID]
}
func (c *Copier) LastCopiedAt(diskID string) (time.Time, bool, error) {
database := c.getDB(diskID)
if database == nil {
return time.Time{}, false, nil
}
return database.LastCopiedAt(diskID)
}
func (c *Copier) Start(ctx context.Context, opts Options) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -79,6 +89,15 @@ func (c *Copier) Start(ctx context.Context, opts Options) (string, error) {
opts.DestFolder = "media"
}
_, free, err := disk.DiskUsage(opts.MountPath)
if err != nil {
return "", err
}
reserveBytes := int64(opts.ReserveFreeGB * 1e9)
if free <= reserveBytes {
return "", errors.New("free space is below reserve threshold")
}
t := c.tasks.Create("copy", opts.DiskID)
copyCtx, cancel := context.WithCancel(ctx)
c.cancels[opts.DiskID] = cancel
@@ -116,12 +135,12 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
})
}
setStatus(task.StatusRunning, "Подготовка…", 0)
setStatus(task.StatusRunning, "Preparing...", 0)
destRoot := filepath.Join(opts.MountPath, opts.DestFolder)
if opts.OverwriteMode == config.OverwriteDelete {
setStatus(task.StatusRunning, "Удаление данных с диска…", 0)
setStatus(task.StatusRunning, "Replacing destination media...", 0)
if err := os.RemoveAll(destRoot); err != nil {
fail(err)
return
@@ -130,7 +149,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
var copiedPaths map[string]struct{}
if opts.FileSelectMode == config.SelectNew {
setStatus(task.StatusRunning, "Загрузка истории…", 0)
setStatus(task.StatusRunning, "Loading copy history...", 0)
var err error
copiedPaths, err = database.CopiedPaths(opts.DiskID)
if err != nil {
@@ -139,14 +158,14 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
}
}
setStatus(task.StatusRunning, "Сканирование источников…", 0)
files, err := buildFileList(opts.MediaPath, opts.EnabledSources, copiedPaths)
setStatus(task.StatusRunning, "Scanning sources...", 0)
files, err := buildFileList(opts.MediaPath, opts.SourceRules, copiedPaths)
if err != nil {
fail(err)
return
}
if len(files) == 0 {
setStatus(task.StatusSuccess, "Нет новых файлов для копирования.", 100)
setStatus(task.StatusSuccess, "No files to copy.", 100)
return
}
@@ -161,7 +180,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
reserveBytes := int64(opts.ReserveFreeGB * 1e9)
available := free - reserveBytes
if available <= 0 {
setStatus(task.StatusSuccess, "Недостаточно свободного места на диске.", 100)
setStatus(task.StatusFailed, "Free space is below the reserved threshold.", 100)
return
}
@@ -181,7 +200,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
case <-ctx.Done():
c.tasks.Update(taskID, func(t *task.Task) {
t.Status = task.StatusCanceled
t.Message = "Отменено"
t.Message = "Canceled"
t.SpeedBPS = 0
t.ETASec = 0
})
@@ -204,7 +223,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
}
prog := int(float64(doneBytes) / float64(totalBytes) * 100)
msg := fmt.Sprintf("Копирование %s (%d/%d)", filepath.Base(f.srcAbs), i+1, total)
msg := fmt.Sprintf("Copying %s (%d/%d)", filepath.Base(f.srcAbs), i+1, total)
c.tasks.Update(taskID, func(t *task.Task) {
t.Status = task.StatusRunning
@@ -219,7 +238,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
if errors.Is(err, context.Canceled) {
c.tasks.Update(taskID, func(t *task.Task) {
t.Status = task.StatusCanceled
t.Message = "Отменено"
t.Message = "Canceled"
t.SpeedBPS = 0
t.ETASec = 0
})
@@ -238,7 +257,7 @@ func (c *Copier) run(ctx context.Context, taskID string, opts Options, database
})
}
setStatus(task.StatusSuccess, fmt.Sprintf("Готово. Скопировано файлов: %d.", copied), 100)
setStatus(task.StatusSuccess, fmt.Sprintf("Done. Copied %d files.", copied), 100)
}
type fileEntry struct {
@@ -247,15 +266,35 @@ type fileEntry struct {
size int64
}
func buildFileList(mediaPath string, sources []string, skip map[string]struct{}) ([]fileEntry, error) {
func buildFileList(mediaPath string, rules []config.SourceFolder, skip map[string]struct{}) ([]fileEntry, error) {
roots, ruleMap := normalizeSourceRules(rules)
var result []fileEntry
for _, src := range sources {
for _, src := range roots {
dir := filepath.Join(mediaPath, src)
err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
if err != nil {
return nil
}
if path == dir {
return nil
}
rel, relErr := filepath.Rel(mediaPath, path)
if relErr != nil {
return nil
}
rel = filepath.ToSlash(rel)
if !isPathEnabled(rel, ruleMap) && !hasEnabledDescendant(rel, ruleMap) {
return filepath.SkipDir
}
return nil
}
rel, _ := filepath.Rel(mediaPath, path)
rel = filepath.ToSlash(rel)
if !isPathEnabled(rel, ruleMap) {
return nil
}
if _, skipped := skip[rel]; skipped {
return nil
}
@@ -273,6 +312,68 @@ func buildFileList(mediaPath string, sources []string, skip map[string]struct{})
return result, nil
}
func normalizeSourceRules(rules []config.SourceFolder) ([]string, map[string]bool) {
ruleMap := make(map[string]bool, len(rules))
for _, rule := range rules {
src := filepath.ToSlash(filepath.Clean(strings.TrimSpace(rule.Path)))
src = strings.TrimPrefix(src, "./")
src = strings.TrimPrefix(src, "/")
if src == "" || src == "." {
continue
}
if src == ".." || strings.HasPrefix(src, "../") {
continue
}
ruleMap[src] = rule.Enabled
}
var roots []string
for src, enabled := range ruleMap {
if !enabled || hasEnabledAncestor(src, ruleMap) {
continue
}
roots = append(roots, src)
}
sort.Strings(roots)
return roots, ruleMap
}
func hasEnabledAncestor(path string, ruleMap map[string]bool) bool {
for parent := parentSourcePath(path); parent != ""; parent = parentSourcePath(parent) {
if ruleMap[parent] {
return true
}
}
return false
}
func hasEnabledDescendant(path string, ruleMap map[string]bool) bool {
prefix := path + "/"
for other, enabled := range ruleMap {
if enabled && strings.HasPrefix(other, prefix) {
return true
}
}
return false
}
func isPathEnabled(path string, ruleMap map[string]bool) bool {
for current := path; current != ""; current = parentSourcePath(current) {
if enabled, ok := ruleMap[current]; ok {
return enabled
}
}
return false
}
func parentSourcePath(path string) string {
idx := strings.LastIndex(path, "/")
if idx < 0 {
return ""
}
return path[:idx]
}
// rsyncFile copies src to dst using rsync with resume support.
// --partial keeps partial files on interruption.
// --append-verify resumes partial transfers and verifies checksums.
+42 -3
View File
@@ -47,6 +47,10 @@ func (d *DB) migrate() error {
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_copy_history_disk_path
ON copy_history (disk_id, source_path);
CREATE TABLE IF NOT EXISTS disk_stats (
disk_id TEXT PRIMARY KEY,
last_copied_at DATETIME NOT NULL
);
`)
return err
}
@@ -65,11 +69,26 @@ func (d *DB) RecordCopy(rec CopyRecord) error {
if t.IsZero() {
t = time.Now().UTC()
}
_, err := d.sql.Exec(
tx, err := d.sql.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(
`INSERT OR IGNORE INTO copy_history (disk_id, source_path, file_size, copied_at) VALUES (?,?,?,?)`,
rec.DiskID, rec.SourcePath, rec.FileSize, t.Format(time.RFC3339),
)
return err
); err != nil {
return err
}
if _, err := tx.Exec(
`INSERT INTO disk_stats (disk_id, last_copied_at) VALUES (?, ?)
ON CONFLICT(disk_id) DO UPDATE SET last_copied_at=excluded.last_copied_at`,
rec.DiskID, t.Format(time.RFC3339),
); err != nil {
return err
}
return tx.Commit()
}
func (d *DB) CopiedPaths(diskID string) (map[string]struct{}, error) {
@@ -90,3 +109,23 @@ func (d *DB) CopiedPaths(diskID string) (map[string]struct{}, error) {
}
return m, rows.Err()
}
func (d *DB) LastCopiedAt(diskID string) (time.Time, bool, error) {
var raw string
err := d.sql.QueryRow(
`SELECT last_copied_at FROM disk_stats WHERE disk_id=?`,
diskID,
).Scan(&raw)
if err == sql.ErrNoRows {
return time.Time{}, false, nil
}
if err != nil {
return time.Time{}, false, err
}
t, err := time.Parse(time.RFC3339, raw)
if err != nil {
return time.Time{}, false, err
}
return t, true, nil
}
+7 -11
View File
@@ -2,6 +2,7 @@ package watcher
import (
"context"
"os"
"path/filepath"
"sort"
"sync"
@@ -121,22 +122,17 @@ func (w *Watcher) probe() {
}
func discoverDisks(root string) map[string]disk.DiskInfo {
candidates := []string{root}
if entries, err := filepath.Glob(filepath.Join(root, "*")); err == nil {
for _, path := range entries {
candidates = append(candidates, path)
}
entries, err := os.ReadDir(root)
if err != nil {
return map[string]disk.DiskInfo{}
}
disks := make(map[string]disk.DiskInfo)
seen := make(map[string]struct{}, len(candidates))
for _, mountPath := range candidates {
if _, ok := seen[mountPath]; ok {
for _, entry := range entries {
if !entry.IsDir() {
continue
}
seen[mountPath] = struct{}{}
mountPath := filepath.Join(root, entry.Name())
info, _ := disk.Probe(mountPath)
if info.State == disk.DiskAbsent {
continue
+3
View File
@@ -24,6 +24,7 @@ command -v docker >/dev/null 2>&1 || die "docker not found in PATH"
command -v go >/dev/null 2>&1 || die "go not found in PATH"
DEFAULT_TAG=$(git -C "${ROOT_DIR}" rev-parse --short HEAD 2>/dev/null || echo dev)
DEFAULT_VERSION=$(git -C "${ROOT_DIR}" describe --tags --always 2>/dev/null || echo dev)
ask() {
# $1=varname $2=prompt $3=default
@@ -73,6 +74,7 @@ if [ -n "${IMAGE}" ]; then
docker buildx build \
--platform "${PLATFORMS}" \
--file "${ROOT_DIR}/Dockerfile" \
--build-arg "VERSION=${DEFAULT_VERSION}" \
-t "${IMAGE}:${IMAGE_TAG}" \
-t "${IMAGE}:latest" \
--push \
@@ -87,6 +89,7 @@ else
echo "building locally (no push)"
docker build \
--file "${ROOT_DIR}/Dockerfile" \
--build-arg "VERSION=${DEFAULT_VERSION}" \
-t "jukebox-maker:${IMAGE_TAG}" \
-t "jukebox-maker:latest" \
"${ROOT_DIR}"
+72
View File
@@ -69,6 +69,14 @@ a:hover { text-decoration: underline; }
margin: 28px auto 56px;
}
.page-footer {
width: min(var(--content-width), calc(100vw - 48px));
margin: -28px auto 24px;
color: var(--muted);
font-size: 12px;
text-align: right;
}
/* Panel */
.panel {
margin-bottom: 24px;
@@ -259,6 +267,69 @@ a:hover { text-decoration: underline; }
/* Checkbox list */
.source-list { display: flex; flex-direction: column; gap: 0; }
.source-tree {
padding: 8px 0;
}
.source-tree-empty {
padding: 12px 16px;
}
.source-node {
border-bottom: 1px solid var(--border-lite);
}
.source-node:last-child {
border-bottom: 0;
}
.source-row {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
}
.source-row:hover {
background: rgba(33, 133, 208, 0.04);
}
.source-toggle {
width: 24px;
height: 24px;
border: 1px solid transparent;
border-radius: var(--radius);
background: transparent;
color: var(--muted);
cursor: pointer;
flex: 0 0 24px;
}
.source-toggle:hover {
border-color: var(--border);
background: var(--surface-2);
}
.source-toggle-empty {
visibility: hidden;
}
.source-check {
width: 15px;
height: 15px;
accent-color: var(--accent);
cursor: pointer;
}
.source-label {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
flex: 1;
}
.source-item-hint {
font-size: 12px;
color: var(--muted);
}
.source-children {
padding-left: 20px;
}
.source-loading {
padding: 6px 16px 10px 48px;
color: var(--muted);
font-size: 12px;
}
.source-item {
display: flex;
align-items: center;
@@ -343,6 +414,7 @@ a:hover { text-decoration: underline; }
@media (max-width: 720px) {
.page-header { flex-wrap: wrap; padding: 12px 16px; }
.page-main { width: calc(100vw - 24px); margin-top: 20px; }
.page-footer { width: calc(100vw - 24px); margin-top: -8px; }
.disk-grid { grid-template-columns: 1fr; }
.kv-table th { width: 130px; }
.btn-row { flex-wrap: wrap; }
+59 -36
View File
@@ -1,9 +1,9 @@
{{define "content"}}
<section class="panel">
<h2>Накопители</h2>
<h2>Disks</h2>
<div class="panel-body">
<div id="diskSummary" class="text-muted">Загрузка списка накопителей…</div>
<div id="diskSummary" class="text-muted">Loading disks...</div>
</div>
</section>
@@ -33,22 +33,35 @@ function badgeClass(state) {
}
function badgeLabel(state) {
return ({ absent: 'Не подключён', foreign: 'Незнакомый диск', known: 'Диск подключён' })[state] || '—';
return ({ absent: 'Not connected', foreign: 'Uninitialized disk', known: 'Ready' })[state] || '—';
}
function fmtSpeed(bps) {
if (!bps) return '';
if (bps >= 1e9) return (bps / 1e9).toFixed(1) + ' ГБ/с';
if (bps >= 1e6) return (bps / 1e6).toFixed(1) + ' МБ/с';
if (bps >= 1e3) return (bps / 1e3).toFixed(0) + ' КБ/с';
return bps + ' Б/с';
if (bps >= 1e9) return (bps / 1e9).toFixed(1) + ' GB/s';
if (bps >= 1e6) return (bps / 1e6).toFixed(1) + ' MB/s';
if (bps >= 1e3) return (bps / 1e3).toFixed(0) + ' KB/s';
return bps + ' B/s';
}
function fmtETA(sec) {
if (!sec || sec <= 0) return '';
if (sec >= 3600) return Math.floor(sec / 3600) + ' ч ' + Math.floor((sec % 3600) / 60) + ' мин';
if (sec >= 60) return Math.floor(sec / 60) + ' мин';
return sec + ' с';
if (sec >= 3600) return Math.floor(sec / 3600) + ' h ' + Math.floor((sec % 3600) / 60) + ' min';
if (sec >= 60) return Math.floor(sec / 60) + ' min';
return sec + ' s';
}
function fmtDateTime(value) {
if (!value) return 'Never';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
function taskMeta(task) {
@@ -61,21 +74,22 @@ function renderDisks() {
const summary = document.getElementById('diskSummary');
if (!disks.length) {
summary.textContent = 'Подключённые накопители не найдены.';
summary.textContent = 'No disks found.';
grid.innerHTML = '';
return;
}
const knownCount = disks.filter((disk) => disk.state === 'known').length;
summary.textContent = `Найдено накопителей: ${disks.length}. Готово к копированию: ${knownCount}.`;
summary.textContent = `Disks found: ${disks.length}. Ready to copy: ${knownCount}.`;
grid.innerHTML = disks.map((disk) => {
const activeTask = disk.active_task_id ? taskState.get(disk.active_task_id) : null;
const progress = activeTask ? activeTask.progress : 0;
const message = activeTask ? (activeTask.message || 'Подготовка…') : '';
const message = activeTask ? (activeTask.message || 'Preparing...') : '';
const meta = activeTask ? taskMeta(activeTask) : '';
const isKnown = disk.state === 'known';
const isForeign = disk.state === 'foreign';
const hasCapacity = disk.state !== 'absent';
return `
<section class="panel disk-card">
@@ -83,20 +97,24 @@ function renderDisks() {
<table class="kv-table">
<tbody>
<tr>
<th>Статус</th>
<th>Status</th>
<td><span class="badge ${badgeClass(disk.state)}">${badgeLabel(disk.state)}</span></td>
</tr>
<tr>
<th>ID диска</th>
<td>${disk.disk_id ? `<span class="mono">${escapeHTML(disk.disk_id)}</span>` : '<span class="text-muted">ещё не инициализирован</span>'}</td>
<th>Disk ID</th>
<td>${disk.disk_id ? `<span class="mono">${escapeHTML(disk.disk_id)}</span>` : '<span class="text-muted">not initialized yet</span>'}</td>
</tr>
<tr>
<th>Всего на диске</th>
<td>${isKnown ? fmtBytes(disk.total_bytes) : '—'}</td>
<th>Total capacity</th>
<td>${hasCapacity ? fmtBytes(disk.total_bytes) : '—'}</td>
</tr>
<tr>
<th>Свободно</th>
<td>${isKnown ? fmtBytes(disk.free_bytes) : '—'}</td>
<th>Free space</th>
<td>${hasCapacity ? fmtBytes(disk.free_bytes) : '—'}</td>
</tr>
<tr>
<th>Last copied</th>
<td>${fmtDateTime(disk.last_copied_at)}</td>
</tr>
</tbody>
</table>
@@ -111,11 +129,12 @@ function renderDisks() {
` : ''}
<div class="btn-row">
${isKnown ? `
<button class="button-primary" data-action="start-copy" data-disk-id="${escapeHTML(disk.disk_id)}" ${activeTask ? 'disabled' : ''}>▶ Копировать</button>
<button class="button-danger ${activeTask ? '' : 'hidden'}" data-action="cancel-copy" data-disk-id="${escapeHTML(disk.disk_id)}">✕ Отменить</button>
<button class="button-danger" data-action="start-copy" data-mode="replace" data-disk-id="${escapeHTML(disk.disk_id)}" ${activeTask ? 'disabled' : ''}>Replace media</button>
<button class="button-primary" data-action="start-copy" data-mode="add" data-disk-id="${escapeHTML(disk.disk_id)}" ${activeTask ? 'disabled' : ''}>Add media</button>
<button class="button-danger ${activeTask ? '' : 'hidden'}" data-action="cancel-copy" data-disk-id="${escapeHTML(disk.disk_id)}">Cancel</button>
` : ''}
${isForeign ? `
<button class="button-secondary" data-action="init-disk" data-mount-path="${escapeHTML(disk.mount_path)}">Инициализировать диск</button>
<button class="button-secondary" data-action="init-disk" data-mount-path="${escapeHTML(disk.mount_path)}">Initialize disk</button>
` : ''}
</div>
</section>
@@ -170,35 +189,39 @@ async function pollTask(taskID) {
if (['success', 'failed', 'canceled'].includes(task.status)) {
stopTaskPoll(taskID);
taskState.delete(taskID);
if (task.status === 'success') toast(task.message || 'Готово', 'ok');
if (task.status === 'failed') toast('Ошибка: ' + task.error, 'error');
if (task.status === 'canceled') toast('Копирование отменено', 'error');
if (task.status === 'success') toast(task.message || 'Done', 'ok');
if (task.status === 'failed') toast('Error: ' + task.error, 'error');
if (task.status === 'canceled') toast('Copy canceled', 'error');
refreshDisks();
}
} catch (error) {}
}
async function startCopy(diskID) {
async function startCopy(diskID, mode) {
try {
const response = await fetch('/api/disks/' + encodeURIComponent(diskID) + '/copy/start', { method: 'POST' });
const response = await fetch('/api/disks/' + encodeURIComponent(diskID) + '/copy/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode })
});
const payload = await response.json();
if (!response.ok) {
toast(payload.error || 'Ошибка запуска', 'error');
toast(payload.error || 'Failed to start copy', 'error');
return;
}
startTaskPoll(payload.task_id);
refreshDisks();
} catch (error) {
toast('Ошибка связи', 'error');
toast('Network error', 'error');
}
}
async function cancelCopy(diskID) {
try {
await fetch('/api/disks/' + encodeURIComponent(diskID) + '/copy/cancel', { method: 'POST' });
toast('Отмена…', 'ok');
toast('Canceling...', 'ok');
} catch (error) {
toast('Ошибка связи', 'error');
toast('Network error', 'error');
}
}
@@ -211,13 +234,13 @@ async function initDisk(mountPath) {
});
const payload = await response.json();
if (!response.ok) {
toast(payload.error || 'Ошибка инициализации', 'error');
toast(payload.error || 'Failed to initialize disk', 'error');
return;
}
toast('Диск инициализирован', 'ok');
toast('Disk initialized', 'ok');
refreshDisks();
} catch (error) {
toast('Ошибка связи', 'error');
toast('Network error', 'error');
}
}
@@ -226,7 +249,7 @@ document.getElementById('diskGrid').addEventListener('click', (event) => {
if (!button) return;
const action = button.dataset.action;
if (action === 'start-copy') startCopy(button.dataset.diskId);
if (action === 'start-copy') startCopy(button.dataset.diskId, button.dataset.mode || 'add');
if (action === 'cancel-copy') cancelCopy(button.dataset.diskId);
if (action === 'init-disk') initDisk(button.dataset.mountPath);
});
+10 -6
View File
@@ -1,5 +1,5 @@
{{define "layout"}}<!DOCTYPE html>
<html lang="ru">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -12,7 +12,7 @@
<h1>🎵 Jukebox Maker</h1>
<nav class="header-nav">
<a href="/" class="header-action {{if eq .Page "dashboard"}}active{{end}}">Dashboard</a>
<a href="/settings" class="header-action {{if eq .Page "settings"}}active{{end}}">Настройки</a>
<a href="/settings" class="header-action {{if eq .Page "settings"}}active{{end}}">Settings</a>
</nav>
</header>
@@ -20,6 +20,10 @@
{{template "content" .}}
</main>
<footer class="page-footer">
<span>Version {{.Version}}</span>
</footer>
<div class="toast-container" id="toastContainer"></div>
<script>
@@ -33,10 +37,10 @@ function toast(msg, type) {
}
function fmtBytes(b) {
if (!b) return '—';
if (b >= 1e12) return (b/1e12).toFixed(1) + ' ТБ';
if (b >= 1e9) return (b/1e9).toFixed(1) + ' ГБ';
if (b >= 1e6) return (b/1e6).toFixed(1) + ' МБ';
return (b/1e3).toFixed(0) + ' КБ';
if (b >= 1e12) return (b/1e12).toFixed(1) + ' TB';
if (b >= 1e9) return (b/1e9).toFixed(1) + ' GB';
if (b >= 1e6) return (b/1e6).toFixed(1) + ' MB';
return (b/1e3).toFixed(0) + ' KB';
}
</script>
</body>
+199 -57
View File
@@ -2,100 +2,216 @@
<form id="settingsForm" onsubmit="saveSettings(event)">
<section class="panel">
<h2>Источники копирования</h2>
<div class="source-list" id="sourceList">
<div class="text-muted" style="padding:12px 16px">Загрузка…</div>
<h2>Copy Sources</h2>
<div class="panel-body">
<div class="form-hint">Select top-level folders or expand branches and choose individual nested directories.</div>
</div>
<div class="source-list">
<div class="source-tree" id="sourceTree">
<div class="text-muted source-tree-empty">Loading...</div>
</div>
</div>
<div class="btn-row">
<button type="button" class="button-secondary button-sm" onclick="loadSources()">↻ Обновить список</button>
<button type="button" class="button-secondary button-sm" onclick="reloadSourceTree()">Refresh list</button>
</div>
</section>
<section class="panel">
<h2>Параметры копирования</h2>
<h2>Copy Settings</h2>
<div class="form-body">
<div class="form-group">
<label class="form-label" for="reserveGB">Оставить свободным на диске (ГБ)</label>
<label class="form-label" for="reserveGB">Reserved free space on disk (GB)</label>
<input class="form-input" type="number" id="reserveGB" min="0" max="1000" step="0.5" value="2">
<span class="form-hint">Копирование остановится, когда свободного места останется меньше этого значения.</span>
<span class="form-hint">Copying will stop when free space falls below this value.</span>
</div>
<div class="form-group">
<label class="form-label" for="fileSelectMode">Какие файлы копировать</label>
<label class="form-label" for="fileSelectMode">Files to copy</label>
<select class="form-select" id="fileSelectMode" style="width:auto;max-width:420px">
<option value="new">Только новые (не копировавшиеся на этот диск)</option>
<option value="all">Все подряд</option>
<option value="new">Only new files not copied to this disk before</option>
<option value="all">All matching files</option>
</select>
<span class="form-hint">«Только новые» — пропускает файлы, уже скопированные на данный диск, даже если они были удалены с него (считаются просмотренными).</span>
<span class="form-hint">The new-only mode skips files already copied to this disk, even if they were later removed.</span>
</div>
<div class="form-group">
<label class="form-label" for="destFolder">Папка назначения на диске</label>
<label class="form-label" for="destFolder">Destination folder on disk</label>
<input class="form-input" type="text" id="destFolder" placeholder="media" style="width:200px">
<span class="form-hint">Подпапка на диске куда копировать файлы. Структура источника воспроизводится внутри неё. По умолчанию: <code>media</code>.</span>
<span class="form-hint">Files will be copied into this subfolder while preserving the selected source structure.</span>
</div>
<div class="form-group">
<label class="form-label" for="overwriteMode">Режим записи</label>
<label class="form-label" for="overwriteMode">Default write mode</label>
<select class="form-select" id="overwriteMode" style="width:auto;max-width:420px">
<option value="skip">Пропустить существующие файлы</option>
<option value="delete">Удалить папку назначения и перезаписать заново</option>
<option value="skip">Keep existing files</option>
<option value="delete">Replace destination folder contents</option>
</select>
<span class="form-hint">«Удалить и перезаписать» — удаляет папку назначения на диске, затем копирует заново.</span>
<span class="form-hint">This is used for automatic copy runs. Manual dashboard actions can override it.</span>
</div>
</div>
</section>
<section class="panel">
<h2>Автоматизация</h2>
<h2>Automation</h2>
<div class="form-body">
<div class="form-group">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="autoCopy" style="width:15px;height:15px;accent-color:var(--accent)">
<span class="form-label" style="margin:0">Автоматическое копирование</span>
<span class="form-label" style="margin:0">Automatic copy</span>
</label>
<span class="form-hint">При обнаружении знакомого накопителя копирование запустится автоматически.</span>
<span class="form-hint">Start copying automatically when a known disk is detected.</span>
</div>
</div>
</section>
<div style="display:flex;gap:8px;margin-bottom:24px">
<button type="submit" class="button-primary">Сохранить настройки</button>
<button type="button" class="button-secondary" onclick="loadSettings()">Сбросить</button>
<button type="submit" class="button-primary">Save settings</button>
<button type="button" class="button-secondary" onclick="loadSettings()">Reset</button>
</div>
</form>
<script>
let allSources = [];
let enabledSources = {};
const sourceTree = new Map();
const expandedNodes = new Set();
const loadingNodes = new Set();
let sourceConfig = {};
function escapeHTML(value) {
return String(value || '').replace(/[&<>"']/g, (char) => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[char]));
}
function pathDepth(path) {
return path ? path.split('/').length : 0;
}
function parentPath(path) {
if (!path || !path.includes('/')) return '';
return path.slice(0, path.lastIndexOf('/'));
}
function effectiveSourceState(path) {
let current = path;
while (true) {
if (Object.prototype.hasOwnProperty.call(sourceConfig, current)) {
return sourceConfig[current];
}
if (!current) return true;
current = parentPath(current);
}
}
function collectSourcesForSave() {
const items = [];
const seen = new Set();
const roots = sourceTree.get('') || [];
for (const item of roots) {
items.push({ path: item.path, enabled: effectiveSourceState(item.path) });
seen.add(item.path);
}
Object.entries(sourceConfig).forEach(([path, enabled]) => {
if (seen.has(path)) return;
items.push({ path, enabled });
});
return items.sort((a, b) => a.path.localeCompare(b.path));
}
async function loadSourceChildren(path = '') {
if (loadingNodes.has(path)) return;
loadingNodes.add(path);
renderSources();
async function loadSources() {
try {
const r = await fetch('/api/sources');
if (!r.ok) return;
const d = await r.json();
allSources = d.items || [];
const query = path ? '?path=' + encodeURIComponent(path) : '';
const response = await fetch('/api/sources' + query);
if (!response.ok) return;
const payload = await response.json();
sourceTree.set(path, payload.items || []);
} catch (error) {
} finally {
loadingNodes.delete(path);
renderSources();
} catch(e) {}
}
}
async function ensureExpanded(path) {
expandedNodes.add(path);
if (!sourceTree.has(path)) {
await loadSourceChildren(path);
return;
}
renderSources();
}
function toggleSource(path, checked) {
sourceConfig[path] = checked;
renderSources();
}
function renderSourceNodes(parent = '') {
const items = sourceTree.get(parent) || [];
return items.map((item) => {
const checked = effectiveSourceState(item.path);
const expanded = expandedNodes.has(item.path);
const childrenKnown = sourceTree.has(item.path);
const children = childrenKnown ? sourceTree.get(item.path) : [];
const hasChildren = !childrenKnown || children.length > 0;
const pad = 16 + pathDepth(item.path) * 20;
return `
<div class="source-node">
<div class="source-row" style="padding-left:${pad}px">
<button
type="button"
class="source-toggle ${hasChildren ? '' : 'source-toggle-empty'}"
data-action="toggle-expand"
data-path="${escapeHTML(item.path)}"
${hasChildren ? '' : 'tabindex="-1" aria-hidden="true"'}
>${expanded ? '▾' : '▸'}</button>
<input class="source-check" type="checkbox" data-action="toggle-check" data-path="${escapeHTML(item.path)}" ${checked ? 'checked' : ''}>
<div class="source-label">
<span class="source-item-name">${escapeHTML(item.name)}</span>
<span class="source-item-path">/media/${escapeHTML(item.path)}</span>
</div>
</div>
${expanded && loadingNodes.has(item.path) ? '<div class="source-loading">Loading...</div>' : ''}
${expanded && childrenKnown && children.length ? `<div class="source-children">${renderSourceNodes(item.path)}</div>` : ''}
</div>
`;
}).join('');
}
function renderSources() {
const el = document.getElementById('sourceList');
if (!allSources.length) {
el.innerHTML = '<div class="text-muted" style="padding:12px 16px">Папки в /media не найдены.</div>';
const el = document.getElementById('sourceTree');
const roots = sourceTree.get('');
if (loadingNodes.has('') && !roots) {
el.innerHTML = '<div class="text-muted source-tree-empty">Loading...</div>';
return;
}
el.innerHTML = allSources.map(path => {
const checked = enabledSources[path] !== false;
return `<label class="source-item">
<input type="checkbox" data-source="${path}" ${checked ? 'checked' : ''}>
<span class="source-item-name">${path}</span>
<span class="source-item-path">/media/${path}</span>
</label>`;
}).join('');
if (!roots || !roots.length) {
el.innerHTML = '<div class="text-muted source-tree-empty">No folders found in /media.</div>';
return;
}
el.innerHTML = renderSourceNodes('');
}
async function reloadSourceTree() {
sourceTree.clear();
expandedNodes.clear();
await loadSourceChildren('');
}
async function loadSettings() {
@@ -108,39 +224,65 @@ async function loadSettings() {
document.getElementById('fileSelectMode').value = cfg.file_select_mode || 'new';
document.getElementById('overwriteMode').value = cfg.overwrite_mode || 'skip';
document.getElementById('autoCopy').checked = !!cfg.auto_copy;
enabledSources = {};
(cfg.sources || []).forEach(s => { enabledSources[s.path] = s.enabled; });
sourceConfig = {};
(cfg.sources || []).forEach((source) => {
sourceConfig[source.path] = !!source.enabled;
});
renderSources();
} catch(e) {}
} catch (error) {}
}
async function saveSettings(e) {
e.preventDefault();
const checkboxes = document.querySelectorAll('[data-source]');
const sources = Array.from(checkboxes).map(cb => ({ path: cb.dataset.source, enabled: cb.checked }));
Object.keys(enabledSources).forEach(path => {
if (!sources.find(s => s.path === path)) sources.push({ path, enabled: false });
});
async function saveSettings(event) {
event.preventDefault();
const body = {
reserve_free_gb: parseFloat(document.getElementById('reserveGB').value) || 2,
dest_folder: document.getElementById('destFolder').value.trim() || 'media',
file_select_mode: document.getElementById('fileSelectMode').value,
overwrite_mode: document.getElementById('overwriteMode').value,
auto_copy: document.getElementById('autoCopy').checked,
sources,
sources: collectSourcesForSave(),
};
try {
const r = await fetch('/api/config', {
const response = await fetch('/api/config', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (r.ok) { toast('Настройки сохранены', 'ok'); await loadSettings(); }
else { const d = await r.json(); toast(d.error || 'Ошибка сохранения', 'error'); }
} catch(e) { toast('Ошибка связи', 'error'); }
if (response.ok) {
toast('Settings saved', 'ok');
await loadSettings();
return;
}
const payload = await response.json();
toast(payload.error || 'Failed to save settings', 'error');
} catch (error) {
toast('Network error', 'error');
}
}
document.getElementById('sourceTree').addEventListener('click', async (event) => {
const button = event.target.closest('[data-action="toggle-expand"]');
if (!button) return;
const path = button.dataset.path;
if (expandedNodes.has(path)) {
expandedNodes.delete(path);
renderSources();
return;
}
await ensureExpanded(path);
});
document.getElementById('sourceTree').addEventListener('change', (event) => {
const checkbox = event.target.closest('[data-action="toggle-check"]');
if (!checkbox) return;
toggleSource(checkbox.dataset.path, checkbox.checked);
});
loadSettings();
loadSources();
loadSourceChildren('');
</script>
{{end}}