- Untrack config.yaml (now gitignored) and add config.example.yaml with blank credentials; install.sh copies the example and sets mode 600 - Reserve room for the appended source link when asking Claude for a post, count length the way X does, and refuse over-length tweets before posting - Return https://x.com/i/status/<id> for posted tweets - Track which platforms each queued post reached so a partial failure can be retried without double-posting - Write config, state, posts and dismissed files atomically with 0600 - Keep refreshed Twitter tokens in memory if saving them fails, and log the failure instead of writing to the hidden stderr - Exit with a clear message on corrupt data files instead of panicking - Surface save errors in the UI; show status/error messages on home - Add tests for X length counting, the post store, and token updates Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
289 lines
8.9 KiB
Go
289 lines
8.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
|
|
claudeapi "coremarketing/internal/api/claude"
|
|
linkedinapi "coremarketing/internal/api/linkedin"
|
|
"coremarketing/internal/api/twitter"
|
|
"coremarketing/internal/api/youtube"
|
|
"coremarketing/internal/auth"
|
|
"coremarketing/internal/config"
|
|
"coremarketing/internal/fetcher"
|
|
"coremarketing/internal/state"
|
|
"coremarketing/internal/store"
|
|
"coremarketing/internal/ui"
|
|
)
|
|
|
|
func main() {
|
|
cfgPath := filepath.Join(os.Getenv("HOME"), ".local", "state", "coremarketing", "config.yaml")
|
|
|
|
if len(os.Args) > 1 && os.Args[1] == "auth" {
|
|
rest := os.Args[2:]
|
|
if len(rest) == 0 {
|
|
fmt.Fprintf(os.Stderr, "Usage: coremarketing auth <twitter|linkedin> [config.yaml]\n")
|
|
os.Exit(1)
|
|
}
|
|
platform := rest[0]
|
|
rest = rest[1:]
|
|
if len(rest) > 0 {
|
|
cfgPath = rest[0]
|
|
}
|
|
switch platform {
|
|
case "twitter":
|
|
runAuth(cfgPath)
|
|
case "linkedin":
|
|
runLinkedInAuth(cfgPath)
|
|
default:
|
|
fmt.Fprintf(os.Stderr, "Unknown platform %q. Use twitter or linkedin.\n", platform)
|
|
os.Exit(1)
|
|
}
|
|
return
|
|
}
|
|
|
|
if len(os.Args) > 1 {
|
|
cfgPath = os.Args[1]
|
|
}
|
|
|
|
cfg, err := config.Load(cfgPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: %v\n\n", err)
|
|
fmt.Fprintf(os.Stderr, "Copy config.yaml and fill in your credentials.\n")
|
|
os.Exit(1)
|
|
}
|
|
|
|
// If Twitter is configured but has no access token, try a silent refresh
|
|
// first (if a refresh token is stored), then fall back to full re-auth.
|
|
if cfg.Credentials.Twitter.ClientID != "" && !cfg.HasTwitterPost() {
|
|
tw := cfg.Credentials.Twitter
|
|
if tw.OAuth2RefreshToken != "" {
|
|
result, err := auth.RefreshTwitterToken(context.Background(), tw.ClientID, tw.ClientSecret, tw.OAuth2RefreshToken)
|
|
if err == nil {
|
|
// Use the new tokens from memory rather than reloading the file,
|
|
// so a failed save doesn't also lose them for this session.
|
|
cfg.Credentials.Twitter.OAuth2AccessToken = result.AccessToken
|
|
if result.RefreshToken != "" {
|
|
cfg.Credentials.Twitter.OAuth2RefreshToken = result.RefreshToken
|
|
}
|
|
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
|
// X refresh tokens are single-use: the old one in the file is
|
|
// now dead, so the next launch will need `coremarketing auth twitter`.
|
|
fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token to %s: %v\n", cfgPath, saveErr)
|
|
fmt.Fprintf(os.Stderr, "You will need to run `coremarketing auth twitter` next time.\n")
|
|
}
|
|
} else {
|
|
fmt.Printf("Token refresh failed (%v), re-authorizing...\n", err)
|
|
runAuth(cfgPath)
|
|
cfg, err = config.Load(cfgPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
} else {
|
|
fmt.Println("No Twitter access token found. Starting authorization...")
|
|
runAuth(cfgPath)
|
|
cfg, err = config.Load(cfgPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Resolve data file paths relative to the config file so they're always
|
|
// written to the same place regardless of where the binary is invoked from.
|
|
cfgDir := filepath.Dir(cfgPath)
|
|
|
|
statePath := cfg.Settings.StateFile
|
|
if !filepath.IsAbs(statePath) {
|
|
statePath = filepath.Join(cfgDir, statePath)
|
|
}
|
|
|
|
postsPath := filepath.Join(cfgDir, "posts.json")
|
|
dismissedPath := filepath.Join(cfgDir, "dismissed.json")
|
|
|
|
// Refuse to start on an unreadable data file: carrying on with an empty
|
|
// store would overwrite it (and lose its contents) on the next save.
|
|
st, err := state.Load(statePath)
|
|
if err != nil {
|
|
dataFileError(statePath, err)
|
|
}
|
|
|
|
ps, err := store.Load(postsPath)
|
|
if err != nil {
|
|
dataFileError(postsPath, err)
|
|
}
|
|
|
|
ds, err := store.LoadDismissed(dismissedPath)
|
|
if err != nil {
|
|
dataFileError(dismissedPath, err)
|
|
}
|
|
|
|
// Build API clients — nil if credentials are missing
|
|
var twClient *twitter.Client
|
|
if cfg.HasTwitterRead() {
|
|
twClient = twitter.New(
|
|
cfg.Credentials.Twitter.BearerToken,
|
|
cfg.Credentials.Twitter.OAuth2AccessToken,
|
|
cfg.Settings.MaxResults,
|
|
)
|
|
if tw := cfg.Credentials.Twitter; tw.OAuth2RefreshToken != "" {
|
|
currentRefreshToken := tw.OAuth2RefreshToken
|
|
twClient.SetTokenRefresher(func(ctx context.Context) (string, string, error) {
|
|
result, err := auth.RefreshTwitterToken(ctx, tw.ClientID, tw.ClientSecret, currentRefreshToken)
|
|
if err != nil {
|
|
return "", "", err
|
|
}
|
|
if result.RefreshToken != "" {
|
|
currentRefreshToken = result.RefreshToken
|
|
}
|
|
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
|
// stderr is hidden behind the TUI's alt screen, so log it.
|
|
appendLog(cfgDir, "could not save refreshed Twitter token to %s: %v — run `coremarketing auth twitter` before next launch", cfgPath, saveErr)
|
|
}
|
|
return result.AccessToken, result.RefreshToken, nil
|
|
})
|
|
}
|
|
}
|
|
|
|
var ytClient *youtube.Client
|
|
if cfg.HasYouTube() {
|
|
ytClient = youtube.New(cfg.Credentials.YouTube.APIKey, cfg.Settings.MaxResults)
|
|
}
|
|
|
|
f := fetcher.New(twClient, ytClient)
|
|
|
|
cl := claudeapi.New(
|
|
cfg.Credentials.Claude.APIKey,
|
|
cfg.Credentials.Claude.Model,
|
|
cfgDir,
|
|
)
|
|
|
|
var poster twitterPoster
|
|
if cfg.HasTwitterPost() {
|
|
poster = twClient
|
|
}
|
|
|
|
var liPoster linkedinPoster
|
|
if cfg.HasLinkedInPost() {
|
|
liPoster = linkedinapi.New(
|
|
cfg.Credentials.LinkedIn.AccessToken,
|
|
cfg.Credentials.LinkedIn.AuthorURN,
|
|
)
|
|
}
|
|
|
|
model := ui.New(cfg, st, ps, ds, f, cl, poster, liPoster)
|
|
|
|
p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
|
|
if _, err := p.Run(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
// twitterPoster is the subset of twitter.Client used for posting.
|
|
type twitterPoster interface {
|
|
PostTweet(ctx context.Context, text string) (string, error)
|
|
}
|
|
|
|
// linkedinPoster is the subset of linkedin.Client used for posting.
|
|
type linkedinPoster interface {
|
|
PostUpdate(ctx context.Context, text, sourceURL string) (string, error)
|
|
}
|
|
|
|
func runLinkedInAuth(cfgPath string) {
|
|
cfg, err := config.Load(cfgPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if cfg.Credentials.LinkedIn.ClientID == "" || cfg.Credentials.LinkedIn.ClientSecret == "" {
|
|
fmt.Fprintf(os.Stderr, "Error: credentials.linkedin.client_id and client_secret must be set in %s\n", cfgPath)
|
|
os.Exit(1)
|
|
}
|
|
|
|
result, err := auth.LinkedInOAuth2(context.Background(),
|
|
cfg.Credentials.LinkedIn.ClientID,
|
|
cfg.Credentials.LinkedIn.ClientSecret,
|
|
)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Authorization failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
authorURN, err := linkedinapi.GetAuthorURN(context.Background(), result.AccessToken)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not fetch author URN: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Authorized as %s\n", authorURN)
|
|
|
|
if err := config.UpdateLinkedInCredentials(cfgPath, result.AccessToken, authorURN); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not save credentials: %v\n", err)
|
|
fmt.Printf("Add manually to %s:\n access_token: \"%s\"\n author_urn: \"%s\"\n", cfgPath, result.AccessToken, authorURN)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Success! LinkedIn credentials saved to %s\n", cfgPath)
|
|
}
|
|
|
|
func runAuth(cfgPath string) {
|
|
cfg, err := config.Load(cfgPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if cfg.Credentials.Twitter.ClientID == "" {
|
|
fmt.Fprintf(os.Stderr, "Error: credentials.twitter.client_id must be set in %s\n", cfgPath)
|
|
os.Exit(1)
|
|
}
|
|
|
|
result, err := auth.TwitterOAuth2(context.Background(),
|
|
cfg.Credentials.Twitter.ClientID,
|
|
cfg.Credentials.Twitter.ClientSecret,
|
|
)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Authorization failed: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Verify the token and show which account was authorized.
|
|
twClient := twitter.New("", result.AccessToken, 0)
|
|
username, err := twClient.VerifyCredentials(context.Background())
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: could not verify token: %v\n", err)
|
|
} else {
|
|
fmt.Printf("Authorized as @%s\n", username)
|
|
}
|
|
|
|
if err := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Could not save token automatically: %v\n", err)
|
|
fmt.Printf("\nAdd this to %s manually:\n oauth2_access_token: \"%s\"\n", cfgPath, result.AccessToken)
|
|
os.Exit(1)
|
|
}
|
|
|
|
fmt.Printf("Success! oauth2_access_token saved to %s\n", cfgPath)
|
|
}
|
|
|
|
func dataFileError(path string, err error) {
|
|
fmt.Fprintf(os.Stderr, "Error: could not load %s: %v\n", path, err)
|
|
fmt.Fprintf(os.Stderr, "Fix or move the file aside, then start again.\n")
|
|
os.Exit(1)
|
|
}
|
|
|
|
// appendLog writes a timestamped line to coremarketing.log in dir.
|
|
func appendLog(dir, format string, args ...any) {
|
|
f, err := os.OpenFile(filepath.Join(dir, "coremarketing.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer f.Close()
|
|
fmt.Fprintf(f, "[%s] %s\n", time.Now().Format(time.RFC3339), fmt.Sprintf(format, args...))
|
|
}
|