Move to Federated Gitea
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
package twitter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"coremarketing/internal/models"
|
||||
)
|
||||
|
||||
const apiBase = "https://api.twitter.com/2"
|
||||
|
||||
type Client struct {
|
||||
bearerToken string
|
||||
oauth2AccessToken string
|
||||
maxResults int
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
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.
|
||||
func (c *Client) PostTweet(ctx context.Context, text string) (string, 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 "", 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 "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != http.StatusCreated {
|
||||
return "", 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 "", err
|
||||
}
|
||||
return "https://x.com/" + out.Data.ID, 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
|
||||
}
|
||||
Reference in New Issue
Block a user