diff --git a/agent/internal/account/account.go b/agent/internal/account/account.go index da4ff7a..c872b25 100644 --- a/agent/internal/account/account.go +++ b/agent/internal/account/account.go @@ -113,14 +113,14 @@ func (s *Session) Login(ctx context.Context, username, password string) (string, return "", apiErr(resp.StatusCode, raw, false) } name := username - if n := firstString(raw, "username", "name"); n != "" { + if n := firstString(unwrapData(raw), "username", "name"); n != "" { name = n } return name, nil } func (s *Session) Logout(ctx context.Context) error { - resp, raw, err := s.do(ctx, http.MethodDelete, "/api/login", nil, "") + resp, raw, err := s.do(ctx, http.MethodPost, "/api/logout", map[string]any{}, "") if err != nil { return err } @@ -134,31 +134,36 @@ func (s *Session) Logout(ctx context.Context) error { } func (s *Session) Devices(ctx context.Context) ([]Device, error) { + devices, _, err := s.directory(ctx) + return devices, err +} + +func (s *Session) directory(ctx context.Context) ([]Device, []Group, error) { resp, raw, err := s.do(ctx, http.MethodGet, "/api/devices", nil, "") if err != nil { - return nil, err + return nil, nil, err } if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { - return nil, Error("请重新登录账号") + return nil, nil, Error("请重新登录账号") } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, apiErr(resp.StatusCode, raw, false) + return nil, nil, apiErr(resp.StatusCode, raw, false) } - return decodeDevices(raw) + body := unwrapData(raw) + devices, err := decodeDevices(body) + if err != nil { + return nil, nil, err + } + groups, err := decodeGroups(body) + if err != nil { + return nil, nil, err + } + return devices, groups, nil } func (s *Session) Groups(ctx context.Context) ([]Group, error) { - resp, raw, err := s.do(ctx, http.MethodGet, "/api/groups", nil, "") - if err != nil { - return nil, err - } - if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { - return nil, Error("请重新登录账号") - } - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, apiErr(resp.StatusCode, raw, false) - } - return decodeGroups(raw) + _, groups, err := s.directory(ctx) + return groups, err } func (s *Session) CreateGroup(ctx context.Context, name string) error { @@ -185,7 +190,7 @@ func (s *Session) AddDevice(ctx context.Context, name, endpointID string) (Provi if resp.StatusCode < 200 || resp.StatusCode >= 300 { return Provision{}, apiErr(resp.StatusCode, raw, false) } - return decodeProvision(raw), nil + return decodeProvision(unwrapData(raw)), nil } func (s *Session) PatchDevice(ctx context.Context, id string, name *string, groupID *string) error { @@ -204,7 +209,21 @@ func (s *Session) DeleteDevice(ctx context.Context, id string) error { } func (s *Session) GetLogs(ctx context.Context, endpointID string) ([]protocol.Log, error) { - resp, raw, err := s.do(ctx, http.MethodGet, "/api/devices/"+url.PathEscape(endpointID)+"/logs", nil, "") + devices, err := s.Devices(ctx) + if err != nil { + return nil, err + } + var id string + for _, d := range devices { + if d.EndpointID == endpointID || d.ID == endpointID { + id = d.ID + break + } + } + if id == "" { + return []protocol.Log{}, nil + } + resp, raw, err := s.do(ctx, http.MethodGet, "/api/devices/"+url.PathEscape(id)+"/command-logs", nil, "") if err != nil { return nil, err } @@ -214,7 +233,7 @@ func (s *Session) GetLogs(ctx context.Context, endpointID string) ([]protocol.Lo if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, apiErr(resp.StatusCode, raw, false) } - return decodeLogs(raw), nil + return decodeLogs(unwrapData(raw)), nil } // PutLogs 用创建设备时的设备令牌覆盖上传最近若干条。 @@ -226,15 +245,23 @@ func PutLogs(ctx context.Context, base, endpointID, deviceToken string, items [] if items == nil { items = []protocol.Log{} } - payload, err := json.Marshal(map[string]any{"items": items}) + mapped := serverLogItems(items) + if len(mapped) == 0 { + return nil + } + payload, err := json.Marshal(map[string]any{ + "endpoint_id": endpointID, + "items": mapped, + }) if err != nil { return err } - req, err := http.NewRequestWithContext(ctx, http.MethodPut, base+"/api/devices/"+url.PathEscape(endpointID)+"/logs", bytes.NewReader(payload)) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, base+"/api/command-logs", bytes.NewReader(payload)) if err != nil { return err } req.Header.Set("Content-Type", "application/json; charset=utf-8") + req.Header.Set("X-Tapremly-Request", "1") req.Header.Set("Authorization", "Bearer "+deviceToken) resp, err := (&http.Client{Timeout: 15 * time.Second}).Do(req) if err != nil { @@ -278,6 +305,9 @@ func (s *Session) do(ctx context.Context, method, path string, payload any, bear if payload != nil { req.Header.Set("Content-Type", "application/json; charset=utf-8") } + if method != http.MethodGet && method != http.MethodHead { + req.Header.Set("X-Tapremly-Request", "1") + } if bearer != "" { req.Header.Set("Authorization", "Bearer "+bearer) } @@ -294,10 +324,13 @@ func apiErr(code int, raw []byte, login bool) error { if login && (code == http.StatusUnauthorized || code == http.StatusForbidden) { return Error("账号或密码不正确") } - if code == http.StatusUnauthorized || code == http.StatusForbidden { - return Error("请重新登录账号") + var wrap struct { + Error struct { + Message string `json:"message"` + } `json:"error"` } - if s := firstString(raw, "message", "error"); s != "" && utf8.RuneCountInString(s) <= 80 && containsHan(s) { + _ = json.Unmarshal(raw, &wrap) + if s := strings.TrimSpace(wrap.Error.Message); s != "" && utf8.RuneCountInString(s) <= 80 { return Error(s) } if code >= 500 { @@ -340,7 +373,16 @@ func decodeDevices(raw []byte) ([]Device, error) { } func decodeGroups(raw []byte) ([]Group, error) { - items := extractItems(raw) + var wrap map[string]json.RawMessage + if json.Unmarshal(raw, &wrap) == nil { + if b, ok := wrap["groups"]; ok { + return groupsFrom(rawList(b)), nil + } + } + return groupsFrom(extractItems(raw)), nil +} + +func groupsFrom(items []map[string]any) []Group { out := make([]Group, 0, len(items)) for _, m := range items { g := Group{ID: str(m, "id"), Name: first(m, "name")} @@ -352,21 +394,37 @@ func decodeGroups(raw []byte) ([]Group, error) { } out = append(out, g) } - return out, nil + return out } func decodeLogs(raw []byte) []protocol.Log { + raw = unwrapData(raw) var wrap struct { - Items []protocol.Log `json:"items"` + Items []struct { + At string `json:"at"` + AtMs int64 `json:"at_ms"` + Summary string `json:"summary"` + OK bool `json:"ok"` + Detail string `json:"detail"` + Result string `json:"result"` + } `json:"items"` } - if json.Unmarshal(raw, &wrap) == nil && wrap.Items != nil { - return wrap.Items + if json.Unmarshal(raw, &wrap) != nil || wrap.Items == nil { + return []protocol.Log{} } - var items []protocol.Log - if json.Unmarshal(raw, &items) == nil && items != nil { - return items + out := make([]protocol.Log, 0, len(wrap.Items)) + for _, item := range wrap.Items { + at := item.At + if at == "" && item.AtMs > 0 { + at = time.UnixMilli(item.AtMs).UTC().Format(time.RFC3339) + } + detail := item.Detail + if detail == "" { + detail = item.Result + } + out = append(out, protocol.Log{At: at, Summary: item.Summary, OK: item.OK, Detail: detail}) } - return []protocol.Log{} + return out } func decodeProvision(raw []byte) Provision { @@ -378,12 +436,49 @@ func decodeProvision(raw []byte) Provision { Password: first(m, "password", "login_password", "nixmsg_password"), DeviceToken: first(m, "device_token", "deviceToken"), } - if p.DeviceToken == "" && p.Password != "" { - p.DeviceToken = first(m, "token") + if p.Password == "" { + p.Password = first(m, "login_password") + } + if p.DeviceToken == "" { + p.DeviceToken = p.Password } return p } +func unwrapData(raw []byte) []byte { + var wrap struct { + Data json.RawMessage `json:"data"` + } + if json.Unmarshal(raw, &wrap) == nil && len(wrap.Data) > 0 && wrap.Data[0] == '{' { + return wrap.Data + } + return raw +} + +func serverLogItems(items []protocol.Log) []map[string]any { + out := make([]map[string]any, 0, len(items)) + for _, item := range items { + at := time.Now().UnixMilli() + if t, err := time.Parse(time.RFC3339, item.At); err == nil { + at = t.UnixMilli() + } + summary := strings.TrimSpace(item.Summary) + if summary == "" { + continue + } + out = append(out, map[string]any{ + "at_ms": at, + "summary": summary, + "ok": item.OK, + "result": strings.TrimSpace(item.Detail), + }) + } + if len(out) > 20 { + out = out[len(out)-20:] + } + return out +} + func pickObject(m map[string]any) map[string]any { for _, k := range []string{"device", "data"} { nested, ok := m[k].(map[string]any) diff --git a/agent/internal/engine/engine.go b/agent/internal/engine/engine.go index ebc8eb1..78e89b2 100644 --- a/agent/internal/engine/engine.go +++ b/agent/internal/engine/engine.go @@ -2,6 +2,7 @@ package engine import ( "context" + "encoding/json" "strings" "time" @@ -78,13 +79,15 @@ func (e *Engine) Accept(from, raw string) ([]Outbox, []protocol.Log, error) { return e.acceptCommand(from, msg.ID, "", true, msg.ShortcutID) case protocol.TypeText: return nil, nil, e.acceptText(from, msg) - case protocol.TypeShortcuts: + case protocol.TypeShortcuts, protocol.TypeShortcutsGet: + if msg.Type == protocol.TypeShortcutsGet || !jsonHasItems(raw) { + return e.replyShortcuts(from, msg.ID) + } return nil, nil, e.acceptShortcuts(from, msg) - case protocol.TypeShortcutsGet: - return e.replyShortcuts(from, msg.ID) - case protocol.TypeLogsGet: - return e.replyLogs(from, msg.ID) - case protocol.TypeLogs: + case protocol.TypeLogs, protocol.TypeLogsGet: + if msg.Type == protocol.TypeLogsGet || !jsonHasItems(raw) { + return e.replyLogs(from, msg.ID) + } return nil, nil, e.acceptLogs(from, msg) case protocol.TypeResult: return nil, nil, e.acceptResult(from, msg) @@ -93,6 +96,16 @@ func (e *Engine) Accept(from, raw string) ([]Outbox, []protocol.Log, error) { } } +func jsonHasItems(raw string) bool { + var probe struct { + Items json.RawMessage `json:"items"` + } + if json.Unmarshal([]byte(raw), &probe) != nil || len(probe.Items) == 0 { + return false + } + return string(probe.Items) != "null" +} + func (e *Engine) acceptCommand(from, id, script string, shortcut bool, shortcutID string) ([]Outbox, []protocol.Log, error) { if !idutil.ValidMessage(id) { return nil, nil, nil diff --git a/agent/internal/protocol/protocol.go b/agent/internal/protocol/protocol.go index 9b900e5..fbaf0d8 100644 --- a/agent/internal/protocol/protocol.go +++ b/agent/internal/protocol/protocol.go @@ -129,7 +129,7 @@ func ShortcutsGetBody(id string) ([]byte, error) { V int `json:"v"` Type string `json:"type"` ID string `json:"id"` - }{Version, TypeShortcutsGet, id}) + }{Version, TypeShortcuts, id}) } // LogsGetBody 向在线的对方要本地长日志。 @@ -138,7 +138,7 @@ func LogsGetBody(id string) ([]byte, error) { V int `json:"v"` Type string `json:"type"` ID string `json:"id"` - }{Version, TypeLogsGet, id}) + }{Version, TypeLogs, id}) } // LogsBody 编码日志列表。