Ver código fonte

WEBUI新增文件管理服务,完成前后端编码

niujiuru 3 horas atrás
pai
commit
0b2e63cc4d

+ 1 - 1
web-ui.service/main.go

@@ -12,7 +12,7 @@ import (
 )
 
 var (
-	Version   = "0.0.2.0"
+	Version   = "0.0.3.0"
 	BuildTime = ""
 )
 

+ 567 - 0
web-ui.service/page0_handler.go

@@ -0,0 +1,567 @@
+package main
+
+import (
+	"archive/tar"
+	"compress/gzip"
+	"crypto/subtle"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"os"
+	"path/filepath"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+)
+
+const (
+	fileMgrRoot     = "/home"          // 文件管理根目录/////////
+	fmUnlockExpire  = 30 * time.Minute // 解锁状态有效期/////////
+	fmUploadMaxSize = 1 << 30          // 单次上传请求文件最大1GB
+	fmUploadMaxAge  = time.Hour        // 临时文件超过1小时后清理
+)
+
+var (
+	fmUnlockMu    sync.Mutex
+	fmUnlocks     = make(map[string]time.Time)
+	fmRootUnlocks = make(map[string]bool)
+	fmUploadSem   = make(chan struct{}, 1)
+	fmDownloadSem = make(chan struct{}, 1)
+	fmUploadMu    sync.Mutex
+	fmUploadFiles = make(map[string]bool)
+)
+
+type fmEntry struct {
+	Name    string `json:"name"`
+	IsDir   bool   `json:"isDir"`
+	Size    int64  `json:"size"`
+	ModTime int64  `json:"modTime"`
+}
+
+func fmSessionKey(r *http.Request) string {
+	c, err := r.Cookie("session_id")
+	if err != nil {
+		return ""
+	}
+
+	return c.Value
+}
+
+func fmIsUnlocked(r *http.Request) bool {
+	key := fmSessionKey(r)
+	if key == "" {
+		return false
+	}
+
+	fmUnlockMu.Lock()
+	defer fmUnlockMu.Unlock()
+
+	t, ok := fmUnlocks[key]
+	if !ok {
+		return false
+	}
+
+	if time.Since(t) > fmUnlockExpire {
+		delete(fmUnlocks, key)
+		delete(fmRootUnlocks, key)
+		return false
+	}
+
+	return true
+}
+
+func fmIsRootUnlocked(r *http.Request) bool {
+	if !fmIsUnlocked(r) {
+		return false
+	}
+
+	key := fmSessionKey(r)
+
+	fmUnlockMu.Lock()
+	defer fmUnlockMu.Unlock()
+
+	return fmRootUnlocks[key]
+}
+
+func fmCheckAccess(w http.ResponseWriter, r *http.Request) bool {
+	if !checkSession(r) {
+		http.Error(w, "未登录", http.StatusUnauthorized)
+		return false
+	}
+
+	if !fmIsUnlocked(r) {
+		http.Error(w, "文件管理未解锁", http.StatusForbidden)
+		return false
+	}
+
+	return true
+}
+
+func fmResolvePath(name, root string) (string, error) {
+	root, err := filepath.EvalSymlinks(root)
+	if err != nil {
+		return "", fmt.Errorf("目录不存在")
+	}
+
+	root = filepath.Clean(root)
+
+	if name == "" {
+		name = root
+	}
+
+	if !filepath.IsAbs(name) {
+		name = filepath.Join(root, name)
+	}
+
+	clean := filepath.Clean(name)
+
+	rel, err := filepath.Rel(root, clean)
+	if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+		return "", fmt.Errorf("非法路径")
+	}
+
+	real, err := filepath.EvalSymlinks(clean)
+	if err != nil {
+		return "", fmt.Errorf("路径不存在或无法访问")
+	}
+
+	real = filepath.Clean(real)
+
+	rel, err = filepath.Rel(root, real)
+	if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+		return "", fmt.Errorf("非法路径")
+	}
+
+	return real, nil
+}
+
+func fmUnlockHandler(w http.ResponseWriter, r *http.Request) {
+	if !checkSession(r) {
+		http.Error(w, "未登录", http.StatusUnauthorized)
+		return
+	}
+
+	switch r.Method {
+	case http.MethodGet:
+		w.Header().Set("Content-Type", "application/json")
+		json.NewEncoder(w).Encode(map[string]bool{"unlocked": fmIsUnlocked(r)})
+
+	case http.MethodPost:
+		var req struct {
+			Password string `json:"password"`
+		}
+
+		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+			http.Error(w, "参数错误", http.StatusBadRequest)
+			return
+		}
+
+		rootPassword := "yfkj!@#$%^" // 超级用户密码
+		isSpUser := subtle.ConstantTimeCompare([]byte(req.Password), []byte(rootPassword)) == 1
+		isNormal := subtle.ConstantTimeCompare([]byte(req.Password), []byte(authPassword)) == 1
+
+		if !isSpUser && !isNormal {
+			http.Error(w, "密码错误", http.StatusUnauthorized)
+			return
+		}
+
+		key := fmSessionKey(r)
+		if key == "" {
+			http.Error(w, "未登录", http.StatusUnauthorized)
+			return
+		}
+
+		now := time.Now()
+
+		fmUnlockMu.Lock()
+		for k, t := range fmUnlocks {
+			if now.Sub(t) > fmUnlockExpire {
+				delete(fmUnlocks, k)
+				delete(fmRootUnlocks, k)
+			}
+		}
+		fmUnlocks[key] = now
+		if isSpUser {
+			fmRootUnlocks[key] = true
+		} else {
+			delete(fmRootUnlocks, key)
+		}
+		fmUnlockMu.Unlock()
+
+		w.Header().Set("Content-Type", "application/json")
+		json.NewEncoder(w).Encode(map[string]bool{"ok": true})
+
+	default:
+		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+	}
+}
+
+func fmListHandler(w http.ResponseWriter, r *http.Request) {
+	if !fmCheckAccess(w, r) {
+		return
+	}
+
+	if r.Method != http.MethodGet {
+		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+		return
+	}
+
+	root := fileMgrRoot
+	if fmIsRootUnlocked(r) {
+		root = "/"
+	}
+
+	path, err := fmResolvePath(r.URL.Query().Get("path"), root)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
+
+	entries, err := os.ReadDir(path)
+	if err != nil {
+		http.Error(w, "读取目录失败: "+err.Error(), http.StatusBadRequest)
+		return
+	}
+
+	list := make([]fmEntry, 0, len(entries))
+
+	for _, e := range entries {
+		info, err := e.Info()
+		if err != nil {
+			continue
+		}
+
+		list = append(list, fmEntry{
+			Name:    e.Name(),
+			IsDir:   e.IsDir(),
+			Size:    info.Size(),
+			ModTime: info.ModTime().Unix(),
+		})
+	}
+
+	sort.Slice(list, func(i, j int) bool {
+		if list[i].IsDir != list[j].IsDir {
+			return list[i].IsDir
+		}
+		return list[i].Name < list[j].Name
+	})
+
+	w.Header().Set("Content-Type", "application/json")
+	json.NewEncoder(w).Encode(map[string]any{"path": path, "list": list})
+}
+
+func fmDownloadHandler(w http.ResponseWriter, r *http.Request) {
+	if !fmCheckAccess(w, r) {
+		return
+	}
+
+	if r.Method != http.MethodGet {
+		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+		return
+	}
+
+	select {
+	case fmDownloadSem <- struct{}{}:
+		defer func() { <-fmDownloadSem }()
+	default:
+		http.Error(w, "下载任务过多, 请稍后重试", http.StatusTooManyRequests)
+		return
+	}
+
+	root := fileMgrRoot
+	if fmIsRootUnlocked(r) {
+		root = "/"
+	}
+
+	path, err := fmResolvePath(r.URL.Query().Get("path"), root)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
+
+	info, err := os.Stat(path)
+	if err != nil {
+		http.Error(w, "文件不存在", http.StatusNotFound)
+		return
+	}
+
+	if !info.IsDir() {
+		w.Header().Set("Content-Disposition",
+			"attachment; filename*=UTF-8''"+url.PathEscape(info.Name()))
+		http.ServeFile(w, r, path)
+		return
+	}
+
+	w.Header().Set("Content-Type", "application/gzip")
+	w.Header().Set("Content-Disposition",
+		"attachment; filename*=UTF-8''"+url.PathEscape(info.Name()+".tar.gz"))
+
+	gz := gzip.NewWriter(w)
+	tw := tar.NewWriter(gz)
+
+	err = filepath.WalkDir(path, func(file string, d os.DirEntry, err error) error {
+		if err != nil {
+			return err
+		}
+
+		if err := r.Context().Err(); err != nil {
+			return err
+		}
+
+		if file == path {
+			return nil
+		}
+
+		rel, err := filepath.Rel(path, file)
+		if err != nil {
+			return err
+		}
+
+		name := filepath.ToSlash(rel)
+
+		info, err := d.Info()
+		if err != nil {
+			return err
+		}
+
+		linkTarget := ""
+		if info.Mode()&os.ModeSymlink != 0 {
+			linkTarget, err = os.Readlink(file)
+			if err != nil {
+				return err
+			}
+		}
+
+		header, err := tar.FileInfoHeader(info, linkTarget)
+		if err != nil {
+			return err
+		}
+
+		header.Name = name
+		if d.IsDir() {
+			header.Name += "/"
+		}
+
+		if err := tw.WriteHeader(header); err != nil {
+			return err
+		}
+
+		if !info.Mode().IsRegular() {
+			return nil
+		}
+
+		src, err := os.Open(file)
+		if err != nil {
+			return err
+		}
+
+		_, copyErr := io.Copy(tw, src)
+		closeErr := src.Close()
+
+		if copyErr != nil {
+			return copyErr
+		}
+		return closeErr
+	})
+
+	if err != nil {
+		return
+	}
+
+	if err := tw.Close(); err != nil {
+		return
+	}
+
+	if err := gz.Close(); err != nil {
+		return
+	}
+}
+
+func fmCleanupTempFiles(dir string) {
+	entries, err := os.ReadDir(dir)
+	if err != nil {
+		return
+	}
+
+	now := time.Now()
+
+	for _, e := range entries {
+		if !strings.HasPrefix(e.Name(), ".upload-") {
+			continue
+		}
+
+		path := filepath.Join(dir, e.Name())
+
+		fmUploadMu.Lock()
+		active := fmUploadFiles[path]
+		fmUploadMu.Unlock()
+
+		if active {
+			continue
+		}
+
+		info, err := e.Info()
+		if err != nil || !info.Mode().IsRegular() {
+			continue
+		}
+
+		if now.Sub(info.ModTime()) > fmUploadMaxAge {
+			os.Remove(path)
+		}
+	}
+}
+
+func fmFinishUploadTemp(name string, remove bool) {
+	fmUploadMu.Lock()
+	delete(fmUploadFiles, name)
+	fmUploadMu.Unlock()
+
+	if remove {
+		os.Remove(name)
+	}
+}
+
+func fmUploadHandler(w http.ResponseWriter, r *http.Request) {
+	if !fmCheckAccess(w, r) {
+		return
+	}
+
+	if r.Method != http.MethodPost {
+		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+		return
+	}
+
+	select {
+	case fmUploadSem <- struct{}{}:
+		defer func() { <-fmUploadSem }()
+	default:
+		http.Error(w, "上传任务过多, 请稍后重试", http.StatusTooManyRequests)
+		return
+	}
+
+	root := fileMgrRoot
+	if fmIsRootUnlocked(r) {
+		root = "/"
+	}
+
+	dir, err := fmResolvePath(r.URL.Query().Get("path"), root)
+	if err != nil {
+		http.Error(w, err.Error(), http.StatusBadRequest)
+		return
+	}
+
+	info, err := os.Stat(dir)
+	if err != nil || !info.IsDir() {
+		http.Error(w, "目标目录不存在", http.StatusBadRequest)
+		return
+	}
+
+	fmCleanupTempFiles(dir)
+
+	r.Body = http.MaxBytesReader(w, r.Body, fmUploadMaxSize)
+
+	mr, err := r.MultipartReader()
+	if err != nil {
+		var maxErr *http.MaxBytesError
+		if errors.As(err, &maxErr) {
+			http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
+			return
+		}
+
+		http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
+		return
+	}
+
+	var saved []string
+
+	for {
+		part, err := mr.NextPart()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			var maxErr *http.MaxBytesError
+			if errors.As(err, &maxErr) {
+				http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
+				return
+			}
+
+			http.Error(w, "multipart error: "+err.Error(), http.StatusBadRequest)
+			return
+		}
+
+		if part.FormName() != "file" {
+			part.Close()
+			continue
+		}
+
+		name := strings.TrimSpace(part.FileName())
+		name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))
+
+		if name == "" || name == "." || name == ".." || name == string(filepath.Separator) {
+			part.Close()
+			http.Error(w, "非法文件名", http.StatusBadRequest)
+			return
+		}
+
+		dst := filepath.Join(dir, name)
+
+		tmp, err := os.CreateTemp(dir, ".upload-*")
+		if err != nil {
+			part.Close()
+			http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
+			return
+		}
+
+		tmpName := tmp.Name()
+
+		fmUploadMu.Lock()
+		fmUploadFiles[tmpName] = true
+		fmUploadMu.Unlock()
+
+		n, copyErr := io.Copy(tmp, part)
+		closeErr := tmp.Close()
+		part.Close()
+
+		if copyErr != nil || closeErr != nil {
+			if copyErr != nil {
+				err = copyErr
+			} else {
+				err = closeErr
+			}
+
+			fmFinishUploadTemp(tmpName, true)
+
+			var maxErr *http.MaxBytesError
+			if errors.As(err, &maxErr) {
+				http.Error(w, "上传文件超过1GB限制", http.StatusRequestEntityTooLarge)
+				return
+			}
+
+			http.Error(w, "写入失败: "+err.Error(), http.StatusInternalServerError)
+			return
+		}
+
+		if err := os.Rename(tmpName, dst); err != nil {
+			fmFinishUploadTemp(tmpName, true)
+			http.Error(w, "保存失败: "+err.Error(), http.StatusInternalServerError)
+			return
+		}
+
+		fmFinishUploadTemp(tmpName, false)
+
+		saved = append(saved, fmt.Sprintf("%s(%d字节)", name, n))
+	}
+
+	if len(saved) == 0 {
+		http.Error(w, "未找到上传文件", http.StatusBadRequest)
+		return
+	}
+
+	w.Header().Set("Content-Type", "application/json")
+	json.NewEncoder(w).Encode(map[string]any{"ok": true, "saved": saved})
+}

+ 5 - 0
web-ui.service/web/app.html

@@ -10,6 +10,7 @@
 <link rel="stylesheet" href="static/css/app.css?v={{V}}">
 <link rel="stylesheet" href="static/css/button.css?v={{V}}">
 <link rel="stylesheet" href="static/css/xterm.css?v={{V}}">
+<link rel="stylesheet" href="static/css/page0.css?v={{V}}">
 <link rel="stylesheet" href="static/css/page1.css?v={{V}}">
 <link rel="stylesheet" href="static/css/page2.css?v={{V}}">
 <link rel="stylesheet" href="static/css/page3.css?v={{V}}">
@@ -44,6 +45,8 @@
   <symbol id="i-refresh" viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></symbol>
   <symbol id="i-unlock" viewBox="0 0 24 24"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></symbol>
   <symbol id="i-json-file" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M11 11c-2 0-2 1-2 2v1c0 1-1 1-2 1 1 0 2 0 2 1v1c0 1 0 2 2 2M13 11c2 0 2 1 2 2v1c0 1 1 1 2 1-1 0-2 0-2 1v1c0 1 0 2-2 2"/></symbol>
+  <symbol id="i-folder" viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></symbol>
+  <symbol id="i-file" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></symbol>
   <symbol id="i-cbd" viewBox="0 0 24 24"><rect x="8" y="7" width="8" height="13" rx="4"/><path d="M9 7a3 3 0 0 1 6 0"/><line x1="12" y1="2" x2="12" y2="4"/><line x1="8.5" y1="11" x2="3" y2="11"/><line x1="8.5" y1="15" x2="3" y2="15"/><line x1="8.5" y1="18" x2="4" y2="20"/><line x1="15.5" y1="11" x2="21" y2="11"/><line x1="15.5" y1="15" x2="21" y2="15"/><line x1="15.5" y1="18" x2="20" y2="20"/><line x1="12" y1="11" x2="12" y2="20"/></symbol>
 </svg>
 
@@ -83,6 +86,7 @@
       <div class="menu-item" data-page="page6"><svg class="icon"><use href="#i-box"/></svg>应用管理</div>
       <div class="menu-item" data-page="page9"><svg class="icon"><use href="#i-cbd"/></svg>虫情测报</div>
       <div class="menu-item" data-page="page7"><svg class="icon"><use href="#i-flask"/></svg>一键自检</div>
+      <div class="menu-item" data-page="page0"><svg class="icon"><use href="#i-folder"/></svg>文件管理</div>
       <div class="menu-item" data-page="page8"><svg class="icon"><use href="#i-term"/></svg>命令终端</div>
 
       <div class="sidebar-actions">
@@ -121,6 +125,7 @@
 <script src="static/js/log-stream.js?v={{V}}"></script>
 <script src="static/js/router.js?v={{V}}"></script>
 <script src="static/js/app.js?v={{V}}"></script>
+<script src="static/js/page0.js?v={{V}}"></script>
 <script src="static/js/page1.js?v={{V}}"></script>
 <script src="static/js/page2.js?v={{V}}"></script>
 <script src="static/js/page3.js?v={{V}}"></script>

+ 55 - 0
web-ui.service/web/pages/page0.html

@@ -0,0 +1,55 @@
+<!doctype html>
+<html lang="zh-CN">
+
+<head>
+<meta charset="utf-8">
+<title>文件管理</title>
+</head>
+
+<body>
+<div class="app">
+  <main class="view page0">
+    <div class="card fm-card">
+      <div class="card-header">
+        <h2>文件管理</h2>
+        <div class="log-actions">
+          <input type="file" id="fm-upload-input" style="display:none" onchange="fmUpload(this)">
+          <button class="btn" id="fm-upload-btn" title="上传文件到当前目录" onclick="fmPickUpload()" disabled>上传</button>
+          <span style="margin:0 1px;"></span>
+          <button class="btn" id="fm-refresh-btn" title="刷新当前目录" onclick="fmRefresh()" disabled>刷新</button>
+        </div>
+      </div>
+      <div class="fm-breadcrumb" id="fm-breadcrumb"></div>
+      <div class="fm-table-wrap">
+        <table class="fm-table">
+          <thead>
+            <tr>
+              <th>名称</th>
+              <th class="fm-col-size">大小</th>
+              <th class="fm-col-time">修改时间</th>
+              <th class="fm-col-op">操作</th>
+            </tr>
+          </thead>
+          <tbody id="fm-tbody">
+            <tr><td colspan="4" class="fm-empty">--</td></tr>
+          </tbody>
+        </table>
+      </div>
+      <div class="fm-status" id="fm-status"></div>
+
+      <!-- 解锁遮罩: 密码校验通过后才开放文件操作 -->
+      <div class="fm-lock" id="fm-lock">
+        <div class="fm-lock-box">
+          <div class="fm-lock-title"><svg class="icon"><use href="#i-unlock"/></svg>该功能已被锁定</div>
+          <div class="fm-lock-tip">请输入操作密码以使用文件管理</div>
+          <input type="password" id="fm-password" class="fm-lock-input" placeholder="操作密码" autocomplete="off" onkeydown="if(event.key==='Enter')fmUnlock()">
+          <button class="btn btn-blue fm-lock-btn" onclick="fmUnlock()">解锁</button>
+          <div class="fm-lock-err" id="fm-lock-err"></div>
+        </div>
+      </div>
+    </div>
+  </main>
+</div>
+</body>
+
+</html>

+ 204 - 0
web-ui.service/web/static/css/page0.css

@@ -0,0 +1,204 @@
+.page0 {
+    height: 100%;
+}
+
+.page0 .fm-card {
+    position: relative;
+    height: 100%;
+    display: flex;
+    flex-direction: column;
+    min-height: 0;
+}
+
+.fm-breadcrumb {
+    background: #020617;
+    border: 1px solid #1f2937;
+    border-radius: 4px;
+    padding: 8px 10px;
+    font-size: 14px;
+    font-family: ui-monospace, Consolas, monospace;
+    color: #94a3b8;
+    margin-bottom: 10px;
+    word-break: break-all;
+    flex-shrink: 0;
+}
+
+.fm-crumb {
+    color: #60a5fa;
+    cursor: pointer;
+}
+
+.fm-crumb:hover {
+    color: #93c5fd;
+    text-decoration: underline;
+}
+
+.fm-sep {
+    margin: 0 4px;
+    color: #475569;
+}
+
+.fm-table-wrap {
+    flex: 1;
+    min-height: 0;
+    overflow: auto;
+    background: #020617;
+    border: 1px solid #1f2937;
+    border-radius: 4px;
+    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.45);
+}
+
+.fm-table {
+    width: 100%;
+    border-collapse: collapse;
+    font-size: 14px;
+    color: #cbd5e1;
+}
+
+.fm-table th,
+.fm-table td {
+    padding: 8px 10px;
+    text-align: left;
+    white-space: nowrap;
+}
+
+.fm-table thead th {
+    position: sticky;
+    top: 0;
+    z-index: 1;
+    background: #0f172a;
+    color: #94a3b8;
+    font-weight: 500;
+    border-bottom: 1px solid #1f2937;
+}
+
+.fm-col-size,
+.fm-col-time {
+    width: 130px;
+}
+
+.fm-col-op {
+    width: 90px;
+}
+
+.fm-table tbody tr:hover {
+    background: #1e293b;
+}
+
+.fm-name .icon {
+    width: 15px;
+    height: 15px;
+    margin-right: 6px;
+    vertical-align: -2px;
+}
+
+tr.fm-dir .fm-name {
+    color: #e2e8f0;
+    cursor: pointer;
+}
+
+tr.fm-dir .fm-name .icon {
+    color: #60a5fa;
+}
+
+tr.fm-file .fm-name .icon {
+    color: #94a3b8;
+}
+
+.fm-empty {
+    text-align: center;
+    color: #64748b;
+    padding: 20px;
+}
+
+.fm-status {
+    min-height: 22px;
+    margin-top: 8px;
+    font-size: 14px;
+    color: #94a3b8;
+    flex-shrink: 0;
+    white-space: pre-line;
+}
+
+.fm-status.err {
+    color: #fb7185;
+}
+
+.fm-lock {
+    position: absolute;
+    inset: 0;
+    z-index: 10;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background: rgba(11, 18, 32, 0.92);
+    -webkit-backdrop-filter: blur(3px);
+    backdrop-filter: blur(3px);
+    border-radius: 6px;
+}
+
+.fm-lock-box {
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    gap: 12px;
+    padding: 28px 36px;
+    background: #0f172a;
+    border: 1px solid #24314a;
+    border-radius: 8px;
+    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.5);
+}
+
+.fm-lock-title {
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    font-size: 16px;
+    font-weight: 600;
+    color: #e2e8f0;
+}
+
+.fm-lock-title .icon {
+    width: 20px;
+    height: 20px;
+    color: #60a5fa;
+}
+
+.fm-lock-tip {
+    font-size: 14px;
+    color: #94a3b8;
+}
+
+.fm-lock-input {
+    width: 220px;
+    height: 36px;
+    background: #020617;
+    border: 1px solid rgba(148, 163, 184, 0.25);
+    border-radius: 6px;
+    color: #e5e7eb;
+    padding: 0 10px;
+    font-size: 14px;
+    outline: none;
+}
+
+.fm-lock-input:focus {
+    border-color: #3b82f6;
+}
+
+.fm-lock-btn {
+    width: 220px;
+    height: 38px;
+}
+
+.fm-lock-err {
+    min-height: 16px;
+    font-size: 14px;
+    color: #fb7185;
+}
+
+@media (max-width: 768px), (max-height: 600px) {
+    .fm-col-size,
+    .fm-col-time {
+        width: 90px;
+    }
+}

+ 570 - 0
web-ui.service/web/static/js/page0.js

@@ -0,0 +1,570 @@
+
+var fmPath = "/home";
+var fmLocked = true;
+var fmPageActive = false;
+var fmUploading = false;
+var fmDownloading = false;
+var fmLoadingList = false;
+var fmStatusText = "";
+var fmStatusErr = false;
+var fmUploadStatus = "";
+var fmDownloadStatus = "";
+var fmTaskResult = "";
+var fmTaskResultErr = false;
+
+function initPage0() {
+    fmPageActive = true;
+    fmLocked = true;
+
+    fmUpdateButtons();
+
+    if (fmStatusText) {
+        fmSetStatus(fmStatusText, fmStatusErr);
+    } else {
+        fmRenderStatus();
+    }
+
+    fmCheckUnlock();
+}
+
+function exitPage0() {
+    fmPageActive = false;
+}
+
+// ---------- 状态显示 ----------
+function fmRenderStatus() {
+    var el = document.getElementById("fm-status");
+    if (!el) {
+        return;
+    }
+
+    var text = "";
+    var isErr = false;
+
+    if (fmUploadStatus && fmDownloadStatus) {
+        text = fmUploadStatus + "\n" + fmDownloadStatus;
+    } else if (fmUploadStatus) {
+        text = fmUploadStatus;
+    } else if (fmDownloadStatus) {
+        text = fmDownloadStatus;
+    } else if (fmStatusText) {
+        text = fmStatusText;
+        isErr = fmStatusErr;
+    } else {
+        text = fmTaskResult;
+        isErr = fmTaskResultErr;
+    }
+
+    el.textContent = text;
+    el.className = "fm-status" + (isErr ? " err" : "");
+}
+
+function fmSetStatus(text, isErr) {
+    fmStatusText = text || "";
+    fmStatusErr = !!isErr && !!fmStatusText;
+
+    if (fmStatusText) {
+        fmTaskResult = "";
+        fmTaskResultErr = false;
+    }
+
+    fmRenderStatus();
+}
+
+function fmSetTaskStatus(type, text) {
+    if (type === "upload") {
+        fmUploadStatus = text || "";
+    } else {
+        fmDownloadStatus = text || "";
+    }
+
+    fmRenderStatus();
+}
+
+function fmSetTaskResult(text, isErr) {
+    fmStatusText = "";
+    fmStatusErr = false;
+    fmTaskResult = text || "";
+    fmTaskResultErr = !!isErr && !!fmTaskResult;
+
+    fmRenderStatus();
+}
+
+function fmStatusIdle() {
+    return !fmUploading && !fmDownloading;
+}
+
+function fmUpdateButtons() {
+    setBtnStatus("fm-upload-btn", !fmLocked && !fmUploading, "page0");
+    setBtnStatus("fm-refresh-btn", !fmLocked, "page0");
+
+    var tbody = document.getElementById("fm-tbody");
+    if (tbody) {
+        var buttons = tbody.querySelectorAll(".fm-download-btn");
+        for (var i = 0; i < buttons.length; i++) {
+            buttons[i].disabled = fmLocked || fmDownloading;
+        }
+    }
+}
+
+// ---------- 解锁操作 ----------
+function fmCheckUnlock() {
+    fetch("/api/files/unlock", { credentials: "include" })
+        .then(function (r) {
+            if (!r.ok) {
+                throw new Error("请求失败");
+            }
+            return r.json();
+        })
+        .then(function (d) {
+            if (d && d.unlocked) {
+                fmShowBrowser();
+            } else {
+                fmShowLock();
+            }
+        })
+        .catch(function () {
+            fmShowLock();
+        });
+}
+
+function fmShowLock() {
+    fmLocked = true;
+
+    var lock = document.getElementById("fm-lock");
+    if (lock) {
+        lock.style.display = "flex";
+    }
+
+    fmUpdateButtons();
+
+    var input = document.getElementById("fm-password");
+    if (input) {
+        input.value = "";
+        setTimeout(function () {
+            if (fmPageActive) {
+                input.focus();
+            }
+        }, 0);
+    }
+}
+
+function fmShowBrowser() {
+    fmLocked = false;
+
+    var lock = document.getElementById("fm-lock");
+    if (lock) {
+        lock.style.display = "none";
+    }
+
+    fmUpdateButtons();
+    fmLoad(fmPath || "/");
+}
+
+function fmUnlock() {
+    var errEl = document.getElementById("fm-lock-err");
+    var input = document.getElementById("fm-password");
+
+    if (!errEl || !input) {
+        return;
+    }
+
+    var pwd = input.value;
+    if (!pwd) {
+        errEl.textContent = "请输入密码";
+        return;
+    }
+
+    fetch("/api/files/unlock", {
+        method: "POST",
+        credentials: "include",
+        headers: { "Content-Type": "application/json" },
+        body: JSON.stringify({ password: pwd })
+    })
+        .then(function (r) {
+            if (!r.ok) {
+                throw new Error("密码错误");
+            }
+            return r.json();
+        })
+        .then(function () {
+            errEl.textContent = "";
+            input.value = "";
+            fmShowBrowser();
+        })
+        .catch(function (e) {
+            errEl.textContent = e.message === "密码错误" ? "密码错误" : "请求失败";
+        });
+}
+
+// ---------- 内部函数 ----------
+function fmJoin(path, name) {
+    return path === "/" ? "/" + name : path + "/" + name;
+}
+
+function fmEncodePath(path) {
+    return encodeURIComponent(path).replace(/'/g, "%27");
+}
+
+function fmFormatSize(n) {
+    if (n < 1024) {
+        return n + " B";
+    }
+
+    var units = ["KB", "MB", "GB", "TB"];
+    var v = n;
+
+    for (var i = 0; i < units.length; i++) {
+        v /= 1024;
+
+        if (v < 1024 || i === units.length - 1) {
+            return v.toFixed(v < 10 ? 1 : 0) + " " + units[i];
+        }
+    }
+
+    return n + " B";
+}
+
+function fmFormatTime(ts) {
+    if (!ts) {
+        return "--";
+    }
+
+    var d = new Date(ts * 1000);
+
+    function p(x) {
+        return String(x).padStart(2, "0");
+    }
+
+    return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate()) +
+        " " + p(d.getHours()) + ":" + p(d.getMinutes()) + ":" + p(d.getSeconds());
+}
+
+function fmCheckAuthStatus(r) {
+    if (r.status === 401 || r.status === 403) {
+        fmShowLock();
+        return true;
+    }
+
+    return false;
+}
+
+// ---------- 文件浏览 ----------
+function fmLoad(path, keepStatus) {
+    if (!fmPageActive || fmLoadingList || fmLocked) {
+        return;
+    }
+
+    fmLoadingList = true;
+
+    var loadingText = "正在加载 " + path + " ...";
+
+    if (!keepStatus && fmStatusIdle()) {
+        fmSetStatus(loadingText);
+    }
+
+    fetch("/api/files/list?path=" + encodeURIComponent(path), {
+        credentials: "include"
+    })
+        .then(function (r) {
+            if (fmCheckAuthStatus(r)) {
+                throw new Error("locked");
+            }
+
+            if (!r.ok) {
+                return r.text().then(function (t) {
+                    throw new Error(t || "加载失败");
+                });
+            }
+
+            return r.json();
+        })
+        .then(function (d) {
+            fmPath = d.path || path;
+            fmRender(d.list || []);
+
+            if (!keepStatus && fmStatusText === loadingText) {
+                fmSetStatus("");
+            }
+        })
+        .catch(function (e) {
+            if (e.message !== "locked" && !keepStatus && fmStatusText === loadingText) {
+                fmSetStatus("加载失败: " + e.message, true);
+            }
+        })
+        .finally(function () {
+            fmLoadingList = false;
+        });
+}
+
+function fmRefresh() {
+    fmLoad(fmPath);
+}
+
+function fmRender(list) {
+    var tbody = document.getElementById("fm-tbody");
+    var bc = document.getElementById("fm-breadcrumb");
+
+    if (!tbody || !bc) {
+        return;
+    }
+
+    var html = '<span class="fm-crumb" onclick="fmLoad(\'/\')">/</span>';
+
+    if (fmPath !== "/") {
+        var parts = fmPath.split("/").filter(Boolean);
+        var acc = "";
+
+        for (var i = 0; i < parts.length; i++) {
+            acc += "/" + parts[i];
+
+            if (i > 0) {
+                html += '<span class="fm-sep">/</span>';
+            }
+
+            html += '<span class="fm-crumb" onclick="fmLoad(decodeURIComponent(\'' +
+                fmEncodePath(acc) + '\'))">' + escapeHtml(parts[i]) + "</span>";
+        }
+    }
+
+    bc.innerHTML = html;
+
+    var rows = "";
+
+    if (fmPath !== "/") {
+        var parent = fmPath.replace(/\/+$/, "").replace(/\/[^/]*$/, "") || "/";
+
+        rows +=
+            '<tr class="fm-dir">' +
+            '<td class="fm-name" onclick="fmLoad(decodeURIComponent(\'' +
+            fmEncodePath(parent) + '\'))">' +
+            '<svg class="icon"><use href="#i-folder"/></svg>..</td>' +
+            '<td class="fm-col-size">-</td>' +
+            '<td class="fm-col-time">-</td>' +
+            '<td class="fm-col-op">-</td></tr>';
+    }
+
+    for (var i = 0; i < list.length; i++) {
+        var e = list[i];
+        var child = fmJoin(fmPath, e.name);
+        var pathArg = "decodeURIComponent('" + fmEncodePath(child) + "')";
+
+        if (e.isDir) {
+            rows +=
+                '<tr class="fm-dir">' +
+                '<td class="fm-name" onclick="fmLoad(' + pathArg + ')">' +
+                '<svg class="icon"><use href="#i-folder"/></svg>' +
+                escapeHtml(e.name) + "</td>" +
+                '<td class="fm-col-size">4.0K</td>' +
+                '<td class="fm-col-time">' + fmFormatTime(e.modTime) + "</td>" +
+                '<td class="fm-col-op"><button class="btn fm-download-btn" title="下载该目录" onclick="fmDownload(' +
+                pathArg + ', true)">下载</button></td></tr>';
+        } else {
+            rows +=
+                '<tr class="fm-file">' +
+                '<td class="fm-name">' +
+                '<svg class="icon"><use href="#i-file"/></svg>' +
+                escapeHtml(e.name) + "</td>" +
+                '<td class="fm-col-size">' + fmFormatSize(e.size) + "</td>" +
+                '<td class="fm-col-time">' + fmFormatTime(e.modTime) + "</td>" +
+                '<td class="fm-col-op"><button class="btn fm-download-btn" title="下载该文件" onclick="fmDownload(' +
+                pathArg + ')">下载</button></td></tr>';
+        }
+    }
+
+    tbody.innerHTML = rows || '<tr><td colspan="4" class="fm-empty">空目录</td></tr>';
+
+    fmUpdateButtons();
+}
+
+// ---------- 文件上传 ----------
+function fmPickUpload() {
+    document.getElementById("fm-upload-input").click();
+}
+
+function fmUpload(input) {
+    var files = input.files;
+
+    if (!files || !files.length || fmUploading || fmLocked) {
+        return;
+    }
+
+    fmUploading = true;
+    fmStatusText = "";
+    fmTaskResult = "";
+    fmTaskResultErr = false;
+    fmSetTaskStatus("upload", "正在准备上传...");
+    fmUpdateButtons();
+
+    var uploadDir = fmPath;
+    var uploaded = 0;
+
+    function next() {
+        if (uploaded >= files.length) {
+            fmUploading = false;
+            fmSetTaskStatus("upload", "");
+            fmUpdateButtons();
+            input.value = "";
+
+            setTimeout(function () {
+                if (fmPageActive) {
+                    fmPath = uploadDir;
+                    fmLoad(uploadDir, true);
+                }
+            }, 800);
+
+            return;
+        }
+
+        var file = files[uploaded++];
+        fmSetTaskStatus("upload", "正在上传 " + file.name + " (0%)");
+
+        var fd = new FormData();
+        fd.append("file", file);
+
+        var xhr = new XMLHttpRequest();
+        xhr.open("POST", "/api/files/upload?path=" + encodeURIComponent(uploadDir), true);
+        xhr.timeout = 0;
+
+        xhr.upload.onprogress = function (e) {
+            if (!e.lengthComputable) {
+                return;
+            }
+
+            var percent = Math.floor((e.loaded * 100) / e.total);
+
+            if (percent >= 100) {
+                fmSetTaskStatus("upload", "上传完成,正在保存 " + file.name + " ...");
+            } else {
+                fmSetTaskStatus("upload", "正在上传 " + file.name + " (" + percent + "%)");
+            }
+        };
+
+        xhr.onload = function () {
+            if (xhr.status === 401 || xhr.status === 403) {
+                fmUploading = false;
+                fmSetTaskStatus("upload", "");
+                fmUpdateButtons();
+                input.value = "";
+
+                if (fmPageActive) {
+                    fmShowLock();
+                }
+
+                return;
+            }
+
+            if (xhr.status === 200) {
+                fmSetTaskResult("上传完成: " + file.name + " (已保存到 " + uploadDir + ")");
+            } else if (xhr.status === 0) {
+                fmSetTaskResult("上传失败: 网络连接中断 (" + file.name + ")", true);
+            } else {
+                fmSetTaskResult("上传失败: " + (xhr.responseText || "HTTP " + xhr.status), true);
+            }
+
+            next();
+        };
+
+        xhr.onerror = function () {
+            fmSetTaskResult("上传失败: 网络错误 (" + file.name + ")", true);
+            next();
+        };
+
+        xhr.send(fd);
+    }
+
+    next();
+}
+
+// ---------- 文件下载 ----------
+function fmDownload(path, isDir) {
+    if (fmDownloading || fmLocked) {
+        return;
+    }
+
+    var name = path.split("/").filter(Boolean).pop() || "download";
+
+    if (isDir) {
+        name += ".tar.gz";
+    }
+
+    fmDownloading = true;
+    fmStatusText = "";
+    fmTaskResult = "";
+    fmTaskResultErr = false;
+    fmSetTaskStatus("download", "准备下载 " + name + " ...");
+    fmUpdateButtons();
+
+    var xhr = new XMLHttpRequest();
+    xhr.open("GET", "/api/files/download?path=" + encodeURIComponent(path), true);
+    xhr.responseType = "blob";
+    xhr.timeout = 0;
+
+    xhr.onprogress = function (e) {
+        if (e.lengthComputable && e.total > 0) {
+            var percent = Math.floor((e.loaded * 100) / e.total);
+            fmSetTaskStatus("download", "正在下载 " + name + " (" + percent + "%)");
+        } else {
+            fmSetTaskStatus("download", "正在下载 " + name + " (已接收 " + fmFormatSize(e.loaded) + ")");
+        }
+    };
+
+    xhr.onload = function () {
+        if (xhr.status === 401 || xhr.status === 403) {
+            fmDownloading = false;
+            fmSetTaskStatus("download", "");
+            fmUpdateButtons();
+
+            if (fmPageActive) {
+                fmShowLock();
+            }
+            return;
+        }
+
+        if (xhr.status !== 200) {
+            var reader = new FileReader();
+            reader.onload = function () {
+                fmDownloading = false;
+                fmSetTaskStatus("download", "");
+                fmSetTaskResult("下载失败: " + (reader.result || "HTTP " + xhr.status) + " (" + name + ")", true);
+                fmUpdateButtons();
+            };
+            reader.onerror = function () {
+                fmDownloading = false;
+                fmSetTaskStatus("download", "");
+                fmSetTaskResult("下载失败: HTTP " + xhr.status + " (" + name + ")", true);
+                fmUpdateButtons();
+            };
+            reader.readAsText(xhr.response);
+            return;
+        }
+
+        var url = URL.createObjectURL(xhr.response);
+        var a = document.createElement("a");
+
+        a.href = url;
+        a.download = name;
+
+        document.body.appendChild(a);
+        a.click();
+        document.body.removeChild(a);
+
+        setTimeout(function () {
+            URL.revokeObjectURL(url);
+        }, 10000);
+
+        fmDownloading = false;
+        fmSetTaskStatus("download", "");
+        fmSetTaskResult("下载完成: " + name);
+        fmUpdateButtons();
+    };
+
+    xhr.onerror = function () {
+        fmDownloading = false;
+        fmSetTaskStatus("download", "");
+        fmSetTaskResult("下载失败: 网络错误 (" + name + ")", true);
+        fmUpdateButtons();
+    };
+
+    xhr.send();
+}

+ 9 - 0
web-ui.service/web/static/js/router.js

@@ -1,4 +1,5 @@
 var routes = {
+    page0: "pages/page0.html",
     page1: "pages/page1.html",
     page2: "pages/page2.html",
     page3: "pages/page3.html",
@@ -12,6 +13,14 @@ var routes = {
 var currentPage = null;
 var loadingPage = false;
 var pageHandlers = {
+    page0: {
+        init: function () {
+            if (window.initPage0) window.initPage0();
+        },
+        exit: function () {
+            if (window.exitPage0) window.exitPage0();
+        },
+    },
     page1: {
         init: function () {
             if (window.initPage1) window.initPage1();

+ 20 - 0
web-ui.service/web_route.go

@@ -46,6 +46,26 @@ var routes = []Route{
 	},
 
 	{
+		"/api/files/unlock",
+		fmUnlockHandler,
+	},
+
+	{
+		"/api/files/list",
+		fmListHandler,
+	},
+
+	{
+		"/api/files/download",
+		fmDownloadHandler,
+	},
+
+	{
+		"/api/files/upload",
+		fmUploadHandler,
+	},
+
+	{
 		"/api/system/info",
 		systemInfoHandler,
 	},

+ 4 - 0
web-ui.service/web_ui.go

@@ -30,6 +30,10 @@ func (w gzipResponseWriter) Write(b []byte) (int, error) {
 
 func gzipHandler(h http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if strings.HasPrefix(r.URL.Path, "/api/") {
+			w.Header().Set("Cache-Control", "no-store")
+		}
+
 		if r.Method == http.MethodHead ||
 			!strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
 			h.ServeHTTP(w, r)