refactor server command (#206)
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sjzar/chatlog/pkg/config"
|
||||
)
|
||||
|
||||
const (
|
||||
AppName = "chatlog"
|
||||
ServerConfigName = "chatlog-server"
|
||||
EnvPrefix = "CHATLOG"
|
||||
EnvConfigDir = "CHATLOG_DIR"
|
||||
)
|
||||
|
||||
// LoadTUIConfig 加载 TUI 配置
|
||||
func LoadTUIConfig(configPath string) (*TUIConfig, *config.Manager, error) {
|
||||
|
||||
if configPath == "" {
|
||||
configPath = os.Getenv(EnvConfigDir)
|
||||
}
|
||||
|
||||
tcm, err := config.New(AppName, configPath, "", "", true)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("load tui config failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
conf := &TUIConfig{}
|
||||
config.SetDefaults(tcm.Viper, conf, TUIDefaults)
|
||||
|
||||
if err := tcm.Load(conf); err != nil {
|
||||
log.Error().Err(err).Msg("load tui config failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
conf.ConfigDir = tcm.Path
|
||||
return conf, tcm, nil
|
||||
}
|
||||
|
||||
// LoadServiceConfig 加载服务配置
|
||||
func LoadServiceConfig(configPath string, cmdConf map[string]any) (*ServerConfig, *config.Manager, error) {
|
||||
|
||||
if configPath == "" {
|
||||
configPath = os.Getenv(EnvConfigDir)
|
||||
}
|
||||
|
||||
scm, err := config.New(AppName, configPath, ServerConfigName, EnvPrefix, false)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("load server config failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
conf := &ServerConfig{}
|
||||
config.SetDefaults(scm.Viper, conf, ServerDefaults)
|
||||
|
||||
// Load cmd Conf
|
||||
for key, value := range cmdConf {
|
||||
scm.SetConfig(key, value)
|
||||
}
|
||||
|
||||
if err := scm.Load(conf); err != nil {
|
||||
log.Error().Err(err).Msg("load server config failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// Load Data Dir config
|
||||
if len(conf.DataDir) != 0 && len(conf.DataKey) == 0 {
|
||||
if b, err := os.ReadFile(filepath.Join(conf.DataDir, "chatlog.json")); err == nil {
|
||||
var pconf map[string]any
|
||||
if err := json.Unmarshal(b, &pconf); err == nil {
|
||||
for key, value := range pconf {
|
||||
if !DataDirConfigs[key] {
|
||||
continue
|
||||
}
|
||||
scm.SetConfig(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := scm.Load(conf); err != nil {
|
||||
log.Error().Err(err).Msg("reload server config failed")
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return conf, scm, nil
|
||||
}
|
||||
|
||||
var DataDirConfigs = map[string]bool{
|
||||
"type": true,
|
||||
"platform": true,
|
||||
"version": true,
|
||||
"full_version": true,
|
||||
"data_key": true,
|
||||
"img_key": true,
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package conf
|
||||
|
||||
const (
|
||||
DefalutHTTPAddr = "0.0.0.0:5030"
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
Type string `mapstructure:"type"`
|
||||
Platform string `mapstructure:"platform"`
|
||||
Version int `mapstructure:"version"`
|
||||
FullVersion string `mapstructure:"full_version"`
|
||||
DataDir string `mapstructure:"data_dir"`
|
||||
DataKey string `mapstructure:"data_key"`
|
||||
ImgKey string `mapstructure:"img_key"`
|
||||
WorkDir string `mapstructure:"work_dir"`
|
||||
HTTPAddr string `mapstructure:"http_addr"`
|
||||
AutoDecrypt bool `mapstructure:"auto_decrypt"`
|
||||
}
|
||||
|
||||
var ServerDefaults = map[string]any{}
|
||||
|
||||
func (c *ServerConfig) GetDataDir() string {
|
||||
return c.DataDir
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetWorkDir() string {
|
||||
return c.WorkDir
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetPlatform() string {
|
||||
return c.Platform
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetVersion() int {
|
||||
return c.Version
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetDataKey() string {
|
||||
return c.DataKey
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetImgKey() string {
|
||||
return c.ImgKey
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetAutoDecrypt() bool {
|
||||
return c.AutoDecrypt
|
||||
}
|
||||
|
||||
func (c *ServerConfig) GetHTTPAddr() string {
|
||||
if c.HTTPAddr == "" {
|
||||
c.HTTPAddr = DefalutHTTPAddr
|
||||
}
|
||||
return c.HTTPAddr
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/sjzar/chatlog/pkg/config"
|
||||
)
|
||||
|
||||
const (
|
||||
ConfigName = "chatlog"
|
||||
ConfigType = "json"
|
||||
EnvConfigDir = "CHATLOG_DIR"
|
||||
)
|
||||
|
||||
// Service 配置服务
|
||||
type Service struct {
|
||||
configPath string
|
||||
config *Config
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewService 创建配置服务
|
||||
func NewService(configPath string) (*Service, error) {
|
||||
|
||||
service := &Service{
|
||||
configPath: configPath,
|
||||
}
|
||||
|
||||
if err := service.Load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return service, nil
|
||||
}
|
||||
|
||||
// Load 加载配置
|
||||
func (s *Service) Load() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
configPath := s.configPath
|
||||
if configPath == "" {
|
||||
configPath = os.Getenv(EnvConfigDir)
|
||||
}
|
||||
if err := config.Init(ConfigName, ConfigType, configPath); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
conf := &Config{}
|
||||
if err := config.Load(conf); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
conf.ConfigDir = config.ConfigPath
|
||||
s.config = conf
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetConfig 获取配置副本
|
||||
func (s *Service) GetConfig() *Config {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
// 返回配置副本
|
||||
configCopy := *s.config
|
||||
return &configCopy
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
package conf
|
||||
|
||||
import "github.com/sjzar/chatlog/pkg/config"
|
||||
|
||||
type Config struct {
|
||||
type TUIConfig struct {
|
||||
ConfigDir string `mapstructure:"-"`
|
||||
LastAccount string `mapstructure:"last_account" json:"last_account"`
|
||||
History []ProcessConfig `mapstructure:"history" json:"history"`
|
||||
}
|
||||
|
||||
var TUIDefaults = map[string]any{}
|
||||
|
||||
type ProcessConfig struct {
|
||||
Type string `mapstructure:"type" json:"type"`
|
||||
Account string `mapstructure:"account" json:"account"`
|
||||
@@ -30,33 +30,10 @@ type File struct {
|
||||
Size int64 `mapstructure:"size" json:"size"`
|
||||
}
|
||||
|
||||
func (c *Config) ParseHistory() map[string]ProcessConfig {
|
||||
func (c *TUIConfig) ParseHistory() map[string]ProcessConfig {
|
||||
m := make(map[string]ProcessConfig)
|
||||
for _, v := range c.History {
|
||||
m[v.Account] = v
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (c *Config) UpdateHistory(account string, conf ProcessConfig) error {
|
||||
if c.History == nil {
|
||||
c.History = make([]ProcessConfig, 0)
|
||||
}
|
||||
if len(c.History) == 0 {
|
||||
c.History = append(c.History, conf)
|
||||
} else {
|
||||
isFind := false
|
||||
for i, v := range c.History {
|
||||
if v.Account == account {
|
||||
isFind = true
|
||||
c.History[i] = conf
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isFind {
|
||||
c.History = append(c.History, conf)
|
||||
}
|
||||
}
|
||||
config.SetConfig("last_account", account)
|
||||
return config.SetConfig("history", c.History)
|
||||
}
|
||||
@@ -1,18 +1,28 @@
|
||||
package ctx
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/conf"
|
||||
"github.com/sjzar/chatlog/internal/wechat"
|
||||
"github.com/sjzar/chatlog/pkg/config"
|
||||
"github.com/sjzar/chatlog/pkg/util"
|
||||
)
|
||||
|
||||
const (
|
||||
DefalutHTTPAddr = "127.0.0.1:5030"
|
||||
)
|
||||
|
||||
// Context is a context for a chatlog.
|
||||
// It is used to store information about the chatlog.
|
||||
type Context struct {
|
||||
conf *conf.Service
|
||||
conf *conf.TUIConfig
|
||||
cm *config.Manager
|
||||
mu sync.RWMutex
|
||||
|
||||
History map[string]conf.ProcessConfig
|
||||
@@ -49,20 +59,26 @@ type Context struct {
|
||||
WeChatInstances []*wechat.Account
|
||||
}
|
||||
|
||||
func New(conf *conf.Service) *Context {
|
||||
func New(configPath string) (*Context, error) {
|
||||
|
||||
conf, tcm, err := conf.LoadTUIConfig(configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctx := &Context{
|
||||
conf: conf,
|
||||
cm: tcm,
|
||||
}
|
||||
|
||||
ctx.loadConfig()
|
||||
|
||||
return ctx
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
func (c *Context) loadConfig() {
|
||||
conf := c.conf.GetConfig()
|
||||
c.History = conf.ParseHistory()
|
||||
c.SwitchHistory(conf.LastAccount)
|
||||
c.History = c.conf.ParseHistory()
|
||||
c.SwitchHistory(c.conf.LastAccount)
|
||||
c.Refresh()
|
||||
}
|
||||
|
||||
@@ -138,9 +154,39 @@ func (c *Context) Refresh() {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Context) GetDataDir() string {
|
||||
return c.DataDir
|
||||
}
|
||||
|
||||
func (c *Context) GetWorkDir() string {
|
||||
return c.WorkDir
|
||||
}
|
||||
|
||||
func (c *Context) GetPlatform() string {
|
||||
return c.Platform
|
||||
}
|
||||
|
||||
func (c *Context) GetVersion() int {
|
||||
return c.Version
|
||||
}
|
||||
|
||||
func (c *Context) GetDataKey() string {
|
||||
return c.DataKey
|
||||
}
|
||||
|
||||
func (c *Context) GetHTTPAddr() string {
|
||||
if c.HTTPAddr == "" {
|
||||
c.HTTPAddr = DefalutHTTPAddr
|
||||
}
|
||||
return c.HTTPAddr
|
||||
}
|
||||
|
||||
func (c *Context) SetHTTPEnabled(enabled bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.HTTPEnabled == enabled {
|
||||
return
|
||||
}
|
||||
c.HTTPEnabled = enabled
|
||||
c.UpdateConfig()
|
||||
}
|
||||
@@ -148,6 +194,9 @@ func (c *Context) SetHTTPEnabled(enabled bool) {
|
||||
func (c *Context) SetHTTPAddr(addr string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.HTTPAddr == addr {
|
||||
return
|
||||
}
|
||||
c.HTTPAddr = addr
|
||||
c.UpdateConfig()
|
||||
}
|
||||
@@ -155,6 +204,9 @@ func (c *Context) SetHTTPAddr(addr string) {
|
||||
func (c *Context) SetWorkDir(dir string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.WorkDir == dir {
|
||||
return
|
||||
}
|
||||
c.WorkDir = dir
|
||||
c.UpdateConfig()
|
||||
c.Refresh()
|
||||
@@ -163,6 +215,9 @@ func (c *Context) SetWorkDir(dir string) {
|
||||
func (c *Context) SetDataDir(dir string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.DataDir == dir {
|
||||
return
|
||||
}
|
||||
c.DataDir = dir
|
||||
c.UpdateConfig()
|
||||
c.Refresh()
|
||||
@@ -171,12 +226,16 @@ func (c *Context) SetDataDir(dir string) {
|
||||
func (c *Context) SetAutoDecrypt(enabled bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.AutoDecrypt == enabled {
|
||||
return
|
||||
}
|
||||
c.AutoDecrypt = enabled
|
||||
c.UpdateConfig()
|
||||
}
|
||||
|
||||
// 更新配置
|
||||
func (c *Context) UpdateConfig() {
|
||||
|
||||
pconf := conf.ProcessConfig{
|
||||
Type: "wechat",
|
||||
Account: c.Account,
|
||||
@@ -190,6 +249,41 @@ func (c *Context) UpdateConfig() {
|
||||
HTTPEnabled: c.HTTPEnabled,
|
||||
HTTPAddr: c.HTTPAddr,
|
||||
}
|
||||
conf := c.conf.GetConfig()
|
||||
conf.UpdateHistory(c.Account, pconf)
|
||||
|
||||
if c.conf.History == nil {
|
||||
c.conf.History = make([]conf.ProcessConfig, 0)
|
||||
}
|
||||
if len(c.conf.History) == 0 {
|
||||
c.conf.History = append(c.conf.History, pconf)
|
||||
} else {
|
||||
isFind := false
|
||||
for i, v := range c.conf.History {
|
||||
if v.Account == c.Account {
|
||||
isFind = true
|
||||
c.conf.History[i] = pconf
|
||||
break
|
||||
}
|
||||
}
|
||||
if !isFind {
|
||||
c.conf.History = append(c.conf.History, pconf)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.cm.SetConfig("last_account", c.Account); err != nil {
|
||||
log.Error().Err(err).Msg("set last_account failed")
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.cm.SetConfig("history", c.conf.History); err != nil {
|
||||
log.Error().Err(err).Msg("set history failed")
|
||||
return
|
||||
}
|
||||
|
||||
if len(pconf.DataDir) != 0 {
|
||||
if b, err := json.Marshal(pconf); err == nil {
|
||||
if err := os.WriteFile(filepath.Join(pconf.DataDir, "chatlog.json"), b, 0644); err != nil {
|
||||
log.Error().Err(err).Msg("save chatlog.json failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,27 +3,42 @@ package database
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/sjzar/chatlog/internal/chatlog/ctx"
|
||||
"github.com/sjzar/chatlog/internal/model"
|
||||
"github.com/sjzar/chatlog/internal/wechatdb"
|
||||
)
|
||||
|
||||
const (
|
||||
StateInit = iota
|
||||
StateDecrypting
|
||||
StateReady
|
||||
StateError
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ctx *ctx.Context
|
||||
db *wechatdb.DB
|
||||
State int
|
||||
StateMsg string
|
||||
conf Config
|
||||
db *wechatdb.DB
|
||||
}
|
||||
|
||||
func NewService(ctx *ctx.Context) *Service {
|
||||
type Config interface {
|
||||
GetWorkDir() string
|
||||
GetPlatform() string
|
||||
GetVersion() int
|
||||
}
|
||||
|
||||
func NewService(conf Config) *Service {
|
||||
return &Service{
|
||||
ctx: ctx,
|
||||
conf: conf,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Start() error {
|
||||
db, err := wechatdb.New(s.ctx.WorkDir, s.ctx.Platform, s.ctx.Version)
|
||||
db, err := wechatdb.New(s.conf.GetWorkDir(), s.conf.GetPlatform(), s.conf.GetVersion())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.SetReady()
|
||||
s.db = db
|
||||
return nil
|
||||
}
|
||||
@@ -32,10 +47,28 @@ func (s *Service) Stop() error {
|
||||
if s.db != nil {
|
||||
s.db.Close()
|
||||
}
|
||||
s.SetInit()
|
||||
s.db = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) SetInit() {
|
||||
s.State = StateInit
|
||||
}
|
||||
|
||||
func (s *Service) SetDecrypting() {
|
||||
s.State = StateDecrypting
|
||||
}
|
||||
|
||||
func (s *Service) SetReady() {
|
||||
s.State = StateReady
|
||||
}
|
||||
|
||||
func (s *Service) SetError(msg string) {
|
||||
s.State = StateError
|
||||
s.StateMsg = msg
|
||||
}
|
||||
|
||||
func (s *Service) GetDB() *wechatdb.DB {
|
||||
return s.db
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/database"
|
||||
)
|
||||
|
||||
func corsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-CSRF-Token")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) checkDBStateMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
switch s.db.State {
|
||||
case database.StateInit:
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "database is not ready"})
|
||||
c.Abort()
|
||||
return
|
||||
case database.StateDecrypting:
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "database is decrypting, please wait"})
|
||||
c.Abort()
|
||||
return
|
||||
case database.StateError:
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "database is error: " + s.db.StateMsg})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@ func (s *Service) initRouter() {
|
||||
router.StaticFS("/static", http.FS(staticDir))
|
||||
router.StaticFileFS("/favicon.ico", "./favicon.ico", http.FS(staticDir))
|
||||
router.StaticFileFS("/", "./index.htm", http.FS(staticDir))
|
||||
router.GET("/health", func(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
})
|
||||
|
||||
// Media
|
||||
router.GET("/image/*key", s.GetImage)
|
||||
@@ -48,7 +51,7 @@ func (s *Service) initRouter() {
|
||||
}
|
||||
|
||||
// API V1 Router
|
||||
api := router.Group("/api/v1")
|
||||
api := router.Group("/api/v1", s.checkDBStateMiddleware())
|
||||
{
|
||||
api.GET("/chatlog", s.GetChatlog)
|
||||
api.GET("/contact", s.GetContacts)
|
||||
@@ -296,7 +299,7 @@ func (s *Service) GetMedia(c *gin.Context, _type string) {
|
||||
var _err error
|
||||
for _, k := range keys {
|
||||
if len(k) != 32 {
|
||||
absolutePath := filepath.Join(s.ctx.DataDir, k)
|
||||
absolutePath := filepath.Join(s.conf.GetDataDir(), k)
|
||||
if _, err := os.Stat(absolutePath); os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
@@ -331,7 +334,7 @@ func (s *Service) GetMedia(c *gin.Context, _type string) {
|
||||
func (s *Service) GetMediaData(c *gin.Context) {
|
||||
relativePath := filepath.Clean(c.Param("path"))
|
||||
|
||||
absolutePath := filepath.Join(s.ctx.DataDir, relativePath)
|
||||
absolutePath := filepath.Join(s.conf.GetDataDir(), relativePath)
|
||||
|
||||
if _, err := os.Stat(absolutePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/sjzar/chatlog/internal/chatlog/ctx"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/database"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/mcp"
|
||||
"github.com/sjzar/chatlog/internal/errors"
|
||||
@@ -14,20 +13,21 @@ import (
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
DefalutHTTPAddr = "127.0.0.1:5030"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ctx *ctx.Context
|
||||
db *database.Service
|
||||
mcp *mcp.Service
|
||||
conf Config
|
||||
db *database.Service
|
||||
mcp *mcp.Service
|
||||
|
||||
router *gin.Engine
|
||||
server *http.Server
|
||||
}
|
||||
|
||||
func NewService(ctx *ctx.Context, db *database.Service, mcp *mcp.Service) *Service {
|
||||
type Config interface {
|
||||
GetHTTPAddr() string
|
||||
GetDataDir() string
|
||||
}
|
||||
|
||||
func NewService(conf Config, db *database.Service, mcp *mcp.Service) *Service {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
router := gin.New()
|
||||
|
||||
@@ -40,11 +40,12 @@ func NewService(ctx *ctx.Context, db *database.Service, mcp *mcp.Service) *Servi
|
||||
router.Use(
|
||||
errors.RecoveryMiddleware(),
|
||||
errors.ErrorHandlerMiddleware(),
|
||||
gin.LoggerWithWriter(log.Logger),
|
||||
gin.LoggerWithWriter(log.Logger, "/health"),
|
||||
corsMiddleware(),
|
||||
)
|
||||
|
||||
s := &Service{
|
||||
ctx: ctx,
|
||||
conf: conf,
|
||||
db: db,
|
||||
mcp: mcp,
|
||||
router: router,
|
||||
@@ -56,12 +57,8 @@ func NewService(ctx *ctx.Context, db *database.Service, mcp *mcp.Service) *Servi
|
||||
|
||||
func (s *Service) Start() error {
|
||||
|
||||
if s.ctx.HTTPAddr == "" {
|
||||
s.ctx.HTTPAddr = DefalutHTTPAddr
|
||||
}
|
||||
|
||||
s.server = &http.Server{
|
||||
Addr: s.ctx.HTTPAddr,
|
||||
Addr: s.conf.GetHTTPAddr(),
|
||||
Handler: s.router,
|
||||
}
|
||||
|
||||
@@ -72,23 +69,19 @@ func (s *Service) Start() error {
|
||||
}
|
||||
}()
|
||||
|
||||
log.Info().Msg("Starting HTTP server on " + s.ctx.HTTPAddr)
|
||||
log.Info().Msg("Starting HTTP server on " + s.conf.GetHTTPAddr())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) ListenAndServe() error {
|
||||
|
||||
if s.ctx.HTTPAddr == "" {
|
||||
s.ctx.HTTPAddr = DefalutHTTPAddr
|
||||
}
|
||||
|
||||
s.server = &http.Server{
|
||||
Addr: s.ctx.HTTPAddr,
|
||||
Addr: s.conf.GetHTTPAddr(),
|
||||
Handler: s.router,
|
||||
}
|
||||
|
||||
log.Info().Msg("Starting HTTP server on " + s.ctx.HTTPAddr)
|
||||
log.Info().Msg("Starting HTTP server on " + s.conf.GetHTTPAddr())
|
||||
return s.server.ListenAndServe()
|
||||
}
|
||||
|
||||
|
||||
+157
-87
@@ -3,7 +3,7 @@ package chatlog
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -14,14 +14,16 @@ import (
|
||||
"github.com/sjzar/chatlog/internal/chatlog/mcp"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/wechat"
|
||||
iwechat "github.com/sjzar/chatlog/internal/wechat"
|
||||
"github.com/sjzar/chatlog/pkg/config"
|
||||
"github.com/sjzar/chatlog/pkg/util"
|
||||
"github.com/sjzar/chatlog/pkg/util/dat2img"
|
||||
)
|
||||
|
||||
// Manager 管理聊天日志应用
|
||||
type Manager struct {
|
||||
conf *conf.Service
|
||||
ctx *ctx.Context
|
||||
ctx *ctx.Context
|
||||
sc *conf.ServerConfig
|
||||
scm *config.Manager
|
||||
|
||||
// Services
|
||||
db *database.Service
|
||||
@@ -33,36 +35,25 @@ type Manager struct {
|
||||
app *App
|
||||
}
|
||||
|
||||
func New(configPath string) (*Manager, error) {
|
||||
|
||||
// 创建配置服务
|
||||
conf, err := conf.NewService(configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 创建应用上下文
|
||||
ctx := ctx.New(conf)
|
||||
|
||||
wechat := wechat.NewService(ctx)
|
||||
|
||||
db := database.NewService(ctx)
|
||||
|
||||
mcp := mcp.NewService(ctx, db)
|
||||
|
||||
http := http.NewService(ctx, db, mcp)
|
||||
|
||||
return &Manager{
|
||||
conf: conf,
|
||||
ctx: ctx,
|
||||
db: db,
|
||||
mcp: mcp,
|
||||
http: http,
|
||||
wechat: wechat,
|
||||
}, nil
|
||||
func New() *Manager {
|
||||
return &Manager{}
|
||||
}
|
||||
|
||||
func (m *Manager) Run() error {
|
||||
func (m *Manager) Run(configPath string) error {
|
||||
|
||||
var err error
|
||||
m.ctx, err = ctx.New(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
m.wechat = wechat.NewService(m.ctx)
|
||||
|
||||
m.db = database.NewService(m.ctx)
|
||||
|
||||
m.mcp = mcp.NewService(m.db)
|
||||
|
||||
m.http = http.NewService(m.ctx, m.db, m.mcp)
|
||||
|
||||
m.ctx.WeChatInstances = m.wechat.GetWeChatInstances()
|
||||
if len(m.ctx.WeChatInstances) >= 1 {
|
||||
@@ -263,52 +254,91 @@ func (m *Manager) RefreshSession() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) CommandKey(pid int) (string, error) {
|
||||
instances := m.wechat.GetWeChatInstances()
|
||||
if len(instances) == 0 {
|
||||
func (m *Manager) CommandKey(configPath string, pid int, force bool, showXorKey bool) (string, error) {
|
||||
|
||||
var err error
|
||||
m.ctx, err = ctx.New(configPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
m.wechat = wechat.NewService(m.ctx)
|
||||
|
||||
m.ctx.WeChatInstances = m.wechat.GetWeChatInstances()
|
||||
if len(m.ctx.WeChatInstances) == 0 {
|
||||
return "", fmt.Errorf("wechat process not found")
|
||||
}
|
||||
if len(instances) == 1 {
|
||||
key, _, err := instances[0].GetKey(context.Background())
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
||||
if len(m.ctx.WeChatInstances) == 1 {
|
||||
key, imgKey := m.ctx.DataKey, m.ctx.ImgKey
|
||||
if len(key) == 0 || len(imgKey) == 0 || force {
|
||||
key, imgKey, err = m.ctx.WeChatInstances[0].GetKey(context.Background())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m.ctx.Refresh()
|
||||
m.ctx.UpdateConfig()
|
||||
}
|
||||
return key, nil
|
||||
|
||||
result := fmt.Sprintf("Data Key: [%s]\nImage Key: [%s]", key, imgKey)
|
||||
if m.ctx.Version == 4 && showXorKey {
|
||||
if b, err := dat2img.ScanAndSetXorKey(m.ctx.DataDir); err == nil {
|
||||
result += fmt.Sprintf("\nXor Key: [0x%X]", b)
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
if pid == 0 {
|
||||
str := "Select a process:\n"
|
||||
for _, ins := range instances {
|
||||
for _, ins := range m.ctx.WeChatInstances {
|
||||
str += fmt.Sprintf("PID: %d. %s[Version: %s Data Dir: %s ]\n", ins.PID, ins.Name, ins.FullVersion, ins.DataDir)
|
||||
}
|
||||
return str, nil
|
||||
}
|
||||
for _, ins := range instances {
|
||||
for _, ins := range m.ctx.WeChatInstances {
|
||||
if ins.PID == uint32(pid) {
|
||||
key, _, err := ins.GetKey(context.Background())
|
||||
if err != nil {
|
||||
return "", err
|
||||
key, imgKey := ins.Key, ins.ImgKey
|
||||
if len(key) == 0 || len(imgKey) == 0 || force {
|
||||
key, imgKey, err = ins.GetKey(context.Background())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
m.ctx.Refresh()
|
||||
m.ctx.UpdateConfig()
|
||||
}
|
||||
return key, nil
|
||||
result := fmt.Sprintf("Data Key: [%s]\nImage Key: [%s]", key, imgKey)
|
||||
if m.ctx.Version == 4 && showXorKey {
|
||||
if b, err := dat2img.ScanAndSetXorKey(m.ctx.DataDir); err == nil {
|
||||
result += fmt.Sprintf("\nXor Key: [0x%X]", b)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("wechat process not found")
|
||||
}
|
||||
|
||||
func (m *Manager) CommandDecrypt(dataDir string, workDir string, key string, platform string, version int) error {
|
||||
if dataDir == "" {
|
||||
func (m *Manager) CommandDecrypt(configPath string, cmdConf map[string]any) error {
|
||||
|
||||
var err error
|
||||
m.sc, m.scm, err = conf.LoadServiceConfig(configPath, cmdConf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dataDir := m.sc.GetDataDir()
|
||||
if len(dataDir) == 0 {
|
||||
return fmt.Errorf("dataDir is required")
|
||||
}
|
||||
if key == "" {
|
||||
return fmt.Errorf("key is required")
|
||||
|
||||
dataKey := m.sc.GetDataKey()
|
||||
if len(dataKey) == 0 {
|
||||
return fmt.Errorf("dataKey is required")
|
||||
}
|
||||
if workDir == "" {
|
||||
workDir = util.DefaultWorkDir(filepath.Base(filepath.Dir(dataDir)))
|
||||
}
|
||||
m.ctx.DataDir = dataDir
|
||||
m.ctx.WorkDir = workDir
|
||||
m.ctx.DataKey = key
|
||||
m.ctx.Platform = platform
|
||||
m.ctx.Version = version
|
||||
|
||||
m.wechat = wechat.NewService(m.sc)
|
||||
|
||||
if err := m.wechat.DecryptDBFiles(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -316,43 +346,83 @@ func (m *Manager) CommandDecrypt(dataDir string, workDir string, key string, pla
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) CommandHTTPServer(addr string, dataDir string, workDir string, platform string, version int) error {
|
||||
func (m *Manager) CommandHTTPServer(configPath string, cmdConf map[string]any) error {
|
||||
|
||||
if addr == "" {
|
||||
addr = "127.0.0.1:5030"
|
||||
}
|
||||
|
||||
if workDir == "" {
|
||||
return fmt.Errorf("workDir is required")
|
||||
}
|
||||
|
||||
if platform == "" {
|
||||
return fmt.Errorf("platform is required")
|
||||
}
|
||||
|
||||
if version == 0 {
|
||||
return fmt.Errorf("version is required")
|
||||
}
|
||||
|
||||
m.ctx.HTTPAddr = addr
|
||||
m.ctx.DataDir = dataDir
|
||||
m.ctx.WorkDir = workDir
|
||||
m.ctx.Platform = platform
|
||||
m.ctx.Version = version
|
||||
|
||||
// 如果是 4.0 版本,更新下 xorkey
|
||||
if m.ctx.Version == 4 && m.ctx.DataDir != "" {
|
||||
go dat2img.ScanAndSetXorKey(m.ctx.DataDir)
|
||||
}
|
||||
|
||||
// 按依赖顺序启动服务
|
||||
if err := m.db.Start(); err != nil {
|
||||
var err error
|
||||
m.sc, m.scm, err = conf.LoadServiceConfig(configPath, cmdConf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dataDir := m.sc.GetDataDir()
|
||||
workDir := m.sc.GetWorkDir()
|
||||
if len(dataDir) == 0 && len(workDir) == 0 {
|
||||
return fmt.Errorf("dataDir or workDir is required")
|
||||
}
|
||||
|
||||
dataKey := m.sc.GetDataKey()
|
||||
if len(dataKey) == 0 {
|
||||
return fmt.Errorf("dataKey is required")
|
||||
}
|
||||
|
||||
// 如果是 4.0 版本,处理图片密钥
|
||||
version := m.sc.GetVersion()
|
||||
if version == 4 && len(dataDir) != 0 {
|
||||
dat2img.SetAesKey(m.sc.GetImgKey())
|
||||
go dat2img.ScanAndSetXorKey(dataDir)
|
||||
}
|
||||
|
||||
log.Info().Msgf("server config: %+v", m.sc)
|
||||
|
||||
m.wechat = wechat.NewService(m.sc)
|
||||
|
||||
m.db = database.NewService(m.sc)
|
||||
|
||||
m.mcp = mcp.NewService(m.db)
|
||||
|
||||
m.http = http.NewService(m.sc, m.db, m.mcp)
|
||||
|
||||
if m.sc.GetAutoDecrypt() {
|
||||
if err := m.wechat.StartAutoDecrypt(); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info().Msg("auto decrypt is enabled")
|
||||
}
|
||||
|
||||
// init db
|
||||
go func() {
|
||||
// 如果工作目录为空,则解密数据
|
||||
if entries, err := os.ReadDir(workDir); err == nil && len(entries) == 0 {
|
||||
log.Info().Msgf("work dir is empty, decrypt data.")
|
||||
m.db.SetDecrypting()
|
||||
if err := m.wechat.DecryptDBFiles(); err != nil {
|
||||
log.Info().Msgf("decrypt data failed: %v", err)
|
||||
return
|
||||
}
|
||||
log.Info().Msg("decrypt data success")
|
||||
}
|
||||
|
||||
// 按依赖顺序启动服务
|
||||
if err := m.db.Start(); err != nil {
|
||||
log.Info().Msgf("start db failed, try to decrypt data.")
|
||||
m.db.SetDecrypting()
|
||||
if err := m.wechat.DecryptDBFiles(); err != nil {
|
||||
log.Info().Msgf("decrypt data failed: %v", err)
|
||||
return
|
||||
}
|
||||
log.Info().Msg("decrypt data success")
|
||||
if err := m.db.Start(); err != nil {
|
||||
log.Info().Msgf("start db failed: %v", err)
|
||||
m.db.SetError(err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err := m.mcp.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer m.mcp.Stop()
|
||||
|
||||
return m.http.ListenAndServe()
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sjzar/chatlog/internal/chatlog/ctx"
|
||||
"github.com/sjzar/chatlog/internal/chatlog/database"
|
||||
"github.com/sjzar/chatlog/internal/mcp"
|
||||
"github.com/sjzar/chatlog/pkg/util"
|
||||
@@ -18,16 +17,14 @@ import (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ctx *ctx.Context
|
||||
db *database.Service
|
||||
db *database.Service
|
||||
|
||||
mcp *mcp.MCP
|
||||
}
|
||||
|
||||
func NewService(ctx *ctx.Context, db *database.Service) *Service {
|
||||
func NewService(db *database.Service) *Service {
|
||||
return &Service{
|
||||
ctx: ctx,
|
||||
db: db,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"github.com/sjzar/chatlog/internal/chatlog/ctx"
|
||||
"github.com/sjzar/chatlog/internal/errors"
|
||||
"github.com/sjzar/chatlog/internal/wechat"
|
||||
"github.com/sjzar/chatlog/internal/wechat/decrypt"
|
||||
@@ -25,16 +24,24 @@ var (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ctx *ctx.Context
|
||||
conf Config
|
||||
lastEvents map[string]time.Time
|
||||
pendingActions map[string]bool
|
||||
mutex sync.Mutex
|
||||
fm *filemonitor.FileMonitor
|
||||
}
|
||||
|
||||
func NewService(ctx *ctx.Context) *Service {
|
||||
type Config interface {
|
||||
GetDataKey() string
|
||||
GetDataDir() string
|
||||
GetWorkDir() string
|
||||
GetPlatform() string
|
||||
GetVersion() int
|
||||
}
|
||||
|
||||
func NewService(conf Config) *Service {
|
||||
return &Service{
|
||||
ctx: ctx,
|
||||
conf: conf,
|
||||
lastEvents: make(map[string]time.Time),
|
||||
pendingActions: make(map[string]bool),
|
||||
}
|
||||
@@ -61,7 +68,7 @@ func (s *Service) GetDataKey(info *wechat.Account) (string, error) {
|
||||
}
|
||||
|
||||
func (s *Service) StartAutoDecrypt() error {
|
||||
dbGroup, err := filemonitor.NewFileGroup("wechat", s.ctx.DataDir, `.*\.db$`, []string{"fts"})
|
||||
dbGroup, err := filemonitor.NewFileGroup("wechat", s.conf.GetDataDir(), `.*\.db$`, []string{"fts"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -129,12 +136,12 @@ func (s *Service) waitAndProcess(dbFile string) {
|
||||
|
||||
func (s *Service) DecryptDBFile(dbFile string) error {
|
||||
|
||||
decryptor, err := decrypt.NewDecryptor(s.ctx.Platform, s.ctx.Version)
|
||||
decryptor, err := decrypt.NewDecryptor(s.conf.GetPlatform(), s.conf.GetVersion())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
output := filepath.Join(s.ctx.WorkDir, dbFile[len(s.ctx.DataDir):])
|
||||
output := filepath.Join(s.conf.GetWorkDir(), dbFile[len(s.conf.GetDataDir()):])
|
||||
if err := util.PrepareDir(filepath.Dir(output)); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -151,7 +158,7 @@ func (s *Service) DecryptDBFile(dbFile string) error {
|
||||
}
|
||||
}()
|
||||
|
||||
if err := decryptor.Decrypt(context.Background(), dbFile, s.ctx.DataKey, outputFile); err != nil {
|
||||
if err := decryptor.Decrypt(context.Background(), dbFile, s.conf.GetDataKey(), outputFile); err != nil {
|
||||
if err == errors.ErrAlreadyDecrypted {
|
||||
if data, err := os.ReadFile(dbFile); err == nil {
|
||||
outputFile.Write(data)
|
||||
@@ -168,7 +175,7 @@ func (s *Service) DecryptDBFile(dbFile string) error {
|
||||
}
|
||||
|
||||
func (s *Service) DecryptDBFiles() error {
|
||||
dbGroup, err := filemonitor.NewFileGroup("wechat", s.ctx.DataDir, `.*\.db$`, []string{"fts"})
|
||||
dbGroup, err := filemonitor.NewFileGroup("wechat", s.conf.GetDataDir(), `.*\.db$`, []string{"fts"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user