Files
AI-Expert-Sidebar/internal/handler/library.go
T
2026-04-01 14:09:33 +08:00

95 lines
2.7 KiB
Go

package handler
import (
"context"
"AI-Expert-Sidebar/internal/database"
"AI-Expert-Sidebar/internal/service"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// LibraryHandler exposes library management and CSV import via Wails bindings.
type LibraryHandler struct{ ctx context.Context }
func NewLibraryHandler() *LibraryHandler { return &LibraryHandler{} }
func (h *LibraryHandler) SetContext(ctx context.Context) { h.ctx = ctx }
// ListLibraries returns all registered knowledge libraries.
func (h *LibraryHandler) ListLibraries() []LibraryInfo {
libs, err := service.ListLibraries()
if err != nil {
return nil
}
out := make([]LibraryInfo, len(libs))
for i, l := range libs {
out[i] = LibraryInfo{
ID: l.ID, Name: l.Name, Description: l.Description,
EntryCount: l.EntryCount, IsActive: l.Name == database.GetActiveLibName(),
}
}
return out
}
// GetActiveLibrary returns the name of the currently active library.
func (h *LibraryHandler) GetActiveLibrary() string {
return database.GetActiveLibName()
}
// CreateLibrary registers a new knowledge library.
func (h *LibraryHandler) CreateLibrary(name, description string) string {
if name == "" {
return "名称不能为空"
}
lib, err := service.CreateLibrary(name, description)
if err != nil {
return err.Error()
}
// Auto-switch to newly created library
service.SwitchLibrary(lib.Name) //nolint
return ""
}
// SwitchLibrary makes the named library active.
func (h *LibraryHandler) SwitchLibrary(name string) string {
if err := service.SwitchLibrary(name); err != nil {
return err.Error()
}
return ""
}
// DeleteLibrary removes a library from the registry (file is kept).
func (h *LibraryHandler) DeleteLibrary(name string) string {
if name == database.GetActiveLibName() {
return "不能删除当前使用中的知识库,请先切换到其他库"
}
if err := service.DeleteLibrary(name, false); err != nil {
return err.Error()
}
return ""
}
// ImportCSV opens a native file dialog then imports CSV data into the active library.
func (h *LibraryHandler) ImportCSV() service.ImportResult {
filePath, err := runtime.OpenFileDialog(h.ctx, runtime.OpenDialogOptions{
Title: "选择 CSV 文件",
Filters: []runtime.FileFilter{
{DisplayName: "CSV 文件", Pattern: "*.csv"},
{DisplayName: "所有文件", Pattern: "*"},
},
})
if err != nil || filePath == "" {
return service.ImportResult{Error: "已取消"}
}
return service.ImportCSV(filePath)
}
// LibraryInfo is the frontend-facing representation of a library.
type LibraryInfo struct {
ID uint `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
EntryCount int `json:"entry_count"`
IsActive bool `json:"is_active"`
}