package store import ( "encoding/json" "os" "path/filepath" "sync" "time" "git.asio.asia/TapRemly/desktop/agent/internal/protocol" ) const ( maxLogs = 500 maxInbox = 200 maxResults = 200 ) // Executed 记住一条命令的第一次结果。 type Executed struct { ID string `json:"id"` At time.Time `json:"at"` OK bool `json:"ok"` Error string `json:"error,omitempty"` Detail string `json:"detail,omitempty"` Raw json.RawMessage `json:"raw,omitempty"` } // LocalShortcut 是针对某一台远端的本端快捷命令。 type LocalShortcut struct { protocol.Shortcut RemoteID string `json:"remote_id"` } // RemoteCache 是某台远端上次同步来的快捷命令。 type RemoteCache struct { Items []protocol.Shortcut `json:"items"` SyncedAt time.Time `json:"synced_at"` Syncing bool `json:"syncing"` ReqID string `json:"req_id,omitempty"` } // LogCache 是向对方要来的长日志。 type LogCache struct { Items []protocol.Log `json:"items"` SyncedAt time.Time `json:"synced_at"` Syncing bool `json:"syncing"` ReqID string `json:"req_id,omitempty"` Error string `json:"error,omitempty"` } // TextMsg 是收到的文字。 type TextMsg struct { ID string `json:"id"` From string `json:"from"` Text string `json:"text"` At time.Time `json:"at"` Read bool `json:"read"` } // CmdResult 是我们发出的命令收到的结果。 type CmdResult struct { ID string `json:"id"` Remote string `json:"remote"` OK bool `json:"ok"` Error string `json:"error,omitempty"` Duplicate bool `json:"duplicate,omitempty"` At time.Time `json:"at"` } // Cookie 是账号会话里需要记住的一块。 type Cookie struct { Name string `json:"name"` Value string `json:"value"` Domain string `json:"domain"` Path string `json:"path"` Expires time.Time `json:"expires"` Secure bool `json:"secure"` HttpOnly bool `json:"http_only"` } // Data 是落在本机的全部状态。令牌只在这个文件里,不进界面存储。 type Data struct { ServerURL string `json:"server_url"` NixURL string `json:"nixmsg_url"` EndpointID string `json:"endpoint_id"` SessionToken string `json:"session_token,omitempty"` DeviceToken string `json:"device_token,omitempty"` AccountUser string `json:"account_user,omitempty"` Cookies []Cookie `json:"cookies,omitempty"` Trust []string `json:"trust"` PendingSecret string `json:"pending_secret,omitempty"` Local []LocalShortcut `json:"local_shortcuts"` Published []protocol.Shortcut `json:"published"` Remote map[string]RemoteCache `json:"remote_shortcuts"` RemoteLogs map[string]LogCache `json:"remote_logs"` Executed []Executed `json:"executed"` Logs []protocol.Log `json:"logs"` Inbox []TextMsg `json:"inbox"` Results []CmdResult `json:"results"` } // Store 用一个 JSON 文件保存状态。 type Store struct { mu sync.Mutex path string data Data } func New(dir string) (*Store, error) { if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } s := &Store{path: filepath.Join(dir, "state.json")} s.data = defaultData() b, err := os.ReadFile(s.path) if err != nil { if os.IsNotExist(err) { return s, s.saveLocked() } return nil, err } if len(b) > 0 { if err := json.Unmarshal(b, &s.data); err != nil { return nil, err } } s.normalize() return s, nil } func defaultData() Data { return Data{ ServerURL: "http://127.0.0.1:8080", NixURL: "wss://nm.asio.asia/mqtt", Trust: []string{}, Local: []LocalShortcut{}, Published: []protocol.Shortcut{}, Remote: map[string]RemoteCache{}, RemoteLogs: map[string]LogCache{}, Executed: []Executed{}, Logs: []protocol.Log{}, Inbox: []TextMsg{}, Results: []CmdResult{}, } } func (d Data) clone() Data { n := d n.Trust = append([]string(nil), d.Trust...) n.Cookies = append([]Cookie(nil), d.Cookies...) n.Local = append([]LocalShortcut(nil), d.Local...) n.Published = append([]protocol.Shortcut(nil), d.Published...) n.Executed = append([]Executed(nil), d.Executed...) n.Logs = append([]protocol.Log(nil), d.Logs...) n.Inbox = append([]TextMsg(nil), d.Inbox...) n.Results = append([]CmdResult(nil), d.Results...) n.Remote = map[string]RemoteCache{} for k, v := range d.Remote { v.Items = append([]protocol.Shortcut(nil), v.Items...) n.Remote[k] = v } n.RemoteLogs = map[string]LogCache{} for k, v := range d.RemoteLogs { v.Items = append([]protocol.Log(nil), v.Items...) n.RemoteLogs[k] = v } return n } func (d *Data) normalize() { if d.ServerURL == "" { d.ServerURL = "http://127.0.0.1:8080" } if d.NixURL == "" { d.NixURL = "wss://nm.asio.asia/mqtt" } if d.Trust == nil { d.Trust = []string{} } if d.Local == nil { d.Local = []LocalShortcut{} } if d.Published == nil { d.Published = []protocol.Shortcut{} } if d.Remote == nil { d.Remote = map[string]RemoteCache{} } if d.RemoteLogs == nil { d.RemoteLogs = map[string]LogCache{} } if d.Executed == nil { d.Executed = []Executed{} } if d.Logs == nil { d.Logs = []protocol.Log{} } if d.Inbox == nil { d.Inbox = []TextMsg{} } if d.Results == nil { d.Results = []CmdResult{} } d.ensureSelf() } func (d *Data) ensureSelf() { if d.EndpointID == "" { return } for _, it := range d.Trust { if it == d.EndpointID { return } } d.Trust = append([]string{d.EndpointID}, d.Trust...) } func (s *Store) normalize() { s.data.normalize() } // Update 在副本上修改,成功后才替换并保存。回调里不能再调用 Store。 func (s *Store) Update(fn func(*Data) error) error { s.mu.Lock() defer s.mu.Unlock() next := s.data.clone() if err := fn(&next); err != nil { return err } next.normalize() s.data = next return s.saveLocked() } // View 在锁内只读。回调里复制需要带走的数据。 func (s *Store) View(fn func(*Data)) { s.mu.Lock() defer s.mu.Unlock() s.normalize() fn(&s.data) } func (s *Store) saveLocked() error { s.normalize() b, err := json.MarshalIndent(s.data, "", " ") if err != nil { return err } tmp := s.path + ".tmp" if err := os.WriteFile(tmp, b, 0o600); err != nil { return err } if err := os.Rename(tmp, s.path); err != nil { _ = os.Remove(s.path) if err2 := os.Rename(tmp, s.path); err2 != nil { return err2 } } return nil } // AppendLog 保留最近 500 条,返回最近 20 条供上传。 func AppendLog(d *Data, item protocol.Log) []protocol.Log { d.Logs = append(d.Logs, item) if len(d.Logs) > maxLogs { d.Logs = append([]protocol.Log(nil), d.Logs[len(d.Logs)-maxLogs:]...) } return LastLogs(d.Logs, 20) } // LastLogs 取末尾 n 条。 func LastLogs(items []protocol.Log, n int) []protocol.Log { if len(items) <= n { out := append([]protocol.Log(nil), items...) return out } return append([]protocol.Log(nil), items[len(items)-n:]...) } // TrimExecuted 丢掉早于保留窗口的记录。 func TrimExecuted(d *Data, now time.Time, keep time.Duration) { cut := now.Add(-keep) out := d.Executed[:0] for _, e := range d.Executed { if e.At.After(cut) { out = append(out, e) } } d.Executed = out }