// Package api talks to the LAN-Clipboard server with a device token. package api import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "runtime" "strings" "time" "github.com/coder/websocket" ) // ErrUnauthorized means the token is invalid, revoked or its user deactivated. var ErrUnauthorized = errors.New("Token ungültig oder widerrufen") const ( closeUnauthorized = 4401 // The server pings every 30 s; silence beyond this means the connection is dead readTimeout = 75 * time.Second // Largest event: a clip of up to 200,000 characters, JSON-escaped maxMessageBytes = 4 << 20 ) type Clip struct { ID int64 `json:"id"` UserID int64 `json:"user_id"` Kind string `json:"kind"` Content string `json:"content"` ProjectID *int64 `json:"project_id"` } type Project struct { ID int64 `json:"id"` Name string `json:"name"` Role string `json:"role"` } type User struct { ID int64 `json:"id"` Username string `json:"username"` } // Event is a live-sync message, e.g. {"type": "clip.created", "data": {...}}. type Event struct { Type string `json:"type"` Data json.RawMessage `json:"data"` } type Client struct { base *url.URL token string userAgent string http *http.Client } func New(server, token, version string) (*Client, error) { base, err := url.Parse(strings.TrimRight(server, "/")) if err != nil { return nil, err } return &Client{ base: base, token: token, userAgent: fmt.Sprintf("lc-agent/%s (%s)", version, runtime.GOOS), http: &http.Client{Timeout: 30 * time.Second}, }, nil } func (c *Client) do(ctx context.Context, method, path string, body, out any) error { var reader io.Reader if body != nil { data, err := json.Marshal(body) if err != nil { return err } reader = bytes.NewReader(data) } req, err := http.NewRequestWithContext(ctx, method, c.base.String()+path, reader) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+c.token) req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", c.userAgent) if body != nil { req.Header.Set("Content-Type", "application/json") } resp, err := c.http.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusUnauthorized { return ErrUnauthorized } if resp.StatusCode >= 300 { return fmt.Errorf("%s %s: %s", method, path, errorDetail(resp)) } if out == nil { return nil } return json.NewDecoder(resp.Body).Decode(out) } func errorDetail(resp *http.Response) string { var payload struct { Detail any `json:"detail"` } data, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) if json.Unmarshal(data, &payload) == nil { if s, ok := payload.Detail.(string); ok { return fmt.Sprintf("%d %s", resp.StatusCode, s) } } return resp.Status } func (c *Client) Me(ctx context.Context) (User, error) { var user User return user, c.do(ctx, http.MethodGet, "/api/users/me", nil, &user) } func (c *Client) Projects(ctx context.Context) ([]Project, error) { var projects []Project return projects, c.do(ctx, http.MethodGet, "/api/projects", nil, &projects) } func (c *Client) CreateProject(ctx context.Context, name string) (Project, error) { var project Project return project, c.do(ctx, http.MethodPost, "/api/projects", map[string]string{"name": name}, &project) } func (c *Client) CreateClip(ctx context.Context, content string, projectID *int64) (Clip, error) { var clip Clip body := map[string]any{"content": content, "kind": "text", "project_id": projectID} return clip, c.do(ctx, http.MethodPost, "/api/clips", body, &clip) } // DeleteClip deletes a clip; one that is already gone counts as success. func (c *Client) DeleteClip(ctx context.Context, id int64) error { err := c.do(ctx, http.MethodDelete, fmt.Sprintf("/api/clips/%d", id), nil, nil) if err != nil && strings.Contains(err.Error(), ": 404") { return nil } return err } // Events connects to the live sync and calls handle for every message until the // connection ends. It returns ErrUnauthorized if the server rejects the token. func (c *Client) Events(ctx context.Context, handle func(Event)) error { wsURL := *c.base wsURL.Scheme = map[string]string{"https": "wss", "http": "ws"}[c.base.Scheme] wsURL.Path += "/api/ws" header := http.Header{} header.Set("Authorization", "Bearer "+c.token) header.Set("User-Agent", c.userAgent) conn, resp, err := websocket.Dial(ctx, wsURL.String(), &websocket.DialOptions{HTTPHeader: header}) if err != nil { if resp != nil && resp.StatusCode == http.StatusUnauthorized { return ErrUnauthorized } return err } defer conn.CloseNow() conn.SetReadLimit(maxMessageBytes) for { readCtx, cancel := context.WithTimeout(ctx, readTimeout) _, data, err := conn.Read(readCtx) cancel() if err != nil { if websocket.CloseStatus(err) == closeUnauthorized { return ErrUnauthorized } return err } var event Event if json.Unmarshal(data, &event) == nil { handle(event) } } }