469 lines
12 KiB
Go
469 lines
12 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(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, "")
|
|
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) {
|
|
resp, raw, err := s.do(ctx, http.MethodGet, "/api/devices", 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 decodeDevices(raw)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
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(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) {
|
|
resp, raw, err := s.do(ctx, http.MethodGet, "/api/devices/"+url.PathEscape(endpointID)+"/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(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{}
|
|
}
|
|
payload, err := json.Marshal(map[string]any{"items": items})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPut, base+"/api/devices/"+url.PathEscape(endpointID)+"/logs", bytes.NewReader(payload))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
|
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 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("账号或密码不正确")
|
|
}
|
|
if code == http.StatusUnauthorized || code == http.StatusForbidden {
|
|
return Error("请重新登录账号")
|
|
}
|
|
if s := firstString(raw, "message", "error"); s != "" && utf8.RuneCountInString(s) <= 80 && containsHan(s) {
|
|
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) {
|
|
items := extractItems(raw)
|
|
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, nil
|
|
}
|
|
|
|
func decodeLogs(raw []byte) []protocol.Log {
|
|
var wrap struct {
|
|
Items []protocol.Log `json:"items"`
|
|
}
|
|
if json.Unmarshal(raw, &wrap) == nil && wrap.Items != nil {
|
|
return wrap.Items
|
|
}
|
|
var items []protocol.Log
|
|
if json.Unmarshal(raw, &items) == nil && items != nil {
|
|
return items
|
|
}
|
|
return []protocol.Log{}
|
|
}
|
|
|
|
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.DeviceToken == "" && p.Password != "" {
|
|
p.DeviceToken = first(m, "token")
|
|
}
|
|
return p
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|