Stop committing credentials; fix posting length, partial posts, and data safety
- 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>
This commit is contained in:
+11
@@ -0,0 +1,11 @@
|
||||
# Real credentials live here — copy config.example.yaml instead
|
||||
config.yaml
|
||||
|
||||
# Runtime data written next to the config file
|
||||
state.json
|
||||
posts.json
|
||||
dismissed.json
|
||||
coremarketing.log
|
||||
|
||||
# Build output
|
||||
/coremarketing
|
||||
@@ -12,7 +12,9 @@ A terminal UI app that monitors open source SaaS applications across X.com, YouT
|
||||
|
||||
**1. Configure credentials**
|
||||
|
||||
Edit `config.yaml` and fill in your API keys:
|
||||
`./install.sh` copies `config.example.yaml` to `~/.local/state/coremarketing/config.yaml` (the default location the app reads). Fill in your API keys there:
|
||||
|
||||
> **Never commit real credentials.** `config.yaml` is gitignored; only `config.example.yaml`, with blank credentials, belongs in the repo.
|
||||
|
||||
```yaml
|
||||
credentials:
|
||||
|
||||
@@ -235,7 +235,7 @@ credentials:
|
||||
claude:
|
||||
# Get your key at https://console.anthropic.com
|
||||
api_key: ""
|
||||
# Model to use for post generation (defaults to claude-3-5-sonnet-latest)
|
||||
# Model to use for post generation (defaults to claude-sonnet-4-6)
|
||||
model: "claude-sonnet-4-6"
|
||||
|
||||
posting:
|
||||
+3
-2
@@ -40,8 +40,9 @@ if [[ -d "$CONFIG_DIR" ]] && compgen -G "$CONFIG_DIR/*" > /dev/null 2>&1; then
|
||||
fi
|
||||
|
||||
if [[ ! -f "$CONFIG_DIR/config.yaml" ]]; then
|
||||
cp "$SCRIPT_DIR/config.yaml" "$CONFIG_DIR/config.yaml"
|
||||
echo "Config installed: $CONFIG_DIR/config.yaml"
|
||||
cp "$SCRIPT_DIR/config.example.yaml" "$CONFIG_DIR/config.yaml"
|
||||
chmod 600 "$CONFIG_DIR/config.yaml"
|
||||
echo "Config installed: $CONFIG_DIR/config.yaml — fill in your credentials there"
|
||||
else
|
||||
echo "Config already exists, skipping: $CONFIG_DIR/config.yaml"
|
||||
fi
|
||||
|
||||
@@ -34,25 +34,25 @@ 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 {
|
||||
func New(apiKey, model, stateDir string) *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) {
|
||||
// GeneratePost creates a post in the voice of a product manager based on
|
||||
// selected content. maxLength is the space available for the post text itself,
|
||||
// excluding anything appended at posting time (such as the source URL).
|
||||
func (c *Client) GeneratePost(ctx context.Context, app *models.Application, items []models.ContentItem, maxLength int) (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)
|
||||
fullPrompt := systemPrompt + "\n\n---\n\n" + c.buildUserPrompt(app, items, maxLength)
|
||||
|
||||
msg, err := c.client.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.F(c.model),
|
||||
@@ -76,11 +76,11 @@ func (c *Client) GeneratePost(ctx context.Context, app *models.Application, item
|
||||
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 {
|
||||
func (c *Client) buildUserPrompt(app *models.Application, items []models.ContentItem, maxLength int) 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(fmt.Sprintf("Character limit: %d\n\n", maxLength))
|
||||
sb.WriteString("Selected content from social media and community:\n\n")
|
||||
|
||||
for i, item := range items {
|
||||
@@ -96,14 +96,14 @@ func (c *Client) buildUserPrompt(app *models.Application, items []models.Content
|
||||
|
||||
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,
|
||||
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)
|
||||
f, err := os.OpenFile(c.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ func (c *Client) postTweet(ctx context.Context, text string) (tweetURL string, u
|
||||
if err := json.Unmarshal(raw, &out); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return "https://x.com/" + out.Data.ID, false, nil
|
||||
return "https://x.com/i/status/" + out.Data.ID, false, nil
|
||||
}
|
||||
|
||||
// BuildSearchQuery constructs an X search query from hashtags.
|
||||
@@ -280,3 +280,44 @@ func clamp(v, min, max int) int {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package twitter
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTweetLength(t *testing.T) {
|
||||
cases := []struct {
|
||||
content, url string
|
||||
want int
|
||||
}{
|
||||
{"hello", "", 5},
|
||||
{"hello", "https://example.com/a/very/long/path/that/x/shortens", 5 + 2 + 23},
|
||||
{"café — “quoted”", "", 15},
|
||||
{"🚀", "", 2},
|
||||
{"日本", "", 4},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := TweetLength(c.content, c.url); got != c.want {
|
||||
t.Errorf("TweetLength(%q, %q) = %d, want %d", c.content, c.url, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReservedLimitFits(t *testing.T) {
|
||||
url := "https://x.com/someone/status/123"
|
||||
limit := 280 - URLReserve(url)
|
||||
if got := TweetLength(strings.Repeat("a", limit), url); got != 280 {
|
||||
t.Errorf("post at reserved limit counts as %d, want 280", got)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"coremarketing/internal/fileutil"
|
||||
"coremarketing/internal/models"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -148,7 +149,7 @@ func UpdateOAuth2Tokens(path, accessToken, refreshToken string) error {
|
||||
updated = oauth2RefreshTokenRe.ReplaceAllLiteralString(updated, `oauth2_refresh_token: "`+refreshToken+`"`)
|
||||
}
|
||||
|
||||
return os.WriteFile(path, []byte(updated), 0600)
|
||||
return fileutil.WriteFileAtomic(path, []byte(updated), 0600)
|
||||
}
|
||||
|
||||
// UpdateLinkedInCredentials rewrites the access_token and author_urn values
|
||||
@@ -188,5 +189,5 @@ func UpdateLinkedInCredentials(path, accessToken, authorURN string) error {
|
||||
if !tokenDone || !urnDone {
|
||||
return fmt.Errorf("linkedin credentials fields not found in %s", path)
|
||||
}
|
||||
return os.WriteFile(path, []byte(strings.Join(result, "\n")), 0600)
|
||||
return fileutil.WriteFileAtomic(path, []byte(strings.Join(result, "\n")), 0600)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const sample = `credentials:
|
||||
twitter:
|
||||
oauth2_access_token: "old-access"
|
||||
oauth2_refresh_token: "old-refresh"
|
||||
linkedin:
|
||||
access_token: ""
|
||||
author_urn: ""
|
||||
`
|
||||
|
||||
func TestUpdateTokensDoesNotTouchOtherSections(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
if err := os.WriteFile(path, []byte(sample), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UpdateOAuth2Tokens(path, "new-access", "new-refresh"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := UpdateLinkedInCredentials(path, "li-token", "urn:li:person:1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(path)
|
||||
got := string(data)
|
||||
for _, want := range []string{
|
||||
`oauth2_access_token: "new-access"`,
|
||||
`oauth2_refresh_token: "new-refresh"`,
|
||||
` access_token: "li-token"`,
|
||||
`author_urn: "urn:li:person:1"`,
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package fileutil
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// WriteFileAtomic writes data to a temp file in the same directory and renames
|
||||
// it over path, so a crash mid-write never leaves a truncated file behind.
|
||||
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer os.Remove(tmpName) // no-op once the rename succeeds
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(tmpName, perm); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, path)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"coremarketing/internal/fileutil"
|
||||
|
||||
"encoding/json"
|
||||
"os"
|
||||
"time"
|
||||
@@ -35,7 +37,7 @@ func (s *State) Save() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(s.path, data, 0644)
|
||||
return fileutil.WriteFileAtomic(s.path, data, 0600)
|
||||
}
|
||||
|
||||
func (s *State) GetLastChecked(appName string, lookbackDays int) time.Time {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"coremarketing/internal/fileutil"
|
||||
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
@@ -34,7 +36,7 @@ func (s *DismissedStore) Save() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(s.path, data, 0644)
|
||||
return fileutil.WriteFileAtomic(s.path, data, 0600)
|
||||
}
|
||||
|
||||
func (s *DismissedStore) Dismiss(id string) {
|
||||
|
||||
+30
-1
@@ -1,6 +1,8 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"coremarketing/internal/fileutil"
|
||||
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -13,6 +15,24 @@ type GeneratedPost struct {
|
||||
Content string `json:"content"`
|
||||
SourceURL string `json:"source_url,omitempty"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
// PostedTo lists platforms this post has already been published to, so a
|
||||
// partial failure can be retried without double-posting elsewhere.
|
||||
PostedTo []string `json:"posted_to,omitempty"`
|
||||
}
|
||||
|
||||
// Platform identifiers recorded in GeneratedPost.PostedTo.
|
||||
const (
|
||||
PlatformX = "x"
|
||||
PlatformLinkedIn = "linkedin"
|
||||
)
|
||||
|
||||
func (p GeneratedPost) HasPosted(platform string) bool {
|
||||
for _, done := range p.PostedTo {
|
||||
if done == platform {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
@@ -41,7 +61,7 @@ func (s *Store) Save() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(s.path, data, 0644)
|
||||
return fileutil.WriteFileAtomic(s.path, data, 0600)
|
||||
}
|
||||
|
||||
func (s *Store) Add(appName, content, sourceURL string) {
|
||||
@@ -63,3 +83,12 @@ func (s *Store) Remove(ids map[string]bool) {
|
||||
}
|
||||
s.Posts = kept
|
||||
}
|
||||
|
||||
// MarkPosted records that the post with the given ID was published to platform.
|
||||
func (s *Store) MarkPosted(id, platform string) {
|
||||
for i := range s.Posts {
|
||||
if s.Posts[i].ID == id && !s.Posts[i].HasPosted(platform) {
|
||||
s.Posts[i].PostedTo = append(s.Posts[i].PostedTo, platform)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMarkPostedPersists(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "posts.json")
|
||||
s, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.Add("App", "content", "")
|
||||
id := s.Posts[0].ID
|
||||
s.MarkPosted(id, PlatformX)
|
||||
s.MarkPosted(id, PlatformX) // idempotent
|
||||
if err := s.Save(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if perm := info.Mode().Perm(); perm != 0600 {
|
||||
t.Errorf("posts file mode = %o, want 600", perm)
|
||||
}
|
||||
|
||||
reloaded, err := Load(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := reloaded.Posts[0]
|
||||
if !p.HasPosted(PlatformX) || p.HasPosted(PlatformLinkedIn) || len(p.PostedTo) != 1 {
|
||||
t.Errorf("PostedTo = %v, want [x]", p.PostedTo)
|
||||
}
|
||||
}
|
||||
+65
-27
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
claudeapi "coremarketing/internal/api/claude"
|
||||
"coremarketing/internal/api/twitter"
|
||||
"coremarketing/internal/config"
|
||||
"coremarketing/internal/fetcher"
|
||||
"coremarketing/internal/models"
|
||||
@@ -58,7 +59,7 @@ type batchGenerateMsg struct {
|
||||
}
|
||||
|
||||
type batchPostedMsg struct {
|
||||
postedIDs []string
|
||||
posted map[string][]string // post ID → platforms newly published to
|
||||
urls []string
|
||||
errors []string
|
||||
}
|
||||
@@ -182,6 +183,7 @@ func (i genPostItem) Description() string { return i.Content }
|
||||
|
||||
type genPostDelegate struct {
|
||||
selected map[string]bool
|
||||
maxLength int
|
||||
}
|
||||
|
||||
func (d genPostDelegate) Height() int { return 4 }
|
||||
@@ -203,7 +205,13 @@ func (d genPostDelegate) Render(w io.Writer, m list.Model, index int, item list.
|
||||
|
||||
line1 := fmt.Sprintf("%s %s · %s", check, pi.AppName, pi.GeneratedAt.Format("Jan 2, 3:04pm"))
|
||||
line2 := " " + truncate(pi.Content, 80)
|
||||
line3 := " " + fmt.Sprintf("%d chars", utf8.RuneCountInString(pi.Content))
|
||||
line3 := " " + fmt.Sprintf("%d / %d chars on X", twitter.TweetLength(pi.Content, pi.SourceURL), d.maxLength)
|
||||
if pi.SourceURL != "" {
|
||||
line3 += " (incl. link)"
|
||||
}
|
||||
if len(pi.PostedTo) > 0 {
|
||||
line3 += " · already posted to " + strings.Join(pi.PostedTo, ", ")
|
||||
}
|
||||
|
||||
var s1, s2, s3 lipgloss.Style
|
||||
if isFocused {
|
||||
@@ -384,7 +392,9 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.textarea.SetValue(msg.post)
|
||||
focusCmd := m.textarea.Focus()
|
||||
m.appState.SetLastChecked(m.selectedApp.Name, time.Now())
|
||||
_ = m.appState.Save()
|
||||
if err := m.appState.Save(); err != nil {
|
||||
m.errorMsg = "Could not save state: " + err.Error()
|
||||
}
|
||||
removeUsedItems(&m)
|
||||
m.view = viewPostPreview
|
||||
return m, focusCmd
|
||||
@@ -393,11 +403,15 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
for i, content := range msg.contents {
|
||||
m.postStore.Add(m.selectedApp.Name, content, msg.sourceURLs[i])
|
||||
}
|
||||
_ = m.postStore.Save()
|
||||
m.appState.SetLastChecked(m.selectedApp.Name, time.Now())
|
||||
_ = m.appState.Save()
|
||||
removeUsedItems(&m)
|
||||
m.statusMsg = successStyle.Render(fmt.Sprintf("✓ %d posts saved to queue — press p to review", len(msg.contents)))
|
||||
if err := m.postStore.Save(); err != nil {
|
||||
m.statusMsg = ""
|
||||
m.errorMsg = "Could not save generated posts: " + err.Error()
|
||||
} else if err := m.appState.Save(); err != nil {
|
||||
m.errorMsg = "Could not save state: " + err.Error()
|
||||
}
|
||||
m.view = viewHome
|
||||
return m, nil
|
||||
|
||||
@@ -407,15 +421,27 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return m, nil
|
||||
|
||||
case batchPostedMsg:
|
||||
// Remove successfully posted items from the store
|
||||
postedSet := map[string]bool{}
|
||||
for _, id := range msg.postedIDs {
|
||||
postedSet[id] = true
|
||||
// Record per-platform success, then drop posts that are now published
|
||||
// everywhere posting is configured. Partially posted ones stay queued
|
||||
// so the failed platform can be retried without double-posting.
|
||||
for id, platforms := range msg.posted {
|
||||
for _, p := range platforms {
|
||||
m.postStore.MarkPosted(id, p)
|
||||
}
|
||||
m.postStore.Remove(postedSet)
|
||||
_ = m.postStore.Save()
|
||||
}
|
||||
done := map[string]bool{}
|
||||
for _, p := range m.postStore.Posts {
|
||||
if (m.poster == nil || p.HasPosted(store.PlatformX)) &&
|
||||
(m.liPoster == nil || p.HasPosted(store.PlatformLinkedIn)) {
|
||||
done[p.ID] = true
|
||||
}
|
||||
}
|
||||
m.postStore.Remove(done)
|
||||
m.resultURLs = msg.urls
|
||||
m.resultErrors = msg.errors
|
||||
if err := m.postStore.Save(); err != nil {
|
||||
m.resultErrors = append(m.resultErrors, "Could not save post queue (posted items may reappear): "+err.Error())
|
||||
}
|
||||
m.view = viewResult
|
||||
|
||||
case errMsg:
|
||||
@@ -706,6 +732,12 @@ func (m Model) renderHome() string {
|
||||
if n := len(m.postStore.Posts); n > 0 {
|
||||
sb.WriteString(" " + successStyle.Render(fmt.Sprintf("● %d post(s) ready to publish", n)) + "\n")
|
||||
}
|
||||
if m.errorMsg != "" {
|
||||
sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n")
|
||||
}
|
||||
if m.statusMsg != "" {
|
||||
sb.WriteString(" " + m.statusMsg + "\n")
|
||||
}
|
||||
|
||||
sb.WriteString(m.appList.View())
|
||||
sb.WriteString("\n")
|
||||
@@ -774,7 +806,7 @@ func (m Model) renderPostPreview() string {
|
||||
sb.WriteString("\n")
|
||||
|
||||
text := m.textarea.Value()
|
||||
charCount := utf8.RuneCountInString(text)
|
||||
charCount := twitter.TweetLength(text, m.pendingSourceURL)
|
||||
limit := m.cfg.Posting.MaxLength
|
||||
|
||||
var countStyle lipgloss.Style
|
||||
@@ -788,6 +820,9 @@ func (m Model) renderPostPreview() string {
|
||||
}
|
||||
|
||||
countLine := countStyle.Render(fmt.Sprintf(" %d / %d characters", charCount, limit))
|
||||
if m.pendingSourceURL != "" {
|
||||
countLine += countStyle.Render(fmt.Sprintf(" (incl. %d for the source link)", twitter.URLReserve(m.pendingSourceURL)))
|
||||
}
|
||||
if charCount > limit {
|
||||
countLine += " " + errorStyle.Render(fmt.Sprintf("(%d over!)", charCount-limit))
|
||||
}
|
||||
@@ -881,7 +916,7 @@ func (m Model) buildGenList() list.Model {
|
||||
for i, p := range m.postStore.Posts {
|
||||
items[i] = genPostItem{p}
|
||||
}
|
||||
m.genDelegate = genPostDelegate{selected: m.genSelected}
|
||||
m.genDelegate = genPostDelegate{selected: m.genSelected, maxLength: m.cfg.Posting.MaxLength}
|
||||
l := list.New(items, m.genDelegate, m.width-4, m.height-10)
|
||||
l.Title = "Generated Posts [Space=select Ctrl+P=post d=delete]"
|
||||
l.SetShowStatusBar(false)
|
||||
@@ -999,10 +1034,11 @@ func (m Model) doFetch(app models.Application, since time.Time) tea.Cmd {
|
||||
func (m Model) doGenerate(items []models.ContentItem) tea.Cmd {
|
||||
app := m.selectedApp
|
||||
cl := m.claude
|
||||
limit := m.cfg.Posting.MaxLength - twitter.URLReserve(firstSourceURL(items))
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
post, err := cl.GeneratePost(ctx, app, items)
|
||||
post, err := cl.GeneratePost(ctx, app, items, limit)
|
||||
if err != nil {
|
||||
return errMsg{err: err, from: viewContentBrowser}
|
||||
}
|
||||
@@ -1013,12 +1049,14 @@ func (m Model) doGenerate(items []models.ContentItem) tea.Cmd {
|
||||
func (m Model) doBatchGenerate(items []models.ContentItem) tea.Cmd {
|
||||
app := m.selectedApp
|
||||
cl := m.claude
|
||||
maxLength := m.cfg.Posting.MaxLength
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
var contents, sourceURLs []string
|
||||
for _, item := range items {
|
||||
post, err := cl.GeneratePost(ctx, app, []models.ContentItem{item})
|
||||
limit := maxLength - twitter.URLReserve(item.URL)
|
||||
post, err := cl.GeneratePost(ctx, app, []models.ContentItem{item}, limit)
|
||||
if err != nil {
|
||||
return errMsg{err: err, from: viewContentBrowser}
|
||||
}
|
||||
@@ -1032,14 +1070,17 @@ func (m Model) doBatchGenerate(items []models.ContentItem) tea.Cmd {
|
||||
func (m Model) doPostBatch(posts []store.GeneratedPost) tea.Cmd {
|
||||
poster := m.poster
|
||||
liPoster := m.liPoster
|
||||
maxLength := m.cfg.Posting.MaxLength
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
var postedIDs, urls, errs []string
|
||||
posted := map[string][]string{}
|
||||
var urls, errs []string
|
||||
for _, p := range posts {
|
||||
anySuccess := false
|
||||
|
||||
if poster != nil {
|
||||
if poster != nil && !p.HasPosted(store.PlatformX) {
|
||||
if n := twitter.TweetLength(p.Content, p.SourceURL); n > maxLength {
|
||||
errs = append(errs, fmt.Sprintf("%s (X): post is %d characters including the link, limit is %d — delete it and regenerate a shorter one", p.AppName, n, maxLength))
|
||||
} else {
|
||||
text := p.Content
|
||||
if p.SourceURL != "" {
|
||||
text += "\n\n" + p.SourceURL
|
||||
@@ -1049,24 +1090,21 @@ func (m Model) doPostBatch(posts []store.GeneratedPost) tea.Cmd {
|
||||
errs = append(errs, fmt.Sprintf("%s (X): %v", p.AppName, err))
|
||||
} else {
|
||||
urls = append(urls, u)
|
||||
anySuccess = true
|
||||
posted[p.ID] = append(posted[p.ID], store.PlatformX)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if liPoster != nil {
|
||||
if liPoster != nil && !p.HasPosted(store.PlatformLinkedIn) {
|
||||
u, err := liPoster.PostUpdate(ctx, p.Content, p.SourceURL)
|
||||
if err != nil {
|
||||
errs = append(errs, fmt.Sprintf("%s (LinkedIn): %v", p.AppName, err))
|
||||
} else {
|
||||
urls = append(urls, u)
|
||||
anySuccess = true
|
||||
posted[p.ID] = append(posted[p.ID], store.PlatformLinkedIn)
|
||||
}
|
||||
}
|
||||
|
||||
if anySuccess {
|
||||
postedIDs = append(postedIDs, p.ID)
|
||||
}
|
||||
}
|
||||
return batchPostedMsg{postedIDs: postedIDs, urls: urls, errors: errs}
|
||||
return batchPostedMsg{posted: posted, urls: urls, errors: errs}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
@@ -64,13 +65,17 @@ func main() {
|
||||
if tw.OAuth2RefreshToken != "" {
|
||||
result, err := auth.RefreshTwitterToken(context.Background(), tw.ClientID, tw.ClientSecret, tw.OAuth2RefreshToken)
|
||||
if err == nil {
|
||||
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token: %v\n", saveErr)
|
||||
// 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
|
||||
}
|
||||
cfg, err = config.Load(cfgPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err)
|
||||
os.Exit(1)
|
||||
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)
|
||||
@@ -104,22 +109,21 @@ func main() {
|
||||
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 {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not load state file: %v\n", err)
|
||||
st, _ = state.Load(statePath)
|
||||
dataFileError(statePath, err)
|
||||
}
|
||||
|
||||
ps, err := store.Load(postsPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not load posts file: %v\n", err)
|
||||
ps, _ = store.Load(postsPath)
|
||||
dataFileError(postsPath, err)
|
||||
}
|
||||
|
||||
ds, err := store.LoadDismissed(dismissedPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not load dismissed file: %v\n", err)
|
||||
ds, _ = store.LoadDismissed(dismissedPath)
|
||||
dataFileError(dismissedPath, err)
|
||||
}
|
||||
|
||||
// Build API clients — nil if credentials are missing
|
||||
@@ -137,10 +141,13 @@ func main() {
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token: %v\n", saveErr)
|
||||
}
|
||||
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
|
||||
})
|
||||
}
|
||||
@@ -157,7 +164,6 @@ func main() {
|
||||
cfg.Credentials.Claude.APIKey,
|
||||
cfg.Credentials.Claude.Model,
|
||||
cfgDir,
|
||||
cfg.Posting.MaxLength,
|
||||
)
|
||||
|
||||
var poster twitterPoster
|
||||
@@ -264,3 +270,19 @@ func runAuth(cfgPath string) {
|
||||
|
||||
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...))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user