Move to Federated Gitea

This commit is contained in:
2026-04-29 06:55:00 -06:00
commit 0aac727cc1
18 changed files with 3208 additions and 0 deletions
+112
View File
@@ -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...))
}
+137
View File
@@ -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"`
}
+254
View File
@@ -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
}
+124
View File
@@ -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
}