564 lines
14 KiB
Go
564 lines
14 KiB
Go
// Package account 访问 TapRemly 账号服务。服务端尚未完成时按同一约定调用。
|
|
package account
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/protocol"
|
|
"git.asio.asia/TapRemly/desktop/agent/internal/store"
|
|
)
|
|
|
|
// Error 是可以显示给用户的短句。
|
|
type Error string
|
|
|
|
func (e Error) Error() string { return string(e) }
|
|
|
|
// Device 是账号下的一台设备。
|
|
type Device struct {
|
|
ID string
|
|
Name string
|
|
EndpointID string
|
|
GroupID string
|
|
}
|
|
|
|
// Group 是一个分组。
|
|
type Group struct {
|
|
ID string
|
|
Name string
|
|
}
|
|
|
|
// Provision 是登记本机时服务端返回的端信息。密码不向外转发。
|
|
type Provision struct {
|
|
ID string
|
|
Name string
|
|
EndpointID string
|
|
Password string
|
|
DeviceToken string
|
|
}
|
|
|
|
// Session 带着账号会话访问服务器。
|
|
type Session struct {
|
|
Base string
|
|
HTTP *http.Client
|
|
}
|
|
|
|
func NewSession(base string, cookies []store.Cookie) (*Session, error) {
|
|
jar, err := cookiejar.New(nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
base = strings.TrimRight(strings.TrimSpace(base), "/")
|
|
if base == "" {
|
|
return nil, Error("请填写服务器地址")
|
|
}
|
|
u, err := url.Parse(base)
|
|
if err != nil || u.Scheme == "" || u.Host == "" {
|
|
return nil, Error("服务器地址不正确")
|
|
}
|
|
if len(cookies) > 0 {
|
|
list := make([]*http.Cookie, 0, len(cookies))
|
|
for _, c := range cookies {
|
|
if c.Name == "" {
|
|
continue
|
|
}
|
|
list = append(list, &http.Cookie{
|
|
Name: c.Name, Value: c.Value, Path: c.Path, Expires: c.Expires, Secure: c.Secure, HttpOnly: c.HttpOnly,
|
|
})
|
|
}
|
|
jar.SetCookies(u, list)
|
|
}
|
|
return &Session{
|
|
Base: base,
|
|
HTTP: &http.Client{Timeout: 20 * time.Second, Jar: jar},
|
|
}, nil
|
|
}
|
|
|
|
// Cookies 导出当前会话,供下次启动继续使用。
|
|
func (s *Session) Cookies() []store.Cookie {
|
|
u, err := url.Parse(s.Base)
|
|
if err != nil || s.HTTP == nil || s.HTTP.Jar == nil {
|
|
return nil
|
|
}
|
|
src := s.HTTP.Jar.Cookies(u)
|
|
out := make([]store.Cookie, 0, len(src))
|
|
for _, c := range src {
|
|
out = append(out, store.Cookie{
|
|
Name: c.Name, Value: c.Value, Domain: u.Hostname(), Path: c.Path, Expires: c.Expires, Secure: c.Secure, HttpOnly: c.HttpOnly,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (s *Session) Login(ctx context.Context, username, password string) (string, error) {
|
|
body := map[string]string{"username": username, "password": password}
|
|
resp, raw, err := s.do(ctx, http.MethodPost, "/api/login", body, "")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
|
return "", Error("账号或密码不正确")
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return "", apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
name := username
|
|
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.MethodPost, "/api/logout", map[string]any{}, "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusNoContent || resp.StatusCode == http.StatusOK {
|
|
return nil
|
|
}
|
|
if resp.StatusCode >= 400 {
|
|
return apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
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, nil, err
|
|
}
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
|
return nil, nil, Error("请重新登录账号")
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil, nil, apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
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) {
|
|
_, groups, err := s.directory(ctx)
|
|
return groups, err
|
|
}
|
|
|
|
func (s *Session) CreateGroup(ctx context.Context, name string) error {
|
|
return s.expectOK(ctx, http.MethodPost, "/api/groups", map[string]string{"name": name})
|
|
}
|
|
|
|
func (s *Session) RenameGroup(ctx context.Context, id, name string) error {
|
|
return s.expectOK(ctx, http.MethodPatch, "/api/groups/"+url.PathEscape(id), map[string]string{"name": name})
|
|
}
|
|
|
|
func (s *Session) DeleteGroup(ctx context.Context, id string) error {
|
|
return s.expectOK(ctx, http.MethodDelete, "/api/groups/"+url.PathEscape(id), nil)
|
|
}
|
|
|
|
func (s *Session) AddDevice(ctx context.Context, name, endpointID string) (Provision, error) {
|
|
payload := map[string]string{"name": name}
|
|
if endpointID != "" {
|
|
payload["endpoint_id"] = endpointID
|
|
}
|
|
resp, raw, err := s.do(ctx, http.MethodPost, "/api/devices", payload, "")
|
|
if err != nil {
|
|
return Provision{}, err
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return Provision{}, apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
return decodeProvision(unwrapData(raw)), nil
|
|
}
|
|
|
|
func (s *Session) PatchDevice(ctx context.Context, id string, name *string, groupID *string) error {
|
|
payload := map[string]any{}
|
|
if name != nil {
|
|
payload["name"] = *name
|
|
}
|
|
if groupID != nil {
|
|
payload["group_id"] = *groupID
|
|
}
|
|
return s.expectOK(ctx, http.MethodPatch, "/api/devices/"+url.PathEscape(id), payload)
|
|
}
|
|
|
|
func (s *Session) DeleteDevice(ctx context.Context, id string) error {
|
|
return s.expectOK(ctx, http.MethodDelete, "/api/devices/"+url.PathEscape(id), nil)
|
|
}
|
|
|
|
func (s *Session) GetLogs(ctx context.Context, endpointID string) ([]protocol.Log, error) {
|
|
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
|
|
}
|
|
if resp.StatusCode == http.StatusNotFound {
|
|
return []protocol.Log{}, nil
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return nil, apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
return decodeLogs(unwrapData(raw)), nil
|
|
}
|
|
|
|
// PutLogs 用创建设备时的设备令牌覆盖上传最近若干条。
|
|
func PutLogs(ctx context.Context, base, endpointID, deviceToken string, items []protocol.Log) error {
|
|
base = strings.TrimRight(strings.TrimSpace(base), "/")
|
|
if base == "" || endpointID == "" || deviceToken == "" {
|
|
return nil
|
|
}
|
|
if items == nil {
|
|
items = []protocol.Log{}
|
|
}
|
|
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/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 {
|
|
return Error("暂时连不上账号服务")
|
|
}
|
|
defer resp.Body.Close()
|
|
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Session) expectOK(ctx context.Context, method, path string, payload any) error {
|
|
resp, raw, err := s.do(ctx, method, path, payload, "")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
|
return Error("请重新登录账号")
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
return apiErr(resp.StatusCode, raw, false)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Session) do(ctx context.Context, method, path string, payload any, bearer string) (*http.Response, []byte, error) {
|
|
var body io.Reader
|
|
if payload != nil {
|
|
b, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
body = bytes.NewReader(b)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, s.Base+path, body)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
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)
|
|
}
|
|
resp, err := s.HTTP.Do(req)
|
|
if err != nil {
|
|
return nil, nil, Error("暂时连不上账号服务")
|
|
}
|
|
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
_ = resp.Body.Close()
|
|
return resp, raw, nil
|
|
}
|
|
|
|
func apiErr(code int, raw []byte, login bool) error {
|
|
if login && (code == http.StatusUnauthorized || code == http.StatusForbidden) {
|
|
return Error("账号或密码不正确")
|
|
}
|
|
var wrap struct {
|
|
Error struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
_ = json.Unmarshal(raw, &wrap)
|
|
if s := strings.TrimSpace(wrap.Error.Message); s != "" && utf8.RuneCountInString(s) <= 80 {
|
|
return Error(s)
|
|
}
|
|
if code >= 500 {
|
|
return Error("账号服务暂时不可用")
|
|
}
|
|
return Error("操作没有成功")
|
|
}
|
|
|
|
func containsHan(s string) bool {
|
|
for _, r := range s {
|
|
if r >= 0x4e00 && r <= 0x9fff {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func decodeDevices(raw []byte) ([]Device, error) {
|
|
items := extractItems(raw)
|
|
out := make([]Device, 0, len(items))
|
|
for _, m := range items {
|
|
d := Device{
|
|
ID: str(m, "id"),
|
|
Name: first(m, "name"),
|
|
EndpointID: first(m, "endpoint_id", "endpointId"),
|
|
GroupID: first(m, "group_id", "groupId"),
|
|
}
|
|
if d.EndpointID == "" {
|
|
d.EndpointID = d.ID
|
|
}
|
|
if d.ID == "" {
|
|
d.ID = d.EndpointID
|
|
}
|
|
if d.Name == "" {
|
|
d.Name = d.EndpointID
|
|
}
|
|
out = append(out, d)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func decodeGroups(raw []byte) ([]Group, error) {
|
|
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")}
|
|
if g.ID == "" {
|
|
continue
|
|
}
|
|
if g.Name == "" {
|
|
g.Name = g.ID
|
|
}
|
|
out = append(out, g)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func decodeLogs(raw []byte) []protocol.Log {
|
|
raw = unwrapData(raw)
|
|
var wrap struct {
|
|
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 []protocol.Log{}
|
|
}
|
|
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 out
|
|
}
|
|
|
|
func decodeProvision(raw []byte) Provision {
|
|
m := pickObject(object(raw))
|
|
p := Provision{
|
|
ID: str(m, "id"),
|
|
Name: first(m, "name"),
|
|
EndpointID: first(m, "endpoint_id", "endpointId"),
|
|
Password: first(m, "password", "login_password", "nixmsg_password"),
|
|
DeviceToken: first(m, "device_token", "deviceToken"),
|
|
}
|
|
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)
|
|
if !ok {
|
|
continue
|
|
}
|
|
if first(nested, "endpoint_id", "endpointId", "id", "password") != "" {
|
|
return nested
|
|
}
|
|
}
|
|
return m
|
|
}
|
|
|
|
func extractItems(raw []byte) []map[string]any {
|
|
var wrap map[string]json.RawMessage
|
|
if json.Unmarshal(raw, &wrap) == nil {
|
|
for _, key := range []string{"items", "devices", "groups"} {
|
|
if b, ok := wrap[key]; ok {
|
|
return rawList(b)
|
|
}
|
|
}
|
|
}
|
|
return rawList(raw)
|
|
}
|
|
|
|
func rawList(b []byte) []map[string]any {
|
|
var arr []json.RawMessage
|
|
if json.Unmarshal(b, &arr) != nil {
|
|
return nil
|
|
}
|
|
out := make([]map[string]any, 0, len(arr))
|
|
for _, item := range arr {
|
|
var m map[string]any
|
|
if json.Unmarshal(item, &m) == nil {
|
|
out = append(out, m)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func object(raw []byte) map[string]any {
|
|
var m map[string]any
|
|
_ = json.Unmarshal(raw, &m)
|
|
if m == nil {
|
|
m = map[string]any{}
|
|
}
|
|
return m
|
|
}
|
|
|
|
func firstString(raw []byte, keys ...string) string {
|
|
return first(object(raw), keys...)
|
|
}
|
|
|
|
func first(m map[string]any, keys ...string) string {
|
|
for _, k := range keys {
|
|
if s := str(m, k); s != "" {
|
|
return s
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func str(m map[string]any, k string) string {
|
|
v, ok := m[k]
|
|
if !ok || v == nil {
|
|
return ""
|
|
}
|
|
switch t := v.(type) {
|
|
case string:
|
|
return strings.TrimSpace(t)
|
|
case float64:
|
|
return strconv.FormatInt(int64(t), 10)
|
|
case json.Number:
|
|
return t.String()
|
|
default:
|
|
s := strings.TrimSpace(fmt.Sprint(t))
|
|
if s == "<nil>" {
|
|
return ""
|
|
}
|
|
return s
|
|
}
|
|
}
|