Move to Federated Gitea
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
|
||||
"coremarketing/internal/models"
|
||||
)
|
||||
|
||||
const systemPrompt = `You are a product manager at a company that champions open source software. You write posts for X.com (Twitter) to help users get more value from open source SaaS applications.
|
||||
|
||||
Your voice:
|
||||
- Knowledgeable but approachable — you know this product deeply and want to share that knowledge
|
||||
- Practical — you share specific workflows, features, and tips users can immediately apply
|
||||
- Community-minded — you reference the broader ecosystem and encourage engagement
|
||||
- Authentic — no corporate buzzwords, write like a real PM sharing genuine insights
|
||||
|
||||
Your posts should:
|
||||
- Lead with the most valuable insight or tip
|
||||
- Be specific rather than generic
|
||||
- Include a call to action when appropriate (question, try it yourself, share your experience)
|
||||
- Stay within the character limit INCLUDING hashtags
|
||||
- End with 2-3 relevant hashtags
|
||||
- May include 1-2 emojis for visual interest
|
||||
|
||||
Output ONLY the post text. No explanations, no alternatives — just the post.`
|
||||
|
||||
type Client struct {
|
||||
client *anthropic.Client
|
||||
model string
|
||||
maxLength int
|
||||
logFile string
|
||||
}
|
||||
|
||||
func New(apiKey, model, stateDir string, maxLength int) *Client {
|
||||
c := anthropic.NewClient(option.WithAPIKey(apiKey))
|
||||
return &Client{
|
||||
client: c,
|
||||
model: model,
|
||||
maxLength: maxLength,
|
||||
logFile: stateDir + "/coremarketing.log",
|
||||
}
|
||||
}
|
||||
|
||||
// GeneratePost creates a post in the voice of a product manager based on selected content.
|
||||
func (c *Client) GeneratePost(ctx context.Context, app *models.Application, items []models.ContentItem) (string, error) {
|
||||
// Combine system instructions with the user prompt in a single user message.
|
||||
// This avoids SDK version ambiguity around the System parameter content block type.
|
||||
fullPrompt := systemPrompt + "\n\n---\n\n" + c.buildUserPrompt(app, items)
|
||||
|
||||
msg, err := c.client.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.F(c.model),
|
||||
MaxTokens: anthropic.F(int64(512)),
|
||||
Messages: anthropic.F([]anthropic.MessageParam{
|
||||
anthropic.NewUserMessage(anthropic.NewTextBlock(fullPrompt)),
|
||||
}),
|
||||
})
|
||||
if err != nil {
|
||||
c.log("GeneratePost error: %v", err)
|
||||
return "", fmt.Errorf("claude API: %w", err)
|
||||
}
|
||||
|
||||
for _, block := range msg.Content {
|
||||
if block.Type == "text" {
|
||||
return strings.TrimSpace(block.Text), nil
|
||||
}
|
||||
}
|
||||
|
||||
c.log("GeneratePost: no text block in response (stop_reason=%s)", msg.StopReason)
|
||||
return "", fmt.Errorf("no text content in claude response (stop_reason=%s)", msg.StopReason)
|
||||
}
|
||||
|
||||
func (c *Client) buildUserPrompt(app *models.Application, items []models.ContentItem) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(fmt.Sprintf("Application: %s\n", app.Name))
|
||||
sb.WriteString(fmt.Sprintf("Description: %s\n\n", app.Description))
|
||||
sb.WriteString(fmt.Sprintf("Character limit: %d\n\n", c.maxLength))
|
||||
sb.WriteString("Selected content from social media and community:\n\n")
|
||||
|
||||
for i, item := range items {
|
||||
sb.WriteString(fmt.Sprintf("--- Item %d [%s] ---\n", i+1, string(item.Source)))
|
||||
if item.Title != "" {
|
||||
sb.WriteString(fmt.Sprintf("Title: %s\n", item.Title))
|
||||
}
|
||||
sb.WriteString(fmt.Sprintf("Author: @%s\n", item.AuthorHandle))
|
||||
sb.WriteString(fmt.Sprintf("Date: %s\n", item.PublishedAt.Format("Jan 2, 2006")))
|
||||
sb.WriteString(fmt.Sprintf("Content: %s\n", item.Body))
|
||||
sb.WriteString(fmt.Sprintf("URL: %s\n\n", item.URL))
|
||||
}
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"Based on this content, write ONE X.com post (max %d characters including hashtags) in the voice of a product manager helping users better use %s.",
|
||||
c.maxLength, app.Name,
|
||||
))
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func (c *Client) log(format string, args ...any) {
|
||||
f, err := os.OpenFile(c.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
fmt.Fprintf(f, "[%s] %s\n", time.Now().Format(time.RFC3339), fmt.Sprintf(format, args...))
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package linkedin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
apiBase = "https://api.linkedin.com"
|
||||
linkedinVersion = "202501"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
accessToken string
|
||||
authorURN string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(accessToken, authorURN string) *Client {
|
||||
return &Client{
|
||||
accessToken: accessToken,
|
||||
authorURN: authorURN,
|
||||
http: &http.Client{Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// PostUpdate creates a LinkedIn post. If sourceURL is non-empty it is attached
|
||||
// as an article card (LinkedIn will fetch the title and thumbnail automatically).
|
||||
func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string, error) {
|
||||
pr := postRequest{
|
||||
Author: c.authorURN,
|
||||
Commentary: text,
|
||||
Visibility: "PUBLIC",
|
||||
Distribution: distribution{
|
||||
FeedDistribution: "MAIN_FEED",
|
||||
TargetEntities: []any{},
|
||||
ThirdPartyDistributionChannels: []any{},
|
||||
},
|
||||
LifecycleState: "PUBLISHED",
|
||||
IsReshareDisabledByAuthor: false,
|
||||
}
|
||||
if sourceURL != "" {
|
||||
pr.Content = &postContent{Article: articleContent{Source: sourceURL}}
|
||||
}
|
||||
|
||||
body, err := json.Marshal(pr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBase+"/rest/posts", strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.accessToken)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("LinkedIn-Version", linkedinVersion)
|
||||
req.Header.Set("X-Restli-Protocol-Version", "2.0.0")
|
||||
|
||||
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("linkedin HTTP %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
|
||||
postID := res.Header.Get("X-RestLi-Id")
|
||||
if postID == "" {
|
||||
return "", nil
|
||||
}
|
||||
return "https://www.linkedin.com/feed/update/" + postID + "/", nil
|
||||
}
|
||||
|
||||
// GetAuthorURN fetches the LinkedIn person URN for the owner of accessToken.
|
||||
func GetAuthorURN(ctx context.Context, accessToken string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/v2/userinfo", nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("userinfo HTTP %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
|
||||
var info struct {
|
||||
Sub string `json:"sub"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &info); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if info.Sub == "" {
|
||||
return "", fmt.Errorf("no sub in userinfo response: %s", raw)
|
||||
}
|
||||
return "urn:li:person:" + info.Sub, nil
|
||||
}
|
||||
|
||||
type postRequest struct {
|
||||
Author string `json:"author"`
|
||||
Commentary string `json:"commentary"`
|
||||
Visibility string `json:"visibility"`
|
||||
Distribution distribution `json:"distribution"`
|
||||
Content *postContent `json:"content,omitempty"`
|
||||
LifecycleState string `json:"lifecycleState"`
|
||||
IsReshareDisabledByAuthor bool `json:"isReshareDisabledByAuthor"`
|
||||
}
|
||||
|
||||
type distribution struct {
|
||||
FeedDistribution string `json:"feedDistribution"`
|
||||
TargetEntities []any `json:"targetEntities"`
|
||||
ThirdPartyDistributionChannels []any `json:"thirdPartyDistributionChannels"`
|
||||
}
|
||||
|
||||
type postContent struct {
|
||||
Article articleContent `json:"article"`
|
||||
}
|
||||
|
||||
type articleContent struct {
|
||||
Source string `json:"source"`
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package youtube
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"coremarketing/internal/models"
|
||||
)
|
||||
|
||||
const apiBase = "https://www.googleapis.com/youtube/v3"
|
||||
|
||||
type Client struct {
|
||||
apiKey string
|
||||
maxResults int
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func New(apiKey string, maxResults int) *Client {
|
||||
return &Client{
|
||||
apiKey: apiKey,
|
||||
maxResults: maxResults,
|
||||
http: &http.Client{Timeout: 15 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// SearchVideos searches YouTube for videos matching the query published after `since`.
|
||||
func (c *Client) SearchVideos(ctx context.Context, query string, since time.Time, appName string) ([]models.ContentItem, error) {
|
||||
params := url.Values{
|
||||
"part": {"snippet"},
|
||||
"q": {query},
|
||||
"type": {"video"},
|
||||
"order": {"date"},
|
||||
"publishedAfter": {since.UTC().Format(time.RFC3339)},
|
||||
"maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))},
|
||||
"key": {c.apiKey},
|
||||
}
|
||||
return c.doSearch(ctx, params, appName)
|
||||
}
|
||||
|
||||
// GetChannelVideos fetches recent videos from a specific YouTube channel.
|
||||
func (c *Client) GetChannelVideos(ctx context.Context, channelID string, since time.Time, appName string) ([]models.ContentItem, error) {
|
||||
params := url.Values{
|
||||
"part": {"snippet"},
|
||||
"channelId": {channelID},
|
||||
"type": {"video"},
|
||||
"order": {"date"},
|
||||
"publishedAfter": {since.UTC().Format(time.RFC3339)},
|
||||
"maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))},
|
||||
"key": {c.apiKey},
|
||||
}
|
||||
return c.doSearch(ctx, params, appName)
|
||||
}
|
||||
|
||||
func (c *Client) doSearch(ctx context.Context, params url.Values, appName string) ([]models.ContentItem, error) {
|
||||
endpoint := apiBase + "/search?" + params.Encode()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("youtube HTTP %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
|
||||
var resp searchResponse
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var items []models.ContentItem
|
||||
for _, r := range resp.Items {
|
||||
ts, _ := time.Parse(time.RFC3339, r.Snippet.PublishedAt)
|
||||
videoURL := "https://www.youtube.com/watch?v=" + r.ID.VideoID
|
||||
items = append(items, models.ContentItem{
|
||||
ID: r.ID.VideoID,
|
||||
Source: models.SourceYouTube,
|
||||
Author: r.Snippet.ChannelTitle,
|
||||
AuthorHandle: r.Snippet.ChannelTitle,
|
||||
Title: r.Snippet.Title,
|
||||
Body: r.Snippet.Description,
|
||||
URL: videoURL,
|
||||
PublishedAt: ts,
|
||||
AppName: appName,
|
||||
})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
type searchResponse struct {
|
||||
Items []struct {
|
||||
ID struct {
|
||||
VideoID string `json:"videoId"`
|
||||
} `json:"id"`
|
||||
Snippet struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
ChannelTitle string `json:"channelTitle"`
|
||||
PublishedAt string `json:"publishedAt"`
|
||||
} `json:"snippet"`
|
||||
} `json:"items"`
|
||||
}
|
||||
|
||||
func clamp(v, min, max int) int {
|
||||
if v < min {
|
||||
return min
|
||||
}
|
||||
if v > max {
|
||||
return max
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
authURL = "https://twitter.com/i/oauth2/authorize"
|
||||
tokenURL = "https://api.twitter.com/2/oauth2/token"
|
||||
redirectURI = "http://localhost:8080/callback"
|
||||
scopes = "tweet.read tweet.write users.read"
|
||||
)
|
||||
|
||||
type Result struct {
|
||||
AccessToken string
|
||||
}
|
||||
|
||||
// TwitterOAuth2 runs the OAuth 2.0 PKCE flow for Twitter/X. It opens the
|
||||
// browser, starts a local callback server on :8080, and exchanges the
|
||||
// authorization code for a user access token.
|
||||
func TwitterOAuth2(ctx context.Context, clientID, clientSecret string) (*Result, error) {
|
||||
verifier, challenge, state, err := generatePKCE()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating PKCE values: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {clientID},
|
||||
"redirect_uri": {redirectURI},
|
||||
"scope": {scopes},
|
||||
"state": {state},
|
||||
"code_challenge": {challenge},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
authFullURL := authURL + "?" + params.Encode()
|
||||
|
||||
codeCh := make(chan string, 1)
|
||||
errCh := make(chan error, 1)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
srv := &http.Server{Addr: ":8080", Handler: mux}
|
||||
|
||||
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("state") != state {
|
||||
http.Error(w, "state mismatch", http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("OAuth state mismatch — possible CSRF")
|
||||
return
|
||||
}
|
||||
if e := q.Get("error"); e != "" {
|
||||
http.Error(w, e, http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("authorization denied: %s", e)
|
||||
return
|
||||
}
|
||||
code := q.Get("code")
|
||||
if code == "" {
|
||||
http.Error(w, "missing code", http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("no code in OAuth callback")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprintln(w, "<html><body><h2>Authorization successful!</h2><p>You can close this tab.</p></body></html>")
|
||||
codeCh <- code
|
||||
})
|
||||
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
errCh <- fmt.Errorf("local callback server: %w", err)
|
||||
}
|
||||
}()
|
||||
defer srv.Shutdown(context.Background())
|
||||
|
||||
fmt.Printf("Open this URL in your browser to authorize:\n\n %s\n\n", authFullURL)
|
||||
|
||||
var code string
|
||||
select {
|
||||
case code = <-codeCh:
|
||||
case err = <-errCh:
|
||||
return nil, err
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(5 * time.Minute):
|
||||
return nil, fmt.Errorf("timed out waiting for authorization")
|
||||
}
|
||||
|
||||
return exchangeCode(ctx, clientID, clientSecret, code, verifier)
|
||||
}
|
||||
|
||||
func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier string) (*Result, error) {
|
||||
data := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {redirectURI},
|
||||
"code_verifier": {verifier},
|
||||
}
|
||||
if clientSecret == "" {
|
||||
data.Set("client_id", clientID)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(data.Encode()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
if clientSecret != "" {
|
||||
req.SetBasicAuth(clientID, clientSecret)
|
||||
}
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("token exchange HTTP %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
|
||||
var out struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out.AccessToken == "" {
|
||||
return nil, fmt.Errorf("no access_token in response: %s", raw)
|
||||
}
|
||||
return &Result{AccessToken: out.AccessToken}, nil
|
||||
}
|
||||
|
||||
// LinkedInOAuth2 runs the standard OAuth 2.0 authorization code flow for
|
||||
// LinkedIn. Unlike Twitter, LinkedIn uses client_secret instead of PKCE.
|
||||
func LinkedInOAuth2(ctx context.Context, clientID, clientSecret string) (*Result, error) {
|
||||
state, err := generateState()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating state: %w", err)
|
||||
}
|
||||
|
||||
params := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {clientID},
|
||||
"redirect_uri": {redirectURI},
|
||||
"scope": {"w_member_social openid profile"},
|
||||
"state": {state},
|
||||
}
|
||||
authFullURL := "https://www.linkedin.com/oauth/v2/authorization?" + params.Encode()
|
||||
|
||||
codeCh := make(chan string, 1)
|
||||
errCh := make(chan error, 1)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
srv := &http.Server{Addr: ":8080", Handler: mux}
|
||||
|
||||
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
if q.Get("state") != state {
|
||||
http.Error(w, "state mismatch", http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("OAuth state mismatch — possible CSRF")
|
||||
return
|
||||
}
|
||||
if e := q.Get("error"); e != "" {
|
||||
http.Error(w, e, http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("authorization denied: %s", e)
|
||||
return
|
||||
}
|
||||
code := q.Get("code")
|
||||
if code == "" {
|
||||
http.Error(w, "missing code", http.StatusBadRequest)
|
||||
errCh <- fmt.Errorf("no code in OAuth callback")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprintln(w, "<html><body><h2>Authorization successful!</h2><p>You can close this tab.</p></body></html>")
|
||||
codeCh <- code
|
||||
})
|
||||
|
||||
go func() {
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
errCh <- fmt.Errorf("local callback server: %w", err)
|
||||
}
|
||||
}()
|
||||
defer srv.Shutdown(context.Background())
|
||||
|
||||
fmt.Printf("Open this URL in your browser to authorize LinkedIn:\n\n %s\n\n", authFullURL)
|
||||
|
||||
var code string
|
||||
select {
|
||||
case code = <-codeCh:
|
||||
case err = <-errCh:
|
||||
return nil, err
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(5 * time.Minute):
|
||||
return nil, fmt.Errorf("timed out waiting for authorization")
|
||||
}
|
||||
|
||||
return linkedinExchangeCode(ctx, clientID, clientSecret, code)
|
||||
}
|
||||
|
||||
func linkedinExchangeCode(ctx context.Context, clientID, clientSecret, code string) (*Result, error) {
|
||||
data := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {redirectURI},
|
||||
"client_id": {clientID},
|
||||
"client_secret": {clientSecret},
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
"https://www.linkedin.com/oauth/v2/accessToken",
|
||||
strings.NewReader(data.Encode()),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
raw, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("token exchange HTTP %d: %s", res.StatusCode, raw)
|
||||
}
|
||||
|
||||
var out struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if out.AccessToken == "" {
|
||||
return nil, fmt.Errorf("no access_token in response: %s", raw)
|
||||
}
|
||||
return &Result{AccessToken: out.AccessToken}, nil
|
||||
}
|
||||
|
||||
func generatePKCE() (verifier, challenge, state string, err error) {
|
||||
vb := make([]byte, 32)
|
||||
if _, err = rand.Read(vb); err != nil {
|
||||
return
|
||||
}
|
||||
verifier = base64.RawURLEncoding.EncodeToString(vb)
|
||||
h := sha256.Sum256([]byte(verifier))
|
||||
challenge = base64.RawURLEncoding.EncodeToString(h[:])
|
||||
state, err = generateState()
|
||||
return
|
||||
}
|
||||
|
||||
func generateState() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"coremarketing/internal/models"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type TwitterCreds struct {
|
||||
BearerToken string `yaml:"bearer_token"`
|
||||
ClientID string `yaml:"client_id"`
|
||||
ClientSecret string `yaml:"client_secret"`
|
||||
OAuth2AccessToken string `yaml:"oauth2_access_token"`
|
||||
}
|
||||
|
||||
type YouTubeCreds struct {
|
||||
APIKey string `yaml:"api_key"`
|
||||
}
|
||||
|
||||
type ClaudeCreds struct {
|
||||
APIKey string `yaml:"api_key"`
|
||||
Model string `yaml:"model"`
|
||||
}
|
||||
|
||||
type LinkedInCreds struct {
|
||||
ClientID string `yaml:"client_id"`
|
||||
ClientSecret string `yaml:"client_secret"`
|
||||
AccessToken string `yaml:"access_token"`
|
||||
AuthorURN string `yaml:"author_urn"`
|
||||
}
|
||||
|
||||
type Credentials struct {
|
||||
Twitter TwitterCreds `yaml:"twitter"`
|
||||
LinkedIn LinkedInCreds `yaml:"linkedin"`
|
||||
YouTube YouTubeCreds `yaml:"youtube"`
|
||||
Claude ClaudeCreds `yaml:"claude"`
|
||||
}
|
||||
|
||||
type PostingConfig struct {
|
||||
TwitterHandle string `yaml:"twitter_handle"`
|
||||
MaxLength int `yaml:"max_length"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
StateFile string `yaml:"state_file"`
|
||||
MaxResults int `yaml:"max_results"`
|
||||
DefaultLookbackDays int `yaml:"default_lookback_days"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Applications []models.Application `yaml:"applications"`
|
||||
Credentials Credentials `yaml:"credentials"`
|
||||
Posting PostingConfig `yaml:"posting"`
|
||||
Settings Settings `yaml:"settings"`
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("parsing config file: %w", err)
|
||||
}
|
||||
|
||||
if err := cfg.setDefaults(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
func (c *Config) setDefaults() error {
|
||||
if len(c.Applications) == 0 {
|
||||
return fmt.Errorf("no applications configured in config.yaml")
|
||||
}
|
||||
if c.Credentials.Claude.APIKey == "" {
|
||||
return fmt.Errorf("credentials.claude.api_key is required")
|
||||
}
|
||||
if c.Credentials.Claude.Model == "" {
|
||||
c.Credentials.Claude.Model = "claude-sonnet-4-6"
|
||||
}
|
||||
if c.Settings.StateFile == "" {
|
||||
c.Settings.StateFile = "state.json"
|
||||
}
|
||||
if c.Settings.MaxResults == 0 {
|
||||
c.Settings.MaxResults = 20
|
||||
}
|
||||
if c.Settings.DefaultLookbackDays == 0 {
|
||||
c.Settings.DefaultLookbackDays = 7
|
||||
}
|
||||
if c.Posting.MaxLength == 0 {
|
||||
c.Posting.MaxLength = 280
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Config) HasTwitterRead() bool {
|
||||
return c.Credentials.Twitter.BearerToken != ""
|
||||
}
|
||||
|
||||
func (c *Config) HasTwitterPost() bool {
|
||||
return c.Credentials.Twitter.OAuth2AccessToken != ""
|
||||
}
|
||||
|
||||
func (c *Config) HasYouTube() bool {
|
||||
return c.Credentials.YouTube.APIKey != ""
|
||||
}
|
||||
|
||||
func (c *Config) HasLinkedInPost() bool {
|
||||
l := c.Credentials.LinkedIn
|
||||
return l.AccessToken != "" && l.AuthorURN != ""
|
||||
}
|
||||
|
||||
var (
|
||||
oauth2TokenRe = regexp.MustCompile(`oauth2_access_token:\s*"[^"]*"`)
|
||||
liAccessTokenRe = regexp.MustCompile(`access_token:\s*"[^"]*"`)
|
||||
liAuthorURNRe = regexp.MustCompile(`author_urn:\s*"[^"]*"`)
|
||||
liSectionRe = regexp.MustCompile(`^ linkedin:\s*$`)
|
||||
credentialSectionRe = regexp.MustCompile(`^ [a-z]`)
|
||||
)
|
||||
|
||||
// UpdateOAuth2Token rewrites the oauth2_access_token value in the named
|
||||
// config file in-place, preserving all other content and formatting.
|
||||
func UpdateOAuth2Token(path, token string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated := oauth2TokenRe.ReplaceAllLiteralString(string(data), `oauth2_access_token: "`+token+`"`)
|
||||
if updated == string(data) {
|
||||
return fmt.Errorf("oauth2_access_token field not found in %s", path)
|
||||
}
|
||||
return os.WriteFile(path, []byte(updated), 0600)
|
||||
}
|
||||
|
||||
// UpdateLinkedInCredentials rewrites the access_token and author_urn values
|
||||
// inside the linkedin credentials section, preserving all other content.
|
||||
func UpdateLinkedInCredentials(path, accessToken, authorURN string) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lines := strings.Split(string(data), "\n")
|
||||
result := make([]string, len(lines))
|
||||
inLinkedIn := false
|
||||
tokenDone, urnDone := false, false
|
||||
|
||||
for i, line := range lines {
|
||||
if liSectionRe.MatchString(line) {
|
||||
inLinkedIn = true
|
||||
result[i] = line
|
||||
continue
|
||||
}
|
||||
if inLinkedIn && credentialSectionRe.MatchString(line) {
|
||||
inLinkedIn = false
|
||||
}
|
||||
switch {
|
||||
case inLinkedIn && !tokenDone && strings.Contains(line, "access_token:"):
|
||||
result[i] = liAccessTokenRe.ReplaceAllLiteralString(line, `access_token: "`+accessToken+`"`)
|
||||
tokenDone = true
|
||||
case inLinkedIn && !urnDone && strings.Contains(line, "author_urn:"):
|
||||
result[i] = liAuthorURNRe.ReplaceAllLiteralString(line, `author_urn: "`+authorURN+`"`)
|
||||
urnDone = true
|
||||
default:
|
||||
result[i] = line
|
||||
}
|
||||
}
|
||||
|
||||
if !tokenDone || !urnDone {
|
||||
return fmt.Errorf("linkedin credentials fields not found in %s", path)
|
||||
}
|
||||
return os.WriteFile(path, []byte(strings.Join(result, "\n")), 0600)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package fetcher
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"coremarketing/internal/api/twitter"
|
||||
"coremarketing/internal/api/youtube"
|
||||
"coremarketing/internal/models"
|
||||
)
|
||||
|
||||
type Fetcher struct {
|
||||
twitter *twitter.Client
|
||||
youtube *youtube.Client
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Items []models.ContentItem
|
||||
Errors []string
|
||||
}
|
||||
|
||||
func New(tw *twitter.Client, yt *youtube.Client) *Fetcher {
|
||||
return &Fetcher{twitter: tw, youtube: yt}
|
||||
}
|
||||
|
||||
// FetchForApp concurrently fetches content from all configured sources.
|
||||
func (f *Fetcher) FetchForApp(ctx context.Context, app *models.Application, since time.Time) Result {
|
||||
type batch struct {
|
||||
items []models.ContentItem
|
||||
err error
|
||||
label string
|
||||
}
|
||||
|
||||
jobs := make(chan func() batch, 8)
|
||||
results := make(chan batch, 8)
|
||||
|
||||
// Worker pool
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 4; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for job := range jobs {
|
||||
results <- job()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Enqueue fetches
|
||||
enqueue := func(label string, fn func() ([]models.ContentItem, error)) {
|
||||
jobs <- func() batch {
|
||||
items, err := fn()
|
||||
return batch{items: items, err: err, label: label}
|
||||
}
|
||||
}
|
||||
|
||||
if f.twitter != nil && app.TwitterHandle != "" {
|
||||
enqueue("X (account @"+app.TwitterHandle+")", func() ([]models.ContentItem, error) {
|
||||
return f.twitter.GetUserTweets(ctx, app.TwitterHandle, since, app.Name)
|
||||
})
|
||||
}
|
||||
|
||||
if f.youtube != nil && app.YouTubeChannelID != "" {
|
||||
enqueue("YouTube (channel)", func() ([]models.ContentItem, error) {
|
||||
return f.youtube.GetChannelVideos(ctx, app.YouTubeChannelID, since, app.Name)
|
||||
})
|
||||
}
|
||||
|
||||
close(jobs)
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(results)
|
||||
}()
|
||||
|
||||
var result Result
|
||||
for b := range results {
|
||||
if b.err != nil {
|
||||
result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", b.label, b.err))
|
||||
} else {
|
||||
result.Items = append(result.Items, b.items...)
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicate by ID and sort newest first
|
||||
result.Items = dedup(result.Items)
|
||||
sort.Slice(result.Items, func(i, j int) bool {
|
||||
return result.Items[i].PublishedAt.After(result.Items[j].PublishedAt)
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func dedup(items []models.ContentItem) []models.ContentItem {
|
||||
seen := map[string]bool{}
|
||||
out := items[:0]
|
||||
for _, item := range items {
|
||||
if !seen[item.ID] {
|
||||
seen[item.ID] = true
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Application struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description"`
|
||||
TwitterHandle string `yaml:"twitter_handle"`
|
||||
YouTubeChannelID string `yaml:"youtube_channel_id"`
|
||||
Hashtags []string `yaml:"hashtags"`
|
||||
}
|
||||
|
||||
type ContentSource string
|
||||
|
||||
const (
|
||||
SourceTwitterAccount ContentSource = "X·Account"
|
||||
SourceTwitterSearch ContentSource = "X·Search"
|
||||
SourceYouTube ContentSource = "YouTube"
|
||||
)
|
||||
|
||||
type ContentItem struct {
|
||||
ID string
|
||||
Source ContentSource
|
||||
Author string
|
||||
AuthorHandle string
|
||||
Title string
|
||||
Body string
|
||||
URL string
|
||||
PublishedAt time.Time
|
||||
AppName string
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type State struct {
|
||||
LastChecked map[string]time.Time `json:"last_checked"`
|
||||
path string
|
||||
}
|
||||
|
||||
func Load(path string) (*State, error) {
|
||||
s := &State{
|
||||
LastChecked: make(map[string]time.Time),
|
||||
path: path,
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(data, s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.path = path
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *State) Save() error {
|
||||
data, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(s.path, data, 0644)
|
||||
}
|
||||
|
||||
func (s *State) GetLastChecked(appName string, lookbackDays int) time.Time {
|
||||
if t, ok := s.LastChecked[appName]; ok {
|
||||
return t
|
||||
}
|
||||
return time.Now().AddDate(0, 0, -lookbackDays)
|
||||
}
|
||||
|
||||
func (s *State) SetLastChecked(appName string, t time.Time) {
|
||||
s.LastChecked[appName] = t
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GeneratedPost struct {
|
||||
ID string `json:"id"`
|
||||
AppName string `json:"app_name"`
|
||||
Content string `json:"content"`
|
||||
SourceURL string `json:"source_url,omitempty"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
Posts []GeneratedPost `json:"posts"`
|
||||
path string
|
||||
}
|
||||
|
||||
func Load(path string) (*Store, error) {
|
||||
s := &Store{path: path}
|
||||
data, err := os.ReadFile(path)
|
||||
if os.IsNotExist(err) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := json.Unmarshal(data, s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.path = path
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) Save() error {
|
||||
data, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(s.path, data, 0644)
|
||||
}
|
||||
|
||||
func (s *Store) Add(appName, content, sourceURL string) {
|
||||
s.Posts = append(s.Posts, GeneratedPost{
|
||||
ID: fmt.Sprintf("%d", time.Now().UnixNano()),
|
||||
AppName: appName,
|
||||
Content: content,
|
||||
SourceURL: sourceURL,
|
||||
GeneratedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Store) Remove(ids map[string]bool) {
|
||||
kept := s.Posts[:0]
|
||||
for _, p := range s.Posts {
|
||||
if !ids[p.ID] {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
s.Posts = kept
|
||||
}
|
||||
+1013
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,85 @@
|
||||
package ui
|
||||
|
||||
import "github.com/charmbracelet/lipgloss"
|
||||
|
||||
var (
|
||||
colorPurple = lipgloss.Color("135")
|
||||
colorGreen = lipgloss.Color("82")
|
||||
colorRed = lipgloss.Color("196")
|
||||
colorYellow = lipgloss.Color("226")
|
||||
colorGray = lipgloss.Color("240")
|
||||
colorFaint = lipgloss.Color("238")
|
||||
colorWhite = lipgloss.Color("255")
|
||||
|
||||
titleStyle = lipgloss.NewStyle().
|
||||
Bold(true).
|
||||
Foreground(colorPurple).
|
||||
Padding(0, 1)
|
||||
|
||||
subtitleStyle = lipgloss.NewStyle().
|
||||
Foreground(colorGray).
|
||||
Padding(0, 1)
|
||||
|
||||
headerStyle = lipgloss.NewStyle().
|
||||
Bold(true).
|
||||
Foreground(colorWhite).
|
||||
Background(colorPurple).
|
||||
Padding(0, 2).
|
||||
Width(60)
|
||||
|
||||
statusBarStyle = lipgloss.NewStyle().
|
||||
Foreground(colorGray).
|
||||
Padding(0, 1)
|
||||
|
||||
keyStyle = lipgloss.NewStyle().
|
||||
Foreground(colorPurple).
|
||||
Bold(true)
|
||||
|
||||
keyDescStyle = lipgloss.NewStyle().
|
||||
Foreground(colorGray)
|
||||
|
||||
itemNormalStyle = lipgloss.NewStyle().
|
||||
PaddingLeft(2)
|
||||
|
||||
itemFocusedStyle = lipgloss.NewStyle().
|
||||
PaddingLeft(0).
|
||||
Foreground(colorPurple).
|
||||
SetString("▸ ")
|
||||
|
||||
itemSelectedStyle = lipgloss.NewStyle().
|
||||
PaddingLeft(2).
|
||||
Foreground(colorGreen)
|
||||
|
||||
itemSelectedFocusedStyle = lipgloss.NewStyle().
|
||||
PaddingLeft(0).
|
||||
Foreground(colorGreen).
|
||||
SetString("▸ ")
|
||||
|
||||
checkboxOn = lipgloss.NewStyle().Foreground(colorGreen).Render("●")
|
||||
checkboxOff = lipgloss.NewStyle().Foreground(colorGray).Render("○")
|
||||
|
||||
spinnerStyle = lipgloss.NewStyle().Foreground(colorPurple)
|
||||
|
||||
errorStyle = lipgloss.NewStyle().
|
||||
Foreground(colorRed).
|
||||
Bold(true)
|
||||
|
||||
successStyle = lipgloss.NewStyle().
|
||||
Foreground(colorGreen).
|
||||
Bold(true)
|
||||
|
||||
warningStyle = lipgloss.NewStyle().
|
||||
Foreground(colorYellow)
|
||||
|
||||
charCountOK = lipgloss.NewStyle().Foreground(colorGreen)
|
||||
charCountWarn = lipgloss.NewStyle().Foreground(colorYellow)
|
||||
charCountOver = lipgloss.NewStyle().Foreground(colorRed).Bold(true)
|
||||
|
||||
borderStyle = lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(colorFaint)
|
||||
)
|
||||
|
||||
func keyHint(key, desc string) string {
|
||||
return keyStyle.Render(key) + keyDescStyle.Render(" "+desc)
|
||||
}
|
||||
Reference in New Issue
Block a user