package nixmsg import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/http/cookiejar" "strings" "sync" "time" ) type Client struct { baseURL string username string password string http *http.Client mu sync.Mutex loggedIn bool } func New(baseURL, username, password string) (*Client, error) { jar, err := cookiejar.New(nil) if err != nil { return nil, err } return &Client{ baseURL: strings.TrimRight(baseURL, "/"), username: username, password: password, http: &http.Client{ Timeout: 20 * time.Second, Jar: jar, }, }, nil } type Endpoint struct { ID string LoginPassword string Online bool Found bool } func (c *Client) CreateEndpoint(ctx context.Context, id, name string) (Endpoint, error) { var out struct { ID string `json:"id"` LoginPassword string `json:"login_password"` } err := c.call(ctx, http.MethodPost, "/api/admin/endpoints", map[string]any{ "id": id, "name": name, "remark": "", "login_password": "", "talk_password": "", "default_delay_seconds": 0, }, &out) if err != nil { return Endpoint{}, err } if out.ID == "" || out.LoginPassword == "" { return Endpoint{}, errors.New("nixmsg: endpoint was created without a one-time password") } return Endpoint{ID: out.ID, LoginPassword: out.LoginPassword, Found: true}, nil } func (c *Client) DeleteEndpoint(ctx context.Context, id string) error { return c.call(ctx, http.MethodDelete, "/api/admin/endpoints/"+id, nil, nil) } func (c *Client) Lookup(ctx context.Context, id string) (Endpoint, error) { var out struct { ID string `json:"id"` Online bool `json:"online"` } err := c.call(ctx, http.MethodGet, "/api/admin/endpoints/"+id, nil, &out) if err != nil { var apiErr *APIError if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound { return Endpoint{Found: false}, nil } return Endpoint{}, err } return Endpoint{ID: out.ID, Online: out.Online, Found: true}, nil } type APIError struct { Status int Code string Message string } func (e *APIError) Error() string { if e.Message != "" { return e.Message } return fmt.Sprintf("nixmsg status %d", e.Status) } func (c *Client) call(ctx context.Context, method, path string, body any, dest any) error { status, payload, err := c.do(ctx, method, path, body, true) if err != nil { return err } var env struct { OK bool `json:"ok"` Data json.RawMessage `json:"data"` Error struct { Code string `json:"code"` Message string `json:"message"` } `json:"error"` } if err := json.Unmarshal(payload, &env); err != nil { return fmt.Errorf("nixmsg: invalid response") } if status < 200 || status >= 300 || !env.OK { return &APIError{Status: status, Code: env.Error.Code, Message: env.Error.Message} } if dest != nil && len(env.Data) > 0 && string(env.Data) != "null" { if err := json.Unmarshal(env.Data, dest); err != nil { return fmt.Errorf("nixmsg: invalid data") } } return nil } func (c *Client) do(ctx context.Context, method, path string, body any, retry bool) (int, []byte, error) { status, payload, err := c.roundTrip(ctx, method, path, body) if err != nil { return 0, nil, err } if status == http.StatusUnauthorized && retry && path != "/api/admin/login" { if err := c.login(ctx); err != nil { return 0, nil, err } return c.do(ctx, method, path, body, false) } return status, payload, nil } func (c *Client) login(ctx context.Context) error { c.mu.Lock() defer c.mu.Unlock() status, payload, err := c.roundTrip(ctx, http.MethodPost, "/api/admin/login", map[string]string{ "username": c.username, "password": c.password, }) if err != nil { return err } if status != http.StatusOK { return &APIError{Status: status, Message: "nixmsg login failed"} } var env struct { OK bool `json:"ok"` } if err := json.Unmarshal(payload, &env); err != nil || !env.OK { return errors.New("nixmsg login failed") } c.loggedIn = true return nil } func (c *Client) roundTrip(ctx context.Context, method, path string, body any) (int, []byte, error) { var reader io.Reader if body != nil { raw, err := json.Marshal(body) if err != nil { return 0, nil, err } reader = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader) if err != nil { return 0, nil, err } if body != nil { req.Header.Set("Content-Type", "application/json") } if method != http.MethodGet && method != http.MethodHead && path != "/api/admin/login" { req.Header.Set("X-Nixmsg-Request", "1") } resp, err := c.http.Do(req) if err != nil { return 0, nil, err } defer resp.Body.Close() payload, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return 0, nil, err } return resp.StatusCode, payload, nil }