✨ Added data migration service
This commit is contained in:
@@ -28,12 +28,8 @@ const (
|
||||
|
||||
// GeneralConfig 通用设置配置
|
||||
type GeneralConfig struct {
|
||||
AlwaysOnTop bool `json:"alwaysOnTop" yaml:"always_on_top" mapstructure:"always_on_top"` // 窗口是否置顶
|
||||
DefaultDataPath string `json:"defaultDataPath" yaml:"default_data_path" mapstructure:"default_data_path"` // 默认数据存储路径
|
||||
|
||||
// 数据存储路径配置
|
||||
UseCustomDataPath bool `json:"useCustomDataPath" yaml:"use_custom_data_path" mapstructure:"use_custom_data_path"` // 是否使用自定义数据路径
|
||||
CustomDataPath string `json:"customDataPath" yaml:"custom_data_path" mapstructure:"custom_data_path"` // 自定义数据存储路径
|
||||
AlwaysOnTop bool `json:"alwaysOnTop" yaml:"always_on_top" mapstructure:"always_on_top"` // 窗口是否置顶
|
||||
DataPath string `json:"dataPath" yaml:"data_path" mapstructure:"data_path"` // 数据存储路径
|
||||
|
||||
// 全局热键设置
|
||||
EnableGlobalHotkey bool `json:"enableGlobalHotkey" yaml:"enable_global_hotkey" mapstructure:"enable_global_hotkey"` // 是否启用全局热键
|
||||
@@ -111,9 +107,7 @@ func NewDefaultAppConfig() *AppConfig {
|
||||
return &AppConfig{
|
||||
General: GeneralConfig{
|
||||
AlwaysOnTop: false,
|
||||
DefaultDataPath: dataDir,
|
||||
UseCustomDataPath: false,
|
||||
CustomDataPath: "",
|
||||
DataPath: dataDir,
|
||||
EnableGlobalHotkey: false,
|
||||
GlobalHotkey: HotkeyCombo{
|
||||
Ctrl: false,
|
||||
|
@@ -19,6 +19,8 @@ type ConfigChangeType string
|
||||
const (
|
||||
// ConfigChangeTypeHotkey 热键配置变更
|
||||
ConfigChangeTypeHotkey ConfigChangeType = "hotkey"
|
||||
// ConfigChangeTypeDataPath 数据路径配置变更
|
||||
ConfigChangeTypeDataPath ConfigChangeType = "datapath"
|
||||
)
|
||||
|
||||
// ConfigChangeCallback 配置变更回调函数类型
|
||||
@@ -449,6 +451,45 @@ func CreateHotkeyListener(callback func(enable bool, hotkey *models.HotkeyCombo)
|
||||
}
|
||||
}
|
||||
|
||||
// CreateDataPathListener 创建数据路径配置监听器
|
||||
func CreateDataPathListener(callback func(oldPath, newPath string) error) *ConfigListener {
|
||||
return &ConfigListener{
|
||||
Name: "DataPathListener",
|
||||
ChangeType: ConfigChangeTypeDataPath,
|
||||
Callback: func(changeType ConfigChangeType, oldConfig, newConfig interface{}) error {
|
||||
var oldPath, newPath string
|
||||
|
||||
// 处理旧配置
|
||||
if oldAppConfig, ok := oldConfig.(*models.AppConfig); ok {
|
||||
oldPath = oldAppConfig.General.DataPath
|
||||
}
|
||||
|
||||
// 处理新配置
|
||||
if newAppConfig, ok := newConfig.(*models.AppConfig); ok {
|
||||
newPath = newAppConfig.General.DataPath
|
||||
} else if newConfig == nil {
|
||||
// 如果新配置为空,说明配置被删除,使用默认值
|
||||
defaultConfig := models.NewDefaultAppConfig()
|
||||
newPath = defaultConfig.General.DataPath
|
||||
}
|
||||
|
||||
// 只有路径真正改变时才调用回调
|
||||
if oldPath != newPath {
|
||||
return callback(oldPath, newPath)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DebounceDelay: 100 * time.Millisecond, // 较短的防抖延迟,因为数据路径变更需要快速响应
|
||||
GetConfigFunc: func(v *viper.Viper) interface{} {
|
||||
var config models.AppConfig
|
||||
if err := v.Unmarshal(&config); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &config
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ServiceShutdown 关闭服务
|
||||
func (cns *ConfigNotificationService) ServiceShutdown() error {
|
||||
cns.Cleanup()
|
||||
|
@@ -105,9 +105,7 @@ func setDefaults(v *viper.Viper) {
|
||||
|
||||
// 通用设置默认值
|
||||
v.SetDefault("general.always_on_top", defaultConfig.General.AlwaysOnTop)
|
||||
v.SetDefault("general.default_data_path", defaultConfig.General.DefaultDataPath)
|
||||
v.SetDefault("general.use_custom_data_path", defaultConfig.General.UseCustomDataPath)
|
||||
v.SetDefault("general.custom_data_path", defaultConfig.General.CustomDataPath)
|
||||
v.SetDefault("general.data_path", defaultConfig.General.DataPath)
|
||||
v.SetDefault("general.enable_global_hotkey", defaultConfig.General.EnableGlobalHotkey)
|
||||
v.SetDefault("general.global_hotkey.ctrl", defaultConfig.General.GlobalHotkey.Ctrl)
|
||||
v.SetDefault("general.global_hotkey.shift", defaultConfig.General.GlobalHotkey.Shift)
|
||||
@@ -257,3 +255,13 @@ func (cs *ConfigService) SetHotkeyChangeCallback(callback func(enable bool, hotk
|
||||
hotkeyListener := CreateHotkeyListener(callback)
|
||||
return cs.notificationService.RegisterListener(hotkeyListener)
|
||||
}
|
||||
|
||||
// SetDataPathChangeCallback 设置数据路径配置变更回调
|
||||
func (cs *ConfigService) SetDataPathChangeCallback(callback func(oldPath, newPath string) error) error {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
|
||||
// 创建数据路径监听器并注册
|
||||
dataPathListener := CreateDataPathListener(callback)
|
||||
return cs.notificationService.RegisterListener(dataPathListener)
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@ import (
|
||||
// DialogService 对话框服务,处理文件选择等对话框操作
|
||||
type DialogService struct {
|
||||
logger *log.LoggerService
|
||||
window *application.WebviewWindow // 绑定的窗口
|
||||
}
|
||||
|
||||
// NewDialogService 创建新的对话框服务实例
|
||||
@@ -18,9 +19,16 @@ func NewDialogService(logger *log.LoggerService) *DialogService {
|
||||
|
||||
return &DialogService{
|
||||
logger: logger,
|
||||
window: nil, // 初始为空,后续通过 SetWindow 设置
|
||||
}
|
||||
}
|
||||
|
||||
// SetWindow 设置绑定的窗口
|
||||
func (ds *DialogService) SetWindow(window *application.WebviewWindow) {
|
||||
ds.window = window
|
||||
ds.logger.Info("Dialog service window binding updated")
|
||||
}
|
||||
|
||||
// SelectDirectory 打开目录选择对话框
|
||||
func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
dialog := application.OpenFileDialogWithOptions(&application.OpenFileDialogOptions{
|
||||
@@ -41,9 +49,9 @@ func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
ResolvesAliases: true, // 解析别名/快捷方式
|
||||
|
||||
// 对话框文本配置
|
||||
Title: "选择数据存储目录",
|
||||
Message: "请选择用于存储应用数据的文件夹",
|
||||
ButtonText: "选择",
|
||||
Title: "Select Directory",
|
||||
Message: "Select the folder where you want to store your app data",
|
||||
ButtonText: "Select",
|
||||
|
||||
// 不设置过滤器,因为我们选择目录
|
||||
Filters: nil,
|
||||
@@ -51,8 +59,8 @@ func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
// 不指定默认目录,让系统决定
|
||||
Directory: "",
|
||||
|
||||
// 不绑定到特定窗口,使用默认行为
|
||||
Window: nil,
|
||||
// 绑定到主窗口
|
||||
Window: ds.window,
|
||||
})
|
||||
|
||||
path, err := dialog.PromptForSingleSelection()
|
||||
|
@@ -1,119 +1,183 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
"voidraft/internal/models"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// DocumentError 文档操作错误
|
||||
type DocumentError struct {
|
||||
Operation string // 操作名称
|
||||
Err error // 原始错误
|
||||
}
|
||||
|
||||
// Error 实现error接口
|
||||
func (e *DocumentError) Error() string {
|
||||
return fmt.Sprintf("document error during %s: %v", e.Operation, e.Err)
|
||||
}
|
||||
|
||||
// Unwrap 获取原始错误
|
||||
func (e *DocumentError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// DocumentService 提供文档管理功能
|
||||
type DocumentService struct {
|
||||
configService *ConfigService
|
||||
logger *log.LoggerService
|
||||
document *models.Document // 文档实例
|
||||
document *models.Document
|
||||
docStore *Store[models.Document]
|
||||
mutex sync.RWMutex // 保护document的读写
|
||||
mutex sync.RWMutex
|
||||
|
||||
// 定时保存
|
||||
saveTimer *time.Timer
|
||||
timerMutex sync.Mutex // 保护定时器操作
|
||||
isDirty bool // 文档是否有未保存的变更
|
||||
|
||||
// 服务控制
|
||||
shutdown chan struct{}
|
||||
shutdownOnce sync.Once
|
||||
// 自动保存优化
|
||||
saveTimer *time.Timer
|
||||
isDirty bool
|
||||
lastSaveTime time.Time
|
||||
pendingContent string // 暂存待保存的内容
|
||||
}
|
||||
|
||||
// NewDocumentService 创建新的文档服务实例
|
||||
// NewDocumentService 创建文档服务
|
||||
func NewDocumentService(configService *ConfigService, logger *log.LoggerService) *DocumentService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
service := &DocumentService{
|
||||
return &DocumentService{
|
||||
configService: configService,
|
||||
logger: logger,
|
||||
shutdown: make(chan struct{}),
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
// Initialize 初始化文档服务
|
||||
// Initialize 初始化服务
|
||||
func (ds *DocumentService) Initialize() error {
|
||||
// 确保文档目录存在
|
||||
if err := ds.ensureDocumentsDir(); err != nil {
|
||||
ds.logger.Error("Document: Failed to ensure documents directory", "error", err)
|
||||
return &DocumentError{Operation: "initialize", Err: err}
|
||||
if err := ds.initStore(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 初始化文档存储
|
||||
if err := ds.initDocumentStore(); err != nil {
|
||||
ds.logger.Error("Document: Failed to initialize document store", "error", err)
|
||||
return &DocumentError{Operation: "init_store", Err: err}
|
||||
}
|
||||
|
||||
// 加载默认文档
|
||||
if err := ds.loadDefaultDocument(); err != nil {
|
||||
ds.logger.Error("Document: Failed to load default document", "error", err)
|
||||
return &DocumentError{Operation: "load_default", Err: err}
|
||||
}
|
||||
|
||||
// 启动定时保存
|
||||
ds.loadDocument()
|
||||
ds.startAutoSave()
|
||||
return nil
|
||||
}
|
||||
|
||||
// initStore 初始化存储
|
||||
func (ds *DocumentService) initStore() error {
|
||||
docPath, err := ds.getDocumentPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(docPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.docStore = NewStore[models.Document](StoreOption{
|
||||
FilePath: docPath,
|
||||
AutoSave: false,
|
||||
Logger: ds.logger,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// startAutoSave 启动定时保存
|
||||
func (ds *DocumentService) startAutoSave() {
|
||||
// getDocumentPath 获取文档路径
|
||||
func (ds *DocumentService) getDocumentPath() (string, error) {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
ds.logger.Error("Document: Failed to get config for auto save", "error", err)
|
||||
ds.scheduleNextSave(5 * time.Second) // 默认5秒
|
||||
return
|
||||
return "", err
|
||||
}
|
||||
|
||||
delay := time.Duration(config.Editing.AutoSaveDelay) * time.Millisecond
|
||||
ds.scheduleNextSave(delay)
|
||||
return filepath.Join(config.General.DataPath, "docs", "default.json"), nil
|
||||
}
|
||||
|
||||
// scheduleNextSave 安排下次保存
|
||||
func (ds *DocumentService) scheduleNextSave(delay time.Duration) {
|
||||
ds.timerMutex.Lock()
|
||||
defer ds.timerMutex.Unlock()
|
||||
// loadDocument 加载文档
|
||||
func (ds *DocumentService) loadDocument() {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
// 停止现有定时器
|
||||
doc := ds.docStore.Get()
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建新文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
ds.docStore.Set(*ds.document)
|
||||
ds.logger.Info("Document: Created new document")
|
||||
} else {
|
||||
ds.document = &doc
|
||||
ds.logger.Info("Document: Loaded existing document")
|
||||
}
|
||||
}
|
||||
|
||||
// GetActiveDocument 获取活动文档
|
||||
func (ds *DocumentService) GetActiveDocument() (*models.Document, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 返回副本
|
||||
docCopy := *ds.document
|
||||
return &docCopy, nil
|
||||
}
|
||||
|
||||
// UpdateActiveDocumentContent 更新文档内容
|
||||
func (ds *DocumentService) UpdateActiveDocumentContent(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document != nil {
|
||||
// 只在内容真正改变时才标记为脏
|
||||
if ds.document.Content != content {
|
||||
ds.pendingContent = content
|
||||
ds.isDirty = true
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceSave 强制保存
|
||||
func (ds *DocumentService) ForceSave() error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ds.docStore.Save(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.isDirty = false
|
||||
ds.lastSaveTime = now
|
||||
ds.logger.Info("Document: Force save completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// startAutoSave 启动自动保存
|
||||
func (ds *DocumentService) startAutoSave() {
|
||||
delay := 5 * time.Second // 默认延迟
|
||||
|
||||
if config, err := ds.configService.GetConfig(); err == nil {
|
||||
delay = time.Duration(config.Editing.AutoSaveDelay) * time.Millisecond
|
||||
}
|
||||
|
||||
ds.scheduleAutoSave(delay)
|
||||
}
|
||||
|
||||
// scheduleAutoSave 安排自动保存
|
||||
func (ds *DocumentService) scheduleAutoSave(delay time.Duration) {
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
}
|
||||
|
||||
// 创建新的定时器
|
||||
ds.saveTimer = time.AfterFunc(delay, func() {
|
||||
ds.performAutoSave()
|
||||
// 安排下次保存
|
||||
ds.startAutoSave()
|
||||
ds.startAutoSave() // 重新安排
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,188 +186,94 @@ func (ds *DocumentService) performAutoSave() {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
// 如果没有变更,跳过保存
|
||||
if !ds.isDirty || ds.document == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 更新元数据并保存
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
// 检查距离上次保存的时间间隔,避免过于频繁的保存
|
||||
now := time.Now()
|
||||
if now.Sub(ds.lastSaveTime) < time.Second {
|
||||
// 如果距离上次保存不到1秒,跳过此次保存
|
||||
// 下一个自动保存周期会重新尝试
|
||||
ds.logger.Debug("Document: Skipping auto save due to recent save")
|
||||
return
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Auto saving document",
|
||||
"id", ds.document.Meta.ID,
|
||||
"contentLength", len(ds.document.Content))
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
ds.logger.Error("Document: Failed to auto save document", "error", err)
|
||||
ds.logger.Error("Document: Auto save failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := ds.docStore.Save(); err != nil {
|
||||
ds.logger.Error("Document: Failed to force save document", "error", err)
|
||||
ds.logger.Error("Document: Auto save failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 重置脏标记
|
||||
ds.isDirty = false
|
||||
ds.logger.Info("Document: Auto save completed")
|
||||
ds.lastSaveTime = now
|
||||
ds.logger.Debug("Document: Auto save completed")
|
||||
}
|
||||
|
||||
// stopTimer 停止定时器
|
||||
func (ds *DocumentService) stopTimer() {
|
||||
ds.timerMutex.Lock()
|
||||
defer ds.timerMutex.Unlock()
|
||||
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
ds.saveTimer = nil
|
||||
}
|
||||
}
|
||||
|
||||
// initDocumentStore 初始化文档存储
|
||||
func (ds *DocumentService) initDocumentStore() error {
|
||||
docPath, err := ds.getDefaultDocumentPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Initializing document store", "path", docPath)
|
||||
|
||||
ds.docStore = NewStore[models.Document](StoreOption{
|
||||
FilePath: docPath,
|
||||
AutoSave: true,
|
||||
Logger: ds.logger,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureDocumentsDir 确保文档目录存在
|
||||
func (ds *DocumentService) ensureDocumentsDir() error {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var dataPath string
|
||||
if config.General.UseCustomDataPath && config.General.CustomDataPath != "" {
|
||||
dataPath = config.General.CustomDataPath
|
||||
} else {
|
||||
dataPath = config.General.DefaultDataPath
|
||||
}
|
||||
|
||||
docsDir := filepath.Join(dataPath, "docs")
|
||||
return os.MkdirAll(docsDir, 0755)
|
||||
}
|
||||
|
||||
// getDocumentsDir 获取文档目录路径
|
||||
func (ds *DocumentService) getDocumentsDir() (string, error) {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var dataPath string
|
||||
if config.General.UseCustomDataPath && config.General.CustomDataPath != "" {
|
||||
dataPath = config.General.CustomDataPath
|
||||
} else {
|
||||
dataPath = config.General.DefaultDataPath
|
||||
}
|
||||
|
||||
return filepath.Join(dataPath, "docs"), nil
|
||||
}
|
||||
|
||||
// getDefaultDocumentPath 获取默认文档路径
|
||||
func (ds *DocumentService) getDefaultDocumentPath() (string, error) {
|
||||
docsDir, err := ds.getDocumentsDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(docsDir, "default.json"), nil
|
||||
}
|
||||
|
||||
// loadDefaultDocument 加载默认文档
|
||||
func (ds *DocumentService) loadDefaultDocument() error {
|
||||
doc := ds.docStore.Get()
|
||||
|
||||
// ReloadDocument 重新加载文档
|
||||
func (ds *DocumentService) ReloadDocument() error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建默认文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
|
||||
// 保存默认文档
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return &DocumentError{Operation: "save_default", Err: err}
|
||||
// 强制保存当前文档
|
||||
if ds.document != nil && ds.isDirty {
|
||||
if err := ds.forceSaveInternal(); err != nil {
|
||||
ds.logger.Error("Document: Failed to save before reload", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Created and saved default document")
|
||||
// 重新初始化存储
|
||||
if err := ds.initStore(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 重新加载文档
|
||||
doc := ds.docStore.Get()
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建新文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
ds.docStore.Set(*ds.document)
|
||||
ds.logger.Info("Document: Created new document after reload")
|
||||
} else {
|
||||
ds.document = &doc
|
||||
ds.logger.Info("Document: Loaded default document", "id", doc.Meta.ID)
|
||||
ds.logger.Info("Document: Loaded existing document after reload")
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
ds.isDirty = false
|
||||
ds.pendingContent = ""
|
||||
ds.lastSaveTime = time.Now()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveDocument 获取当前活动文档
|
||||
func (ds *DocumentService) GetActiveDocument() (*models.Document, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
// forceSaveInternal 内部强制保存(不加锁)
|
||||
func (ds *DocumentService) forceSaveInternal() error {
|
||||
if ds.document == nil {
|
||||
return nil, errors.New("no active document loaded")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回副本以防止外部修改
|
||||
docCopy := *ds.document
|
||||
return &docCopy, nil
|
||||
}
|
||||
|
||||
// GetActiveDocumentContent 获取当前活动文档内容
|
||||
func (ds *DocumentService) GetActiveDocumentContent() (string, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return "", errors.New("no active document loaded")
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
return ds.document.Content, nil
|
||||
}
|
||||
now := time.Now()
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
// UpdateActiveDocumentContent 更新当前活动文档内容
|
||||
func (ds *DocumentService) UpdateActiveDocumentContent(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
|
||||
// 更新文档内容并标记为脏
|
||||
ds.document.Content = content
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
ds.isDirty = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveDocumentSync 同步保存文档内容
|
||||
func (ds *DocumentService) SaveDocumentSync(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
|
||||
// 更新内容
|
||||
ds.document.Content = content
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
|
||||
// 立即保存
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -312,57 +282,33 @@ func (ds *DocumentService) SaveDocumentSync(content string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 重置脏标记
|
||||
ds.isDirty = false
|
||||
ds.logger.Info("Document: Sync save completed")
|
||||
ds.lastSaveTime = now
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceSave 强制保存当前文档
|
||||
func (ds *DocumentService) ForceSave() error {
|
||||
ds.logger.Info("Document: Force save triggered")
|
||||
|
||||
ds.mutex.RLock()
|
||||
if ds.document == nil {
|
||||
ds.mutex.RUnlock()
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
content := ds.document.Content
|
||||
ds.mutex.RUnlock()
|
||||
|
||||
return ds.SaveDocumentSync(content)
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
// ServiceShutdown 关闭服务
|
||||
func (ds *DocumentService) ServiceShutdown() error {
|
||||
ds.logger.Info("Document: Service is shutting down...")
|
||||
// 停止定时器
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
}
|
||||
|
||||
// 确保只执行一次关闭
|
||||
var shutdownErr error
|
||||
ds.shutdownOnce.Do(func() {
|
||||
// 停止定时器
|
||||
ds.stopTimer()
|
||||
// 最后保存
|
||||
if err := ds.ForceSave(); err != nil {
|
||||
ds.logger.Error("Document: Failed to save on shutdown", "error", err)
|
||||
}
|
||||
|
||||
// 执行最后一次保存
|
||||
ds.mutex.RLock()
|
||||
if ds.document != nil && ds.isDirty {
|
||||
content := ds.document.Content
|
||||
ds.mutex.RUnlock()
|
||||
|
||||
if err := ds.SaveDocumentSync(content); err != nil {
|
||||
ds.logger.Error("Document: Failed to save on shutdown", "error", err)
|
||||
shutdownErr = err
|
||||
} else {
|
||||
ds.logger.Info("Document: Document saved successfully on shutdown")
|
||||
}
|
||||
} else {
|
||||
ds.mutex.RUnlock()
|
||||
}
|
||||
|
||||
// 关闭服务
|
||||
close(ds.shutdown)
|
||||
ds.logger.Info("Document: Service shutdown completed")
|
||||
})
|
||||
|
||||
return shutdownErr
|
||||
ds.logger.Info("Document: Service shutdown completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnDataPathChanged 处理数据路径变更
|
||||
func (ds *DocumentService) OnDataPathChanged(oldPath, newPath string) error {
|
||||
ds.logger.Info("Document: Data path changed, reloading document",
|
||||
"oldPath", oldPath,
|
||||
"newPath", newPath)
|
||||
|
||||
// 重新加载文档以使用新的路径
|
||||
return ds.ReloadDocument()
|
||||
}
|
||||
|
562
internal/services/migration_service.go
Normal file
562
internal/services/migration_service.go
Normal file
@@ -0,0 +1,562 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// MigrationStatus 迁移状态
|
||||
type MigrationStatus string
|
||||
|
||||
const (
|
||||
MigrationStatusIdle MigrationStatus = "idle" // 空闲状态
|
||||
MigrationStatusPreparing MigrationStatus = "preparing" // 准备中
|
||||
MigrationStatusMigrating MigrationStatus = "migrating" // 迁移中
|
||||
MigrationStatusCompleted MigrationStatus = "completed" // 完成
|
||||
MigrationStatusFailed MigrationStatus = "failed" // 失败
|
||||
MigrationStatusCancelled MigrationStatus = "cancelled" // 取消
|
||||
)
|
||||
|
||||
// MigrationProgress 迁移进度信息
|
||||
type MigrationProgress struct {
|
||||
Status MigrationStatus `json:"status"` // 迁移状态
|
||||
CurrentFile string `json:"currentFile"` // 当前处理的文件
|
||||
ProcessedFiles int `json:"processedFiles"` // 已处理文件数
|
||||
TotalFiles int `json:"totalFiles"` // 总文件数
|
||||
ProcessedBytes int64 `json:"processedBytes"` // 已处理字节数
|
||||
TotalBytes int64 `json:"totalBytes"` // 总字节数
|
||||
Progress float64 `json:"progress"` // 进度百分比 (0-100)
|
||||
Message string `json:"message"` // 状态消息
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
StartTime time.Time `json:"startTime"` // 开始时间
|
||||
EstimatedTime time.Duration `json:"estimatedTime"` // 估计剩余时间
|
||||
}
|
||||
|
||||
// MigrationProgressCallback 进度回调函数类型
|
||||
type MigrationProgressCallback func(progress MigrationProgress)
|
||||
|
||||
// MigrationService 迁移服务
|
||||
type MigrationService struct {
|
||||
logger *log.LoggerService
|
||||
mu sync.RWMutex
|
||||
currentProgress MigrationProgress
|
||||
progressCallback MigrationProgressCallback
|
||||
cancelFunc context.CancelFunc
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
// NewMigrationService 创建迁移服务
|
||||
func NewMigrationService(logger *log.LoggerService) *MigrationService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
return &MigrationService{
|
||||
logger: logger,
|
||||
currentProgress: MigrationProgress{
|
||||
Status: MigrationStatusIdle,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// SetProgressCallback 设置进度回调
|
||||
func (ms *MigrationService) SetProgressCallback(callback MigrationProgressCallback) {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
ms.progressCallback = callback
|
||||
}
|
||||
|
||||
// GetProgress 获取当前进度
|
||||
func (ms *MigrationService) GetProgress() MigrationProgress {
|
||||
ms.mu.RLock()
|
||||
defer ms.mu.RUnlock()
|
||||
return ms.currentProgress
|
||||
}
|
||||
|
||||
// updateProgress 更新进度并触发回调
|
||||
func (ms *MigrationService) updateProgress(progress MigrationProgress) {
|
||||
ms.mu.Lock()
|
||||
ms.currentProgress = progress
|
||||
callback := ms.progressCallback
|
||||
ms.mu.Unlock()
|
||||
|
||||
if callback != nil {
|
||||
callback(progress)
|
||||
}
|
||||
}
|
||||
|
||||
// MigrateDirectory 迁移目录
|
||||
func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
|
||||
// 创建可取消的上下文
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ms.mu.Lock()
|
||||
ms.ctx = ctx
|
||||
ms.cancelFunc = cancel
|
||||
ms.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
ms.mu.Lock()
|
||||
ms.cancelFunc = nil
|
||||
ms.ctx = nil
|
||||
ms.mu.Unlock()
|
||||
}()
|
||||
|
||||
ms.logger.Info("Migration: Starting directory migration",
|
||||
"from", srcPath,
|
||||
"to", dstPath)
|
||||
|
||||
// 初始化进度
|
||||
progress := MigrationProgress{
|
||||
Status: MigrationStatusPreparing,
|
||||
Message: "Preparing migration...",
|
||||
StartTime: time.Now(),
|
||||
}
|
||||
ms.updateProgress(progress)
|
||||
|
||||
// 检查源目录是否存在
|
||||
if _, err := os.Stat(srcPath); os.IsNotExist(err) {
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Source directory does not exist, skipping migration"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(progress)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 如果路径相同,不需要迁移
|
||||
srcAbs, _ := filepath.Abs(srcPath)
|
||||
dstAbs, _ := filepath.Abs(dstPath)
|
||||
if srcAbs == dstAbs {
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Paths are identical, no migration needed"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(progress)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查目标路径是否是源路径的子目录,防止无限递归复制
|
||||
if ms.isSubDirectory(srcAbs, dstAbs) {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = "Target path cannot be a subdirectory of source path, this would cause infinite recursive copying"
|
||||
ms.updateProgress(progress)
|
||||
return fmt.Errorf("target path cannot be a subdirectory of source path: src=%s, dst=%s", srcAbs, dstAbs)
|
||||
}
|
||||
|
||||
// 计算目录大小(用于显示进度)
|
||||
totalFiles, totalBytes, err := ms.calculateDirectorySize(ctx, srcPath)
|
||||
if err != nil {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = fmt.Sprintf("Failed to calculate directory size: %v", err)
|
||||
ms.updateProgress(progress)
|
||||
return err
|
||||
}
|
||||
|
||||
progress.TotalFiles = totalFiles
|
||||
progress.TotalBytes = totalBytes
|
||||
progress.Status = MigrationStatusMigrating
|
||||
progress.Message = "Starting atomic migration..."
|
||||
ms.updateProgress(progress)
|
||||
|
||||
// 执行原子迁移
|
||||
err = ms.atomicMove(ctx, srcPath, dstPath, &progress)
|
||||
if err != nil {
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
progress.Status = MigrationStatusCancelled
|
||||
progress.Error = "Migration cancelled"
|
||||
} else {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = fmt.Sprintf("Migration failed: %v", err)
|
||||
}
|
||||
ms.updateProgress(progress)
|
||||
return err
|
||||
}
|
||||
|
||||
// 迁移完成
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Migration completed"
|
||||
progress.Progress = 100
|
||||
progress.ProcessedFiles = totalFiles
|
||||
progress.ProcessedBytes = totalBytes
|
||||
duration := time.Since(progress.StartTime)
|
||||
ms.updateProgress(progress)
|
||||
|
||||
ms.logger.Info("Migration: Directory migration completed",
|
||||
"from", srcPath,
|
||||
"to", dstPath,
|
||||
"duration", duration,
|
||||
"files", totalFiles,
|
||||
"bytes", totalBytes)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// atomicMove 原子移动目录 - 使用压缩-移动-解压的方式
|
||||
func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 确保目标目录的父目录存在
|
||||
dstParent := filepath.Dir(dstPath)
|
||||
if err := os.MkdirAll(dstParent, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target parent directory: %v", err)
|
||||
}
|
||||
|
||||
// 检查目标路径情况
|
||||
if stat, err := os.Stat(dstPath); err == nil {
|
||||
if !stat.IsDir() {
|
||||
return fmt.Errorf("Target path exists but is not a directory: %s", dstPath)
|
||||
}
|
||||
|
||||
// 检查目录是否为空
|
||||
isEmpty, err := ms.isDirectoryEmpty(dstPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to check if target directory is empty: %v", err)
|
||||
}
|
||||
|
||||
if !isEmpty {
|
||||
return fmt.Errorf("Target directory is not empty: %s", dstPath)
|
||||
}
|
||||
|
||||
// 目录存在但为空,可以继续迁移
|
||||
ms.logger.Info("Migration: Target directory exists but is empty, proceeding with migration")
|
||||
}
|
||||
|
||||
// 尝试直接重命名(如果在同一分区,这会很快)
|
||||
progress.Message = "Attempting fast move..."
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := os.Rename(srcPath, dstPath); err == nil {
|
||||
// 重命名成功,这是最快的方式
|
||||
ms.logger.Info("Migration: Fast rename successful")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 重命名失败(可能跨分区),使用原子压缩迁移
|
||||
progress.Message = "Starting atomic compress migration..."
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
return ms.atomicCompressMove(ctx, srcPath, dstPath, progress)
|
||||
}
|
||||
|
||||
// atomicCompressMove 原子压缩迁移 - 压缩、移动、解压、清理
|
||||
func (ms *MigrationService) atomicCompressMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
|
||||
// 创建临时压缩文件
|
||||
tempDir := os.TempDir()
|
||||
tempZipFile := filepath.Join(tempDir, fmt.Sprintf("voidraft_migration_%d.zip", time.Now().UnixNano()))
|
||||
|
||||
// 确保临时文件在函数结束时被清理
|
||||
defer func() {
|
||||
if err := os.Remove(tempZipFile); err != nil && !os.IsNotExist(err) {
|
||||
ms.logger.Error("Migration: Failed to clean up temporary zip file", "file", tempZipFile, "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 第一步: 压缩源目录
|
||||
progress.Message = "Compressing source directory..."
|
||||
progress.Progress = 10
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := ms.compressDirectory(ctx, srcPath, tempZipFile, progress); err != nil {
|
||||
return fmt.Errorf("Failed to compress source directory: %v", err)
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 第二步: 解压到目标位置
|
||||
progress.Message = "Extracting to target location..."
|
||||
progress.Progress = 70
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := ms.extractToDirectory(ctx, tempZipFile, dstPath, progress); err != nil {
|
||||
return fmt.Errorf("Failed to extract to target location: %v", err)
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// 如果取消,需要清理已解压的目标目录
|
||||
os.RemoveAll(dstPath)
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 第三步: 删除源目录
|
||||
progress.Message = "Cleaning up source directory..."
|
||||
progress.Progress = 90
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := os.RemoveAll(srcPath); err != nil {
|
||||
ms.logger.Error("Migration: Failed to remove source directory", "error", err)
|
||||
// 不返回错误,因为迁移已经成功
|
||||
}
|
||||
|
||||
progress.Message = "Migration completed"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
ms.logger.Info("Migration: Atomic compress-move completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// compressDirectory 压缩目录到zip文件
|
||||
func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFile string, progress *MigrationProgress) error {
|
||||
// 创建zip文件
|
||||
zipWriter, err := os.Create(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create zip file: %v", err)
|
||||
}
|
||||
defer zipWriter.Close()
|
||||
|
||||
// 创建zip writer
|
||||
zw := zip.NewWriter(zipWriter)
|
||||
defer zw.Close()
|
||||
|
||||
// 遍历源目录并添加到zip
|
||||
return filepath.Walk(srcDir, func(filePath string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 计算相对路径
|
||||
relPath, err := filepath.Rel(srcDir, filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 跳过根目录
|
||||
if relPath == "." {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 更新当前处理的文件
|
||||
progress.CurrentFile = relPath
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
// 创建zip中的文件头
|
||||
header, err := zip.FileInfoHeader(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 使用/作为路径分隔符(zip标准)
|
||||
header.Name = strings.ReplaceAll(relPath, string(filepath.Separator), "/")
|
||||
|
||||
// 处理目录
|
||||
if info.IsDir() {
|
||||
header.Name += "/"
|
||||
header.Method = zip.Store
|
||||
} else {
|
||||
header.Method = zip.Deflate
|
||||
}
|
||||
|
||||
// 写入zip文件头
|
||||
writer, err := zw.CreateHeader(header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 如果是文件,复制内容
|
||||
if !info.IsDir() {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(writer, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// extractToDirectory 从zip文件解压到目录
|
||||
func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dstDir string, progress *MigrationProgress) error {
|
||||
// 打开zip文件
|
||||
reader, err := zip.OpenReader(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to open zip file: %v", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// 确保目标目录存在
|
||||
if err := os.MkdirAll(dstDir, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target directory: %v", err)
|
||||
}
|
||||
|
||||
// 解压每个文件
|
||||
for _, file := range reader.File {
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 更新当前处理的文件
|
||||
progress.CurrentFile = file.Name
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
// 构建目标文件路径
|
||||
dstPath := filepath.Join(dstDir, file.Name)
|
||||
|
||||
// 安全检查:防止zip slip攻击
|
||||
if !strings.HasPrefix(dstPath, filepath.Clean(dstDir)+string(os.PathSeparator)) {
|
||||
return fmt.Errorf("Invalid file path: %s", file.Name)
|
||||
}
|
||||
|
||||
// 处理目录
|
||||
if file.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(dstPath, file.FileInfo().Mode()); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 确保父目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解压文件
|
||||
if err := ms.extractFile(file, dstPath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractFile 解压单个文件
|
||||
func (ms *MigrationService) extractFile(file *zip.File, dstPath string) error {
|
||||
// 打开zip中的文件
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
// 创建目标文件
|
||||
dstFile, err := os.OpenFile(dstPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, file.FileInfo().Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
// 复制文件内容
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
return err
|
||||
}
|
||||
|
||||
// isDirectoryEmpty 检查目录是否为空
|
||||
func (ms *MigrationService) isDirectoryEmpty(dirPath string) (bool, error) {
|
||||
f, err := os.Open(dirPath)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// 尝试读取一个条目
|
||||
_, err = f.Readdir(1)
|
||||
if err == io.EOF {
|
||||
// 目录为空
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 目录不为空
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// isSubDirectory 检查target是否是parent的子目录
|
||||
func (ms *MigrationService) isSubDirectory(parent, target string) bool {
|
||||
// 确保路径以分隔符结尾,以避免误判
|
||||
parent = filepath.Clean(parent) + string(filepath.Separator)
|
||||
target = filepath.Clean(target) + string(filepath.Separator)
|
||||
|
||||
// 检查target是否以parent开头
|
||||
return len(target) > len(parent) && target[:len(parent)] == parent
|
||||
}
|
||||
|
||||
// calculateDirectorySize 计算目录大小和文件数
|
||||
func (ms *MigrationService) calculateDirectorySize(ctx context.Context, dirPath string) (int, int64, error) {
|
||||
var totalFiles int
|
||||
var totalBytes int64
|
||||
|
||||
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
totalFiles++
|
||||
totalBytes += info.Size()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
return totalFiles, totalBytes, err
|
||||
}
|
||||
|
||||
// CancelMigration 取消迁移
|
||||
func (ms *MigrationService) CancelMigration() error {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
if ms.cancelFunc != nil {
|
||||
ms.cancelFunc()
|
||||
ms.logger.Info("Migration: Cancellation requested")
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("no active migration to cancel")
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
func (ms *MigrationService) ServiceShutdown() error {
|
||||
ms.logger.Info("Migration: Service is shutting down...")
|
||||
|
||||
// 取消正在进行的迁移
|
||||
if err := ms.CancelMigration(); err != nil {
|
||||
ms.logger.Debug("Migration: No active migration to cancel during shutdown")
|
||||
}
|
||||
|
||||
ms.logger.Info("Migration: Service shutdown completed")
|
||||
return nil
|
||||
}
|
@@ -9,12 +9,13 @@ import (
|
||||
|
||||
// ServiceManager 服务管理器,负责协调各个服务
|
||||
type ServiceManager struct {
|
||||
configService *ConfigService
|
||||
documentService *DocumentService
|
||||
systemService *SystemService
|
||||
hotkeyService *HotkeyService
|
||||
dialogService *DialogService
|
||||
logger *log.LoggerService
|
||||
configService *ConfigService
|
||||
documentService *DocumentService
|
||||
migrationService *MigrationService
|
||||
systemService *SystemService
|
||||
hotkeyService *HotkeyService
|
||||
dialogService *DialogService
|
||||
logger *log.LoggerService
|
||||
}
|
||||
|
||||
// NewServiceManager 创建新的服务管理器实例
|
||||
@@ -25,6 +26,9 @@ func NewServiceManager() *ServiceManager {
|
||||
// 初始化配置服务 - 使用固定配置(当前目录下的 config/config.yaml)
|
||||
configService := NewConfigService(logger)
|
||||
|
||||
// 初始化迁移服务
|
||||
migrationService := NewMigrationService(logger)
|
||||
|
||||
// 初始化文档服务
|
||||
documentService := NewDocumentService(configService, logger)
|
||||
|
||||
@@ -46,6 +50,15 @@ func NewServiceManager() *ServiceManager {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 设置数据路径变更监听
|
||||
err = configService.SetDataPathChangeCallback(func(oldPath, newPath string) error {
|
||||
return documentService.OnDataPathChanged(oldPath, newPath)
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("Failed to set data path change callback", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 初始化文档服务
|
||||
err = documentService.Initialize()
|
||||
if err != nil {
|
||||
@@ -54,12 +67,13 @@ func NewServiceManager() *ServiceManager {
|
||||
}
|
||||
|
||||
return &ServiceManager{
|
||||
configService: configService,
|
||||
documentService: documentService,
|
||||
systemService: systemService,
|
||||
hotkeyService: hotkeyService,
|
||||
dialogService: dialogService,
|
||||
logger: logger,
|
||||
configService: configService,
|
||||
documentService: documentService,
|
||||
migrationService: migrationService,
|
||||
systemService: systemService,
|
||||
hotkeyService: hotkeyService,
|
||||
dialogService: dialogService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +82,7 @@ func (sm *ServiceManager) GetServices() []application.Service {
|
||||
return []application.Service{
|
||||
application.NewService(sm.configService),
|
||||
application.NewService(sm.documentService),
|
||||
application.NewService(sm.migrationService),
|
||||
application.NewService(sm.systemService),
|
||||
application.NewService(sm.hotkeyService),
|
||||
application.NewService(sm.dialogService),
|
||||
@@ -78,3 +93,8 @@ func (sm *ServiceManager) GetServices() []application.Service {
|
||||
func (sm *ServiceManager) GetHotkeyService() *HotkeyService {
|
||||
return sm.hotkeyService
|
||||
}
|
||||
|
||||
// GetDialogService 获取对话框服务实例
|
||||
func (sm *ServiceManager) GetDialogService() *DialogService {
|
||||
return sm.dialogService
|
||||
}
|
||||
|
Reference in New Issue
Block a user