Replace the old Go TUI with a web app (port 8470) that runs in a container as a CoreDesktop sibling: - cmd/supermarket server with htmx web UI: dashboard, company profile, inventory (partners/competitors), AI and credential settings, and a Core & Hermes page - SQLite storage and a secrets store under ~/.local/share/supermarket - AI providers (Anthropic, OpenAI-compatible) behind one interface - MCP server and a Hermes bridge to the Federated Core MCP hub - Import of the old Coremarketing TUI's state - install.sh / update.sh / lib.sh, Dockerfile, compose.yaml, the bin/supermarket launcher and hermes/setup.sh Posting is not wired back up yet; that comes in Phase 1. See PLAN.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
324 lines
9.0 KiB
Go
324 lines
9.0 KiB
Go
package twitter
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"supermarket/internal/models"
|
|
)
|
|
|
|
const apiBase = "https://api.twitter.com/2"
|
|
|
|
// TokenRefresher is called when PostTweet receives a 401. It should obtain a
|
|
// new access token (and optionally rotate the refresh token) and persist both.
|
|
type TokenRefresher func(ctx context.Context) (accessToken, refreshToken string, err error)
|
|
|
|
type Client struct {
|
|
bearerToken string
|
|
oauth2AccessToken string
|
|
maxResults int
|
|
http *http.Client
|
|
tokenRefresher TokenRefresher
|
|
}
|
|
|
|
// SetTokenRefresher registers a callback invoked automatically on 401 so that
|
|
// an expired OAuth2 access token is refreshed and the post is retried once.
|
|
func (c *Client) SetTokenRefresher(fn TokenRefresher) {
|
|
c.tokenRefresher = fn
|
|
}
|
|
|
|
func New(bearerToken, oauth2AccessToken string, maxResults int) *Client {
|
|
// Bearer tokens are raw base64 strings. If copied from a URL or form they
|
|
// may arrive URL-encoded (%2F, %3D, etc.) — decode to the raw form.
|
|
if decoded, err := url.QueryUnescape(bearerToken); err == nil {
|
|
bearerToken = decoded
|
|
}
|
|
return &Client{
|
|
bearerToken: bearerToken,
|
|
oauth2AccessToken: oauth2AccessToken,
|
|
maxResults: maxResults,
|
|
http: &http.Client{Timeout: 15 * time.Second},
|
|
}
|
|
}
|
|
|
|
// GetUserTweets fetches tweets from a specific account's timeline since `since`.
|
|
func (c *Client) GetUserTweets(ctx context.Context, handle string, since time.Time, appName string) ([]models.ContentItem, error) {
|
|
userID, err := c.lookupUserID(ctx, handle)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("lookup user %s: %w", handle, err)
|
|
}
|
|
|
|
endpoint := fmt.Sprintf("%s/users/%s/tweets", apiBase, userID)
|
|
params := url.Values{
|
|
"max_results": {strconv.Itoa(clamp(c.maxResults, 5, 100))},
|
|
"start_time": {since.UTC().Format(time.RFC3339)},
|
|
"tweet.fields": {"created_at,author_id,entities"},
|
|
"expansions": {"author_id"},
|
|
"exclude": {"retweets,replies"},
|
|
}
|
|
|
|
var resp tweetsResponse
|
|
if err := c.getBearer(ctx, endpoint+"?"+params.Encode(), &resp); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return c.tweetsToItems(resp, handle, models.SourceTwitterAccount, appName), nil
|
|
}
|
|
|
|
// SearchTweets searches recent tweets using the provided query since `since`.
|
|
func (c *Client) SearchTweets(ctx context.Context, query string, since time.Time, appName string) ([]models.ContentItem, error) {
|
|
endpoint := apiBase + "/tweets/search/recent"
|
|
params := url.Values{
|
|
"query": {query},
|
|
"max_results": {strconv.Itoa(clamp(c.maxResults, 10, 100))},
|
|
"start_time": {since.UTC().Format(time.RFC3339)},
|
|
"tweet.fields": {"created_at,author_id,entities"},
|
|
"expansions": {"author_id"},
|
|
}
|
|
|
|
var resp tweetsResponse
|
|
if err := c.getBearer(ctx, endpoint+"?"+params.Encode(), &resp); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return c.tweetsToItems(resp, "", models.SourceTwitterSearch, appName), nil
|
|
}
|
|
|
|
// PostTweet posts a tweet using OAuth 2.0 user context. On a 401 it attempts
|
|
// one automatic token refresh (if a TokenRefresher was registered) and retries.
|
|
func (c *Client) PostTweet(ctx context.Context, text string) (string, error) {
|
|
tweetURL, unauthorized, err := c.postTweet(ctx, text)
|
|
if unauthorized && c.tokenRefresher != nil {
|
|
newAccess, _, refreshErr := c.tokenRefresher(ctx)
|
|
if refreshErr != nil {
|
|
return "", fmt.Errorf("post tweet HTTP 401 and token refresh failed: %w", refreshErr)
|
|
}
|
|
c.oauth2AccessToken = newAccess
|
|
tweetURL, _, err = c.postTweet(ctx, text)
|
|
}
|
|
return tweetURL, err
|
|
}
|
|
|
|
func (c *Client) postTweet(ctx context.Context, text string) (tweetURL string, unauthorized bool, err error) {
|
|
endpoint := apiBase + "/tweets"
|
|
payload := map[string]string{"text": text}
|
|
body, _ := json.Marshal(payload)
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
|
|
|
|
res, err := c.http.Do(req)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
raw, _ := io.ReadAll(res.Body)
|
|
if res.StatusCode == http.StatusUnauthorized {
|
|
return "", true, fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
|
|
}
|
|
if res.StatusCode != http.StatusCreated {
|
|
return "", false, fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
|
|
}
|
|
|
|
var out struct {
|
|
Data struct {
|
|
ID string `json:"id"`
|
|
Text string `json:"text"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
return "", false, err
|
|
}
|
|
return "https://x.com/i/status/" + out.Data.ID, false, nil
|
|
}
|
|
|
|
// BuildSearchQuery constructs an X search query from hashtags.
|
|
func BuildSearchQuery(hashtags []string, excludeHandle string) string {
|
|
var terms []string
|
|
for _, h := range hashtags {
|
|
tag := strings.TrimPrefix(h, "#")
|
|
terms = append(terms, "#"+tag)
|
|
}
|
|
q := "(" + strings.Join(terms, " OR ") + ") -is:retweet lang:en"
|
|
if excludeHandle != "" {
|
|
q += " -from:" + excludeHandle
|
|
}
|
|
return q
|
|
}
|
|
|
|
// --- internal helpers ---
|
|
|
|
func (c *Client) lookupUserID(ctx context.Context, username string) (string, error) {
|
|
var resp struct {
|
|
Data struct {
|
|
ID string `json:"id"`
|
|
} `json:"data"`
|
|
}
|
|
endpoint := fmt.Sprintf("%s/users/by/username/%s", apiBase, username)
|
|
if err := c.getBearer(ctx, endpoint, &resp); err != nil {
|
|
return "", err
|
|
}
|
|
return resp.Data.ID, nil
|
|
}
|
|
|
|
// VerifyCredentials returns the username of the account the oauth2 token belongs to.
|
|
func (c *Client) VerifyCredentials(ctx context.Context) (string, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/users/me", nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
|
|
|
|
res, err := c.http.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
raw, _ := io.ReadAll(res.Body)
|
|
if res.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("HTTP %d: %s", res.StatusCode, raw)
|
|
}
|
|
var out struct {
|
|
Data struct {
|
|
Username string `json:"username"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(raw, &out); err != nil {
|
|
return "", err
|
|
}
|
|
return out.Data.Username, nil
|
|
}
|
|
|
|
func (c *Client) getBearer(ctx context.Context, endpoint string, out interface{}) error {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+c.bearerToken)
|
|
|
|
res, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
raw, _ := io.ReadAll(res.Body)
|
|
if res.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("twitter HTTP %d: %s", res.StatusCode, raw)
|
|
}
|
|
return json.Unmarshal(raw, out)
|
|
}
|
|
|
|
type tweetsResponse struct {
|
|
Data []struct {
|
|
ID string `json:"id"`
|
|
Text string `json:"text"`
|
|
CreatedAt string `json:"created_at"`
|
|
AuthorID string `json:"author_id"`
|
|
} `json:"data"`
|
|
Includes struct {
|
|
Users []struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Username string `json:"username"`
|
|
} `json:"users"`
|
|
} `json:"includes"`
|
|
}
|
|
|
|
func (c *Client) tweetsToItems(resp tweetsResponse, defaultHandle string, source models.ContentSource, appName string) []models.ContentItem {
|
|
userMap := map[string]struct{ name, username string }{}
|
|
for _, u := range resp.Includes.Users {
|
|
userMap[u.ID] = struct{ name, username string }{u.Name, u.Username}
|
|
}
|
|
|
|
var items []models.ContentItem
|
|
for _, t := range resp.Data {
|
|
u := userMap[t.AuthorID]
|
|
handle := u.username
|
|
if handle == "" {
|
|
handle = defaultHandle
|
|
}
|
|
name := u.name
|
|
if name == "" {
|
|
name = handle
|
|
}
|
|
|
|
ts, _ := time.Parse(time.RFC3339, t.CreatedAt)
|
|
items = append(items, models.ContentItem{
|
|
ID: t.ID,
|
|
Source: source,
|
|
Author: name,
|
|
AuthorHandle: handle,
|
|
Body: t.Text,
|
|
URL: fmt.Sprintf("https://x.com/%s/status/%s", handle, t.ID),
|
|
PublishedAt: ts,
|
|
AppName: appName,
|
|
})
|
|
}
|
|
return items
|
|
}
|
|
|
|
func clamp(v, min, max int) int {
|
|
if v < min {
|
|
return min
|
|
}
|
|
if v > max {
|
|
return max
|
|
}
|
|
return v
|
|
}
|
|
|
|
// URLLength is the fixed weight X assigns to any link (t.co wrapping).
|
|
const URLLength = 23
|
|
|
|
// TweetLength returns the length X will count for a post consisting of
|
|
// content followed by "\n\n" and sourceURL (when non-empty).
|
|
func TweetLength(content, sourceURL string) int {
|
|
n := weightedLength(content)
|
|
if sourceURL != "" {
|
|
n += 2 + URLLength
|
|
}
|
|
return n
|
|
}
|
|
|
|
// URLReserve is how many characters to hold back from the post limit so the
|
|
// source URL appended at posting time still fits.
|
|
func URLReserve(sourceURL string) int {
|
|
if sourceURL == "" {
|
|
return 0
|
|
}
|
|
return 2 + URLLength
|
|
}
|
|
|
|
// weightedLength approximates X's character counting: Latin and common
|
|
// punctuation count as 1, everything else (CJK, emoji, …) counts as 2. It may
|
|
// overcount multi-codepoint emoji, which errs on the side of fitting.
|
|
func weightedLength(s string) int {
|
|
n := 0
|
|
for _, r := range s {
|
|
switch {
|
|
case r <= 0x10FF,
|
|
r >= 0x2000 && r <= 0x200D,
|
|
r >= 0x2010 && r <= 0x201F,
|
|
r >= 0x2032 && r <= 0x2037:
|
|
n++
|
|
default:
|
|
n += 2
|
|
}
|
|
}
|
|
return n
|
|
}
|