✨ Improved settings
This commit is contained in:
@@ -229,21 +229,48 @@ func (cs *ConfigService) Get(key string) interface{} {
|
||||
return cs.viper.Get(key)
|
||||
}
|
||||
|
||||
// ResetConfig 重置为默认配置
|
||||
func (cs *ConfigService) ResetConfig() error {
|
||||
// ResetConfig 强制重置所有配置为默认值
|
||||
func (cs *ConfigService) ResetConfig() {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
|
||||
// 重新设置默认值
|
||||
setDefaults(cs.viper)
|
||||
defaultConfig := models.NewDefaultAppConfig()
|
||||
|
||||
// 使用 WriteConfig 写入配置文件(会触发文件监听)
|
||||
// 通用设置 - 批量设置到viper中
|
||||
cs.viper.Set("general.always_on_top", defaultConfig.General.AlwaysOnTop)
|
||||
cs.viper.Set("general.data_path", defaultConfig.General.DataPath)
|
||||
cs.viper.Set("general.enable_global_hotkey", defaultConfig.General.EnableGlobalHotkey)
|
||||
cs.viper.Set("general.global_hotkey.ctrl", defaultConfig.General.GlobalHotkey.Ctrl)
|
||||
cs.viper.Set("general.global_hotkey.shift", defaultConfig.General.GlobalHotkey.Shift)
|
||||
cs.viper.Set("general.global_hotkey.alt", defaultConfig.General.GlobalHotkey.Alt)
|
||||
cs.viper.Set("general.global_hotkey.win", defaultConfig.General.GlobalHotkey.Win)
|
||||
cs.viper.Set("general.global_hotkey.key", defaultConfig.General.GlobalHotkey.Key)
|
||||
|
||||
// 编辑设置 - 批量设置到viper中
|
||||
cs.viper.Set("editing.font_size", defaultConfig.Editing.FontSize)
|
||||
cs.viper.Set("editing.font_family", defaultConfig.Editing.FontFamily)
|
||||
cs.viper.Set("editing.font_weight", defaultConfig.Editing.FontWeight)
|
||||
cs.viper.Set("editing.line_height", defaultConfig.Editing.LineHeight)
|
||||
cs.viper.Set("editing.enable_tab_indent", defaultConfig.Editing.EnableTabIndent)
|
||||
cs.viper.Set("editing.tab_size", defaultConfig.Editing.TabSize)
|
||||
cs.viper.Set("editing.tab_type", defaultConfig.Editing.TabType)
|
||||
cs.viper.Set("editing.auto_save_delay", defaultConfig.Editing.AutoSaveDelay)
|
||||
|
||||
// 外观设置 - 批量设置到viper中
|
||||
cs.viper.Set("appearance.language", defaultConfig.Appearance.Language)
|
||||
|
||||
// 元数据 - 批量设置到viper中
|
||||
cs.viper.Set("metadata.version", defaultConfig.Metadata.Version)
|
||||
cs.viper.Set("metadata.last_updated", time.Now())
|
||||
|
||||
// 一次性写入配置文件,触发配置变更通知
|
||||
if err := cs.viper.WriteConfig(); err != nil {
|
||||
return &ConfigError{Operation: "reset_config", Err: err}
|
||||
cs.logger.Error("Config: Failed to write config during reset", "error", err)
|
||||
} else {
|
||||
cs.logger.Info("Config: All settings have been reset to defaults")
|
||||
// 手动触发配置变更检查,确保通知系统能感知到变更
|
||||
cs.notificationService.CheckConfigChanges()
|
||||
}
|
||||
|
||||
cs.logger.Info("Config: Successfully reset to default configuration")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetHotkeyChangeCallback 设置热键配置变更回调
|
||||
|
156
internal/services/http_service.go
Normal file
156
internal/services/http_service.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// HTTPService HTTP 服务
|
||||
type HTTPService struct {
|
||||
logger *log.LoggerService
|
||||
server *http.Server
|
||||
wsService *WebSocketService
|
||||
}
|
||||
|
||||
// NewHTTPService 创建 HTTP 服务
|
||||
func NewHTTPService(logger *log.LoggerService, wsService *WebSocketService) *HTTPService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
return &HTTPService{
|
||||
logger: logger,
|
||||
wsService: wsService,
|
||||
}
|
||||
}
|
||||
|
||||
// StartServer 启动 HTTP 服务器
|
||||
func (hs *HTTPService) StartServer(port string) error {
|
||||
// 设置 Gin 为发布模式
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
|
||||
// 创建 Gin 路由器
|
||||
router := gin.New()
|
||||
|
||||
// 添加中间件
|
||||
router.Use(gin.Recovery())
|
||||
router.Use(hs.corsMiddleware())
|
||||
|
||||
// 设置路由
|
||||
hs.setupRoutes(router)
|
||||
|
||||
// 创建 HTTP 服务器
|
||||
hs.server = &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: router,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20, // 1MB
|
||||
}
|
||||
|
||||
hs.logger.Info("HTTP: Starting server", "port", port)
|
||||
|
||||
// 启动服务器
|
||||
go func() {
|
||||
if err := hs.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
hs.logger.Error("HTTP: Server failed to start", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupRoutes 设置路由
|
||||
func (hs *HTTPService) setupRoutes(router *gin.Engine) {
|
||||
// WebSocket 端点
|
||||
router.GET("/ws/migration", hs.handleWebSocket)
|
||||
|
||||
// API 端点组
|
||||
api := router.Group("/api")
|
||||
{
|
||||
api.GET("/health", hs.handleHealth)
|
||||
api.GET("/ws/clients", hs.handleWSClients)
|
||||
}
|
||||
}
|
||||
|
||||
// handleWebSocket 处理 WebSocket 连接
|
||||
func (hs *HTTPService) handleWebSocket(c *gin.Context) {
|
||||
if hs.wsService == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "WebSocket service not available"})
|
||||
return
|
||||
}
|
||||
|
||||
hs.wsService.HandleUpgrade(c.Writer, c.Request)
|
||||
}
|
||||
|
||||
// handleHealth 健康检查端点
|
||||
func (hs *HTTPService) handleHealth(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().Unix(),
|
||||
"service": "voidraft-http",
|
||||
})
|
||||
}
|
||||
|
||||
// handleWSClients 获取 WebSocket 客户端数量
|
||||
func (hs *HTTPService) handleWSClients(c *gin.Context) {
|
||||
if hs.wsService == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "WebSocket service not available"})
|
||||
return
|
||||
}
|
||||
|
||||
count := hs.wsService.GetConnectedClientsCount()
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"connected_clients": count,
|
||||
})
|
||||
}
|
||||
|
||||
// corsMiddleware CORS 中间件
|
||||
func (hs *HTTPService) corsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// StopServer 停止 HTTP 服务器
|
||||
func (hs *HTTPService) StopServer() error {
|
||||
if hs.server == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
hs.logger.Info("HTTP: Stopping server...")
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
return hs.server.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
func (hs *HTTPService) ServiceShutdown() error {
|
||||
hs.logger.Info("HTTP: Service is shutting down...")
|
||||
|
||||
if err := hs.StopServer(); err != nil {
|
||||
hs.logger.Error("HTTP: Failed to stop server", "error", err)
|
||||
return err
|
||||
}
|
||||
|
||||
hs.logger.Info("HTTP: Service shutdown completed")
|
||||
return nil
|
||||
}
|
@@ -3,7 +3,6 @@ package services
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -19,40 +18,26 @@ import (
|
||||
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"` // 估计剩余时间
|
||||
Status MigrationStatus `json:"status"` // 迁移状态
|
||||
Progress float64 `json:"progress"` // 进度百分比 (0-100)
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
}
|
||||
|
||||
// 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
|
||||
logger *log.LoggerService
|
||||
mu sync.RWMutex
|
||||
currentProgress MigrationProgress
|
||||
cancelFunc context.CancelFunc
|
||||
ctx context.Context
|
||||
progressBroadcaster func(MigrationProgress) // WebSocket广播函数
|
||||
}
|
||||
|
||||
// NewMigrationService 创建迁移服务
|
||||
@@ -64,18 +49,12 @@ func NewMigrationService(logger *log.LoggerService) *MigrationService {
|
||||
return &MigrationService{
|
||||
logger: logger,
|
||||
currentProgress: MigrationProgress{
|
||||
Status: MigrationStatusIdle,
|
||||
Status: MigrationStatusCompleted, // 初始状态为完成
|
||||
Progress: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
@@ -83,15 +62,15 @@ func (ms *MigrationService) GetProgress() MigrationProgress {
|
||||
return ms.currentProgress
|
||||
}
|
||||
|
||||
// updateProgress 更新进度并触发回调
|
||||
// updateProgress 更新进度
|
||||
func (ms *MigrationService) updateProgress(progress MigrationProgress) {
|
||||
ms.mu.Lock()
|
||||
ms.currentProgress = progress
|
||||
callback := ms.progressCallback
|
||||
ms.mu.Unlock()
|
||||
|
||||
if callback != nil {
|
||||
callback(progress)
|
||||
// 通过WebSocket广播进度
|
||||
if ms.progressBroadcaster != nil {
|
||||
ms.progressBroadcaster(progress)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,22 +90,18 @@ func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
|
||||
ms.mu.Unlock()
|
||||
}()
|
||||
|
||||
ms.logger.Info("Migration: Starting directory migration",
|
||||
"from", srcPath,
|
||||
"to", dstPath)
|
||||
ms.logger.Info("Migration: Starting directory migration", "from", srcPath, "to", dstPath)
|
||||
|
||||
// 初始化进度
|
||||
progress := MigrationProgress{
|
||||
Status: MigrationStatusPreparing,
|
||||
Message: "Preparing migration...",
|
||||
StartTime: time.Now(),
|
||||
Status: MigrationStatusMigrating,
|
||||
Progress: 0,
|
||||
}
|
||||
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
|
||||
@@ -137,69 +112,38 @@ func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
|
||||
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"
|
||||
progress.Error = "Target path cannot be a subdirectory of source path"
|
||||
ms.updateProgress(progress)
|
||||
return fmt.Errorf("target path cannot be a subdirectory of source path: src=%s, dst=%s", srcAbs, dstAbs)
|
||||
return fmt.Errorf("target path cannot be a subdirectory of source path")
|
||||
}
|
||||
|
||||
// 计算目录大小(用于显示进度)
|
||||
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)
|
||||
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)
|
||||
}
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = err.Error()
|
||||
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)
|
||||
|
||||
ms.logger.Info("Migration: Directory migration completed", "from", srcPath, "to", dstPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
// atomicMove 原子移动目录 - 使用压缩-移动-解压的方式
|
||||
// atomicMove 原子移动目录
|
||||
func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
|
||||
// 检查是否取消
|
||||
select {
|
||||
@@ -211,125 +155,98 @@ func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath str
|
||||
// 确保目标目录的父目录存在
|
||||
dstParent := filepath.Dir(dstPath)
|
||||
if err := os.MkdirAll(dstParent, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target parent directory: %v", err)
|
||||
return fmt.Errorf("Failed to create target parent directory")
|
||||
}
|
||||
|
||||
// 检查目标路径情况
|
||||
if stat, err := os.Stat(dstPath); err == nil {
|
||||
if !stat.IsDir() {
|
||||
return fmt.Errorf("Target path exists but is not a directory: %s", dstPath)
|
||||
return fmt.Errorf("Target path exists but is not a directory")
|
||||
}
|
||||
|
||||
// 检查目录是否为空
|
||||
isEmpty, err := ms.isDirectoryEmpty(dstPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to check if target directory is empty: %v", err)
|
||||
return fmt.Errorf("Failed to check target directory")
|
||||
}
|
||||
|
||||
if !isEmpty {
|
||||
return fmt.Errorf("Target directory is not empty: %s", dstPath)
|
||||
return fmt.Errorf("Target directory is not empty")
|
||||
}
|
||||
|
||||
// 目录存在但为空,可以继续迁移
|
||||
ms.logger.Info("Migration: Target directory exists but is empty, proceeding with migration")
|
||||
}
|
||||
|
||||
// 尝试直接重命名(如果在同一分区,这会很快)
|
||||
progress.Message = "Attempting fast move..."
|
||||
progress.Progress = 20
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := os.Rename(srcPath, dstPath); err == nil {
|
||||
// 重命名成功,这是最快的方式
|
||||
ms.logger.Info("Migration: Fast rename successful")
|
||||
return nil
|
||||
} else {
|
||||
ms.logger.Info("Migration: Fast rename failed, using copy method", "error", err)
|
||||
}
|
||||
|
||||
// 重命名失败(可能跨分区),使用原子压缩迁移
|
||||
progress.Message = "Starting atomic compress migration..."
|
||||
// 重命名失败,使用压缩迁移
|
||||
progress.Progress = 30
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
return ms.atomicCompressMove(ctx, srcPath, dstPath, progress)
|
||||
}
|
||||
|
||||
// atomicCompressMove 原子压缩迁移 - 压缩、移动、解压、清理
|
||||
// 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)
|
||||
ms.logger.Error("Migration: Failed to clean up temporary zip file", "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 第一步: 压缩源目录
|
||||
progress.Message = "Compressing source directory..."
|
||||
progress.Progress = 10
|
||||
// 压缩源目录
|
||||
progress.Progress = 40
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := ms.compressDirectory(ctx, srcPath, tempZipFile, progress); err != nil {
|
||||
return fmt.Errorf("Failed to compress source directory: %v", err)
|
||||
if err := ms.compressDirectory(ctx, srcPath, tempZipFile); err != nil {
|
||||
return fmt.Errorf("Failed to compress source directory")
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
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)
|
||||
if err := ms.extractToDirectory(ctx, tempZipFile, dstPath); err != nil {
|
||||
return fmt.Errorf("Failed to extract to target location")
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
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文件
|
||||
func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFile string) error {
|
||||
zipWriter, err := os.Create(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create zip file: %v", err)
|
||||
return fmt.Errorf("Failed to create temporary file")
|
||||
}
|
||||
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
|
||||
@@ -342,31 +259,22 @@ func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFi
|
||||
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
|
||||
@@ -374,13 +282,11 @@ func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFi
|
||||
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 {
|
||||
@@ -399,20 +305,17 @@ func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFi
|
||||
}
|
||||
|
||||
// extractToDirectory 从zip文件解压到目录
|
||||
func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dstDir string, progress *MigrationProgress) error {
|
||||
// 打开zip文件
|
||||
func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dstDir string) error {
|
||||
reader, err := zip.OpenReader(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to open zip file: %v", err)
|
||||
return fmt.Errorf("Failed to open temporary file")
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// 确保目标目录存在
|
||||
if err := os.MkdirAll(dstDir, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target directory: %v", err)
|
||||
return fmt.Errorf("Failed to create target directory")
|
||||
}
|
||||
|
||||
// 解压每个文件
|
||||
for _, file := range reader.File {
|
||||
// 检查是否取消
|
||||
select {
|
||||
@@ -421,19 +324,13 @@ func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dst
|
||||
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)
|
||||
return fmt.Errorf("Invalid file path in archive")
|
||||
}
|
||||
|
||||
// 处理目录
|
||||
if file.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(dstPath, file.FileInfo().Mode()); err != nil {
|
||||
return err
|
||||
@@ -441,12 +338,10 @@ func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dst
|
||||
continue
|
||||
}
|
||||
|
||||
// 确保父目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解压文件
|
||||
if err := ms.extractFile(file, dstPath); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -457,21 +352,18 @@ func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dst
|
||||
|
||||
// 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
|
||||
}
|
||||
@@ -484,56 +376,23 @@ func (ms *MigrationService) isDirectoryEmpty(dirPath string) (bool, error) {
|
||||
}
|
||||
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()
|
||||
@@ -545,18 +404,22 @@ func (ms *MigrationService) CancelMigration() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("no active migration to cancel")
|
||||
return fmt.Errorf("No active migration to cancel")
|
||||
}
|
||||
|
||||
// SetProgressBroadcaster 设置进度广播函数
|
||||
func (ms *MigrationService) SetProgressBroadcaster(broadcaster func(MigrationProgress)) {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
ms.progressBroadcaster = broadcaster
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
@@ -15,6 +15,8 @@ type ServiceManager struct {
|
||||
systemService *SystemService
|
||||
hotkeyService *HotkeyService
|
||||
dialogService *DialogService
|
||||
websocketService *WebSocketService
|
||||
httpService *HTTPService
|
||||
logger *log.LoggerService
|
||||
}
|
||||
|
||||
@@ -41,8 +43,26 @@ func NewServiceManager() *ServiceManager {
|
||||
// 初始化对话服务
|
||||
dialogService := NewDialogService(logger)
|
||||
|
||||
// 初始化 WebSocket 服务
|
||||
websocketService := NewWebSocketService(logger)
|
||||
|
||||
// 初始化 HTTP 服务
|
||||
httpService := NewHTTPService(logger, websocketService)
|
||||
|
||||
// 设置迁移服务的WebSocket广播
|
||||
migrationService.SetProgressBroadcaster(func(progress MigrationProgress) {
|
||||
websocketService.BroadcastMigrationProgress(progress)
|
||||
})
|
||||
|
||||
// 启动 HTTP 服务器
|
||||
err := httpService.StartServer("8899")
|
||||
if err != nil {
|
||||
logger.Error("Failed to start HTTP server", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 使用新的配置通知系统设置热键配置变更监听
|
||||
err := configService.SetHotkeyChangeCallback(func(enable bool, hotkey *models.HotkeyCombo) error {
|
||||
err = configService.SetHotkeyChangeCallback(func(enable bool, hotkey *models.HotkeyCombo) error {
|
||||
return hotkeyService.UpdateHotkey(enable, hotkey)
|
||||
})
|
||||
if err != nil {
|
||||
@@ -50,7 +70,7 @@ func NewServiceManager() *ServiceManager {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 设置数据路径变更监听
|
||||
// 设置数据路径变更监听,处理配置重置和路径变更
|
||||
err = configService.SetDataPathChangeCallback(func(oldPath, newPath string) error {
|
||||
return documentService.OnDataPathChanged(oldPath, newPath)
|
||||
})
|
||||
@@ -73,6 +93,8 @@ func NewServiceManager() *ServiceManager {
|
||||
systemService: systemService,
|
||||
hotkeyService: hotkeyService,
|
||||
dialogService: dialogService,
|
||||
websocketService: websocketService,
|
||||
httpService: httpService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
159
internal/services/websocket_service.go
Normal file
159
internal/services/websocket_service.go
Normal file
@@ -0,0 +1,159 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/lxzan/gws"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// WebSocketService WebSocket 服务
|
||||
type WebSocketService struct {
|
||||
logger *log.LoggerService
|
||||
upgrader *gws.Upgrader
|
||||
clients map[*gws.Conn]bool
|
||||
clientsMu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewWebSocketService 创建 WebSocket 服务
|
||||
func NewWebSocketService(logger *log.LoggerService) *WebSocketService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
ws := &WebSocketService{
|
||||
logger: logger,
|
||||
clients: make(map[*gws.Conn]bool),
|
||||
}
|
||||
|
||||
// 创建 WebSocket 升级器
|
||||
ws.upgrader = gws.NewUpgrader(&WebSocketHandler{service: ws}, &gws.ServerOption{
|
||||
ParallelEnabled: true,
|
||||
Recovery: gws.Recovery,
|
||||
PermessageDeflate: gws.PermessageDeflate{Enabled: true},
|
||||
})
|
||||
|
||||
return ws
|
||||
}
|
||||
|
||||
// WebSocketHandler WebSocket 事件处理器
|
||||
type WebSocketHandler struct {
|
||||
service *WebSocketService
|
||||
}
|
||||
|
||||
// OnOpen 连接建立时调用
|
||||
func (h *WebSocketHandler) OnOpen(socket *gws.Conn) {
|
||||
h.service.logger.Info("WebSocket: Client connected")
|
||||
|
||||
h.service.clientsMu.Lock()
|
||||
h.service.clients[socket] = true
|
||||
h.service.clientsMu.Unlock()
|
||||
}
|
||||
|
||||
// OnClose 连接关闭时调用
|
||||
func (h *WebSocketHandler) OnClose(socket *gws.Conn, err error) {
|
||||
h.service.logger.Info("WebSocket: Client disconnected", "error", err)
|
||||
|
||||
h.service.clientsMu.Lock()
|
||||
delete(h.service.clients, socket)
|
||||
h.service.clientsMu.Unlock()
|
||||
}
|
||||
|
||||
// OnPing 收到 Ping 时调用
|
||||
func (h *WebSocketHandler) OnPing(socket *gws.Conn, payload []byte) {
|
||||
_ = socket.WritePong(nil)
|
||||
}
|
||||
|
||||
// OnPong 收到 Pong 时调用
|
||||
func (h *WebSocketHandler) OnPong(socket *gws.Conn, payload []byte) {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
// OnMessage 收到消息时调用
|
||||
func (h *WebSocketHandler) OnMessage(socket *gws.Conn, message *gws.Message) {
|
||||
defer message.Close()
|
||||
|
||||
h.service.logger.Debug("WebSocket: Received message", "message", string(message.Bytes()))
|
||||
|
||||
}
|
||||
|
||||
// HandleUpgrade 处理 WebSocket 升级请求
|
||||
func (ws *WebSocketService) HandleUpgrade(w http.ResponseWriter, r *http.Request) {
|
||||
socket, err := ws.upgrader.Upgrade(w, r)
|
||||
if err != nil {
|
||||
ws.logger.Error("WebSocket: Failed to upgrade connection", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 启动读取循环(必须在 goroutine 中运行以防止阻塞)
|
||||
go func() {
|
||||
socket.ReadLoop()
|
||||
}()
|
||||
}
|
||||
|
||||
// BroadcastMessage 广播消息给所有连接的客户端
|
||||
func (ws *WebSocketService) BroadcastMessage(messageType string, data interface{}) {
|
||||
message := map[string]interface{}{
|
||||
"type": messageType,
|
||||
"data": data,
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(message)
|
||||
if err != nil {
|
||||
ws.logger.Error("WebSocket: Failed to marshal message", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
ws.clientsMu.RLock()
|
||||
clients := make([]*gws.Conn, 0, len(ws.clients))
|
||||
for client := range ws.clients {
|
||||
clients = append(clients, client)
|
||||
}
|
||||
ws.clientsMu.RUnlock()
|
||||
|
||||
// 使用广播器进行高效广播
|
||||
broadcaster := gws.NewBroadcaster(gws.OpcodeText, jsonData)
|
||||
defer broadcaster.Close()
|
||||
|
||||
for _, client := range clients {
|
||||
if err := broadcaster.Broadcast(client); err != nil {
|
||||
ws.logger.Error("WebSocket: Failed to broadcast to client", "error", err)
|
||||
// 清理失效的连接
|
||||
ws.clientsMu.Lock()
|
||||
delete(ws.clients, client)
|
||||
ws.clientsMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
ws.logger.Debug("WebSocket: Broadcasted message", "type", messageType, "clients", len(clients))
|
||||
}
|
||||
|
||||
// BroadcastMigrationProgress 广播迁移进度
|
||||
func (ws *WebSocketService) BroadcastMigrationProgress(progress MigrationProgress) {
|
||||
ws.BroadcastMessage("migration_progress", progress)
|
||||
}
|
||||
|
||||
// GetConnectedClientsCount 获取连接的客户端数量
|
||||
func (ws *WebSocketService) GetConnectedClientsCount() int {
|
||||
ws.clientsMu.RLock()
|
||||
defer ws.clientsMu.RUnlock()
|
||||
return len(ws.clients)
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
func (ws *WebSocketService) ServiceShutdown() error {
|
||||
ws.logger.Info("WebSocket: Service is shutting down...")
|
||||
|
||||
// 关闭所有客户端连接
|
||||
ws.clientsMu.Lock()
|
||||
for client := range ws.clients {
|
||||
_ = client.WriteClose(1000, []byte("Server shutting down"))
|
||||
}
|
||||
ws.clients = make(map[*gws.Conn]bool)
|
||||
ws.clientsMu.Unlock()
|
||||
|
||||
ws.logger.Info("WebSocket: Service shutdown completed")
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user