- handler panic log includes the stack trace and no longer the sender number - error and exception frames from the service are logged at Warn level - Listen looks the account up again after a connection loss (re-link) - document that received but unhandled messages are lost at shutdown Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
254 lines
6.6 KiB
Go
254 lines
6.6 KiB
Go
package signalbot
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Client talks to a signal-cli-rest-api service. It is safe for concurrent use.
|
|
//
|
|
// The linked account is looked up on first use and cached. Listen looks it
|
|
// up again after each connection loss; create a new Client to make Send and
|
|
// Groups use a newly linked account.
|
|
type Client struct {
|
|
base *url.URL
|
|
number string
|
|
http *http.Client
|
|
log *slog.Logger
|
|
|
|
minBackoff, maxBackoff time.Duration
|
|
|
|
mu sync.Mutex
|
|
acct *Account // resolved account, cached after the first success
|
|
}
|
|
|
|
// Option configures a Client.
|
|
type Option func(*Client)
|
|
|
|
// WithNumber selects the linked account to use, by phone number (E.164) or
|
|
// ACI. Without it, the service must have exactly one linked account.
|
|
func WithNumber(number string) Option { return func(c *Client) { c.number = number } }
|
|
|
|
// WithHTTPClient sets the HTTP client used for REST calls and the websocket
|
|
// handshake. The default is a client without timeout: use contexts.
|
|
func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.http = h } }
|
|
|
|
// WithLogger sets the logger used for reconnections and handler panics.
|
|
// The default is slog.Default().
|
|
func WithLogger(l *slog.Logger) Option { return func(c *Client) { c.log = l } }
|
|
|
|
// Account is a Signal account linked in the service. Number may be empty
|
|
// for accounts without a phone number; ACI may be empty on old service
|
|
// versions.
|
|
type Account struct {
|
|
Number string
|
|
ACI string
|
|
}
|
|
|
|
// id returns the identifier used in API paths and payloads.
|
|
func (a Account) id() string {
|
|
if a.Number != "" {
|
|
return a.Number
|
|
}
|
|
return a.ACI
|
|
}
|
|
|
|
// New returns a client for the service at baseURL (e.g.
|
|
// "http://signal-api:8080"). It does not contact the service.
|
|
func New(baseURL string, opts ...Option) (*Client, error) {
|
|
u, err := url.Parse(baseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("signalbot: invalid base URL: %w", err)
|
|
}
|
|
if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
return nil, fmt.Errorf("signalbot: invalid base URL %q: want http(s)://host[:port][/path]", baseURL)
|
|
}
|
|
u.Path = strings.TrimSuffix(u.Path, "/")
|
|
c := &Client{
|
|
base: u,
|
|
http: http.DefaultClient,
|
|
log: slog.Default(),
|
|
minBackoff: time.Second,
|
|
maxBackoff: 30 * time.Second,
|
|
}
|
|
for _, o := range opts {
|
|
o(c)
|
|
}
|
|
return c, nil
|
|
}
|
|
|
|
// endpoint joins path (which may carry a "?query") to the base URL.
|
|
func (c *Client) endpoint(path string) string {
|
|
p, q, _ := strings.Cut(path, "?")
|
|
u := *c.base
|
|
u.Path += p
|
|
u.RawPath = ""
|
|
u.RawQuery = q
|
|
return u.String()
|
|
}
|
|
|
|
// do performs a JSON request. in may be nil; out may be nil to ignore the body.
|
|
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
|
|
var body io.Reader
|
|
if in != nil {
|
|
b, err := json.Marshal(in)
|
|
if err != nil {
|
|
return fmt.Errorf("signalbot: encode request: %w", err)
|
|
}
|
|
body = bytes.NewReader(b)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, c.endpoint(path), body)
|
|
if err != nil {
|
|
return fmt.Errorf("signalbot: build request: %w", err)
|
|
}
|
|
if in != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
return unavailable(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
if err != nil {
|
|
return unavailable(err)
|
|
}
|
|
if resp.StatusCode >= 300 {
|
|
return apiError(resp.StatusCode, data)
|
|
}
|
|
if out == nil || len(bytes.TrimSpace(data)) == 0 {
|
|
return nil
|
|
}
|
|
if err := json.Unmarshal(data, out); err != nil {
|
|
return fmt.Errorf("signalbot: decode %s response: %w", path, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func apiError(status int, body []byte) *APIError {
|
|
var e struct {
|
|
Error string `json:"error"`
|
|
}
|
|
msg := strings.TrimSpace(string(body))
|
|
if json.Unmarshal(body, &e) == nil && e.Error != "" {
|
|
msg = e.Error
|
|
}
|
|
if msg == "" {
|
|
msg = http.StatusText(status)
|
|
}
|
|
return &APIError{StatusCode: status, Message: msg}
|
|
}
|
|
|
|
// Accounts lists the accounts linked in the service.
|
|
func (c *Client) Accounts(ctx context.Context) ([]Account, error) {
|
|
var raw []json.RawMessage
|
|
if err := c.do(ctx, http.MethodGet, "/v1/accounts", nil, &raw); err != nil {
|
|
return nil, err
|
|
}
|
|
accts := make([]Account, 0, len(raw))
|
|
for _, r := range raw {
|
|
var number string
|
|
if json.Unmarshal(r, &number) == nil {
|
|
accts = append(accts, Account{Number: number})
|
|
continue
|
|
}
|
|
var obj struct {
|
|
Number string `json:"number"`
|
|
ACI *string `json:"aci"`
|
|
}
|
|
if err := json.Unmarshal(r, &obj); err != nil {
|
|
return nil, fmt.Errorf("signalbot: decode account %s: %w", r, err)
|
|
}
|
|
a := Account{Number: obj.Number}
|
|
if obj.ACI != nil {
|
|
a.ACI = *obj.ACI
|
|
}
|
|
accts = append(accts, a)
|
|
}
|
|
return accts, nil
|
|
}
|
|
|
|
// forgetAccount drops the cached account so the next call looks it up again.
|
|
func (c *Client) forgetAccount() {
|
|
c.mu.Lock()
|
|
c.acct = nil
|
|
c.mu.Unlock()
|
|
}
|
|
|
|
// account resolves the account to use and caches it after the first success.
|
|
// The lock is not held during the lookup, so each caller's ctx applies; a
|
|
// concurrent duplicate lookup is harmless.
|
|
func (c *Client) account(ctx context.Context) (Account, error) {
|
|
c.mu.Lock()
|
|
cached := c.acct
|
|
c.mu.Unlock()
|
|
if cached != nil {
|
|
return *cached, nil
|
|
}
|
|
accts, err := c.Accounts(ctx)
|
|
if err != nil {
|
|
return Account{}, err
|
|
}
|
|
var found *Account
|
|
switch {
|
|
case c.number != "":
|
|
for i := range accts {
|
|
if accts[i].Number == c.number || accts[i].ACI == c.number {
|
|
found = &accts[i]
|
|
break
|
|
}
|
|
}
|
|
if found == nil {
|
|
return Account{}, fmt.Errorf("%w: %s", ErrNotLinked, c.number)
|
|
}
|
|
case len(accts) == 0:
|
|
return Account{}, ErrNotLinked
|
|
case len(accts) > 1:
|
|
return Account{}, ErrMultipleAccounts
|
|
default:
|
|
found = &accts[0]
|
|
}
|
|
c.mu.Lock()
|
|
c.acct = found
|
|
c.mu.Unlock()
|
|
return *found, nil
|
|
}
|
|
|
|
// LinkURI asks the service for a device-link URI ("sgnl://linkdevice?…") to
|
|
// be shown as a QR code and scanned from the phone holding the bot account.
|
|
func (c *Client) LinkURI(ctx context.Context, deviceName string) (string, error) {
|
|
var resp struct {
|
|
URI string `json:"device_link_uri"`
|
|
}
|
|
path := "/v1/qrcodelink/raw?device_name=" + url.QueryEscape(deviceName)
|
|
if err := c.do(ctx, http.MethodGet, path, nil, &resp); err != nil {
|
|
return "", err
|
|
}
|
|
if resp.URI == "" {
|
|
return "", errors.New("signalbot: empty device link URI")
|
|
}
|
|
return resp.URI, nil
|
|
}
|
|
|
|
// Ping checks that the service is reachable and the account is linked.
|
|
func (c *Client) Ping(ctx context.Context) error {
|
|
if err := c.do(ctx, http.MethodGet, "/v1/health", nil, nil); err != nil {
|
|
return err
|
|
}
|
|
_, err := c.account(ctx)
|
|
return err
|
|
}
|