84 lines
2.3 KiB
Go
84 lines
2.3 KiB
Go
package pairing
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
func httpJSON(method, url, token string, body interface{}) (int, []byte, error) {
|
|
var buf bytes.Buffer
|
|
if body != nil {
|
|
raw, _ := json.Marshal(body)
|
|
buf.Write(raw)
|
|
}
|
|
req, err := http.NewRequest(method, url, &buf)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
raw, _ := io.ReadAll(resp.Body)
|
|
return resp.StatusCode, raw, nil
|
|
}
|
|
|
|
func field(raw []byte, key string) string {
|
|
var m map[string]interface{}
|
|
_ = json.Unmarshal(raw, &m)
|
|
if d, ok := m["data"].(map[string]interface{}); ok {
|
|
if v, ok := d[key]; ok {
|
|
switch t := v.(type) {
|
|
case string:
|
|
return t
|
|
case float64:
|
|
return strconv.FormatInt(int64(t), 10)
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
type ginH map[string]interface{}
|
|
|
|
// AutoPair 开发便利:登录 → 取配对码 → 配对(无 UI 场景闭环用)
|
|
func AutoPair(server, email, password, deviceName, pubKeyB64 string) (uint64, error) {
|
|
code, raw, err := httpJSON("POST", server+"/api/v1/auth/login", "", ginH{"email": email, "password": password})
|
|
if err != nil || code != 200 {
|
|
return 0, fmt.Errorf("login failed: %s", string(raw))
|
|
}
|
|
token := field(raw, "accessToken")
|
|
code, raw, err = httpJSON("POST", server+"/api/v1/agent/pair-code", token, nil)
|
|
if err != nil || code != 200 {
|
|
return 0, fmt.Errorf("pair-code failed: %s", string(raw))
|
|
}
|
|
pairCode := field(raw, "code")
|
|
return PairWithCode(server, pairCode, deviceName, "core", "0.2.0", pubKeyB64)
|
|
}
|
|
|
|
// PairWithCode 凭配对码注册设备,返回服务器分配的设备 ID
|
|
func PairWithCode(server, pairCode, deviceName, osName, version, pubKeyB64 string) (uint64, error) {
|
|
code, raw, err := httpJSON("POST", server+"/api/v1/agent/pair", "", ginH{
|
|
"code": pairCode, "deviceName": deviceName, "os": osName, "version": version, "publicKey": pubKeyB64,
|
|
})
|
|
if err != nil || code != 200 {
|
|
return 0, fmt.Errorf("pair failed: %s", string(raw))
|
|
}
|
|
id, _ := strconv.ParseUint(field(raw, "deviceId"), 10, 64)
|
|
if id == 0 {
|
|
return 0, fmt.Errorf("pair response missing deviceId")
|
|
}
|
|
return id, nil
|
|
}
|