From 0aac727cc14c9820538b4887acae3508ba09cbc6 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 29 Apr 2026 06:55:00 -0600 Subject: [PATCH] Move to Federated Gitea --- README.md | 150 +++++ config.yaml | 252 ++++++++ go.mod | 35 ++ go.sum | 63 ++ install.sh | 56 ++ internal/api/claude/client.go | 112 ++++ internal/api/linkedin/client.go | 137 +++++ internal/api/twitter/client.go | 254 ++++++++ internal/api/youtube/client.go | 124 ++++ internal/auth/auth.go | 272 +++++++++ internal/config/config.go | 182 ++++++ internal/fetcher/fetcher.go | 106 ++++ internal/models/models.go | 31 + internal/state/state.go | 50 ++ internal/store/store.go | 65 ++ internal/ui/app.go | 1013 +++++++++++++++++++++++++++++++ internal/ui/styles.go | 85 +++ main.go | 221 +++++++ 18 files changed, 3208 insertions(+) create mode 100644 README.md create mode 100644 config.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100755 install.sh create mode 100644 internal/api/claude/client.go create mode 100644 internal/api/linkedin/client.go create mode 100644 internal/api/twitter/client.go create mode 100644 internal/api/youtube/client.go create mode 100644 internal/auth/auth.go create mode 100644 internal/config/config.go create mode 100644 internal/fetcher/fetcher.go create mode 100644 internal/models/models.go create mode 100644 internal/state/state.go create mode 100644 internal/store/store.go create mode 100644 internal/ui/app.go create mode 100644 internal/ui/styles.go create mode 100644 main.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..9ae7901 --- /dev/null +++ b/README.md @@ -0,0 +1,150 @@ +# CoreMarketing Social Curator + +A terminal UI app that monitors open source SaaS applications across X.com, YouTube, and Instagram, then uses Claude AI to generate posts in the voice of a product manager. + +## Prerequisites + +- Go 1.22 or later +- A [Claude API key](https://console.anthropic.com) +- API credentials for whichever platforms you want to monitor (all are optional except Claude) + +## Setup + +**1. Configure credentials** + +Edit `config.yaml` and fill in your API keys: + +```yaml +credentials: + claude: + api_key: "sk-ant-..." # Required + + twitter: + bearer_token: "" # Required for reading (X Basic plan, $100/mo) + client_id: "" # Required for posting (OAuth 2.0 client ID) + client_secret: "" # Confidential clients only — leave blank otherwise + oauth2_access_token: "" # Set automatically by `coremarketing auth twitter` + + youtube: + api_key: "" # Free — get one at console.cloud.google.com + + instagram: + access_token: "" # Requires Facebook App review + business_account_id: "" + +posting: + twitter_handle: "youraccount" # The @handle you post FROM +``` + +Missing credentials are skipped gracefully — the app works with only Claude plus whichever sources you have set up. + +**2. Add your applications** + +In `config.yaml`, list the open source SaaS apps you want to track: + +```yaml +applications: + - name: "Nextcloud" + description: "Self-hosted file storage and collaboration platform" + twitter_handle: "nextcloud" + youtube_channel_id: "UCQGgrx2pSXQ2r0fk2cbQIFQ" + instagram_handle: "" + hashtags: + - "nextcloud" + - "selfhosted" +``` + +**2b. Authorize Twitter/X posting** + +Once `client_id` is set, run the one-time auth flow to obtain a posting token: + +```bash +coremarketing auth twitter +``` + +This opens a browser, handles the OAuth 2.0 PKCE redirect on `localhost:8080`, and writes `oauth2_access_token` directly into `config.yaml`. Re-run it any time the token expires. + +## Build & Install + +To build and install the binary to `~/.local/bin/`: + +```bash +./install.sh +``` + +The script auto-detects your Go installation. If `~/.local/bin` is not in your PATH, it will print a reminder to add it to your shell config. + +To build locally without installing: + +```bash +go build -o coremarketing . +``` + +## Run + +```bash +coremarketing +``` + +Or, if running from the project directory without installing: + +```bash +./coremarketing +``` + +To use a different config file: + +```bash +coremarketing /path/to/config.yaml +``` + +## Usage + +The app uses a two-stage workflow: first generate posts from curated content, then publish them when ready. + +### Stage 1 — Research and generate + +| Screen | Keys | +|---|---| +| **App list** — pick which application to research | `↑↓` navigate, `/` filter, `Enter` select, `p` view post queue, `q` quit | +| **Fetching** — pulls content from all configured sources since last check | _(automatic)_ | +| **Content browser** — review what was found | `↑↓` navigate, `Space` select/deselect, `Enter` generate post, `Esc` back | +| **Post preview** — edit the Claude-generated post | `Enter` save to queue, `Ctrl+R` regenerate, `Esc` back | + +### Stage 2 — Publish + +From the app list, press `p` to open the post queue. The home screen shows a badge when posts are ready. + +| Screen | Keys | +|---|---| +| **Generated Posts** — all saved posts waiting to be published | `↑↓` navigate, `Space` select/deselect, `Ctrl+P` post selected, `d` delete selected, `Esc` back | +| **Result** — shows published URLs and any errors | `Enter` return to home | + +You can queue posts for multiple applications before publishing them all at once. + +## Data files + +All data files are written next to `config.yaml`, regardless of where you run the binary from. + +| File | Purpose | +|---|---| +| `state.json` | Tracks when content was last fetched per application | +| `posts.json` | Stores generated posts waiting to be published | + +## Lookback window + +The lookback window always defaults to 7 days. It only advances (per application) when Claude successfully generates a post from that application's content — ensuring you never miss content between runs. + +To reset the window for all applications: + +```bash +rm state.json +``` + +To reset a single application, open `state.json` and delete that app's entry. + +## Generated posts + +Claude writes each post in the voice of a product manager — practical, specific, and helpful rather than promotional. Posts are capped at the `max_length` set in `config.yaml` (default: 280 characters for standard X accounts, up to 25,000 for X Premium). + +You can edit the generated post in the preview screen before saving it to the queue. diff --git a/config.yaml b/config.yaml new file mode 100644 index 0000000..bdec5d7 --- /dev/null +++ b/config.yaml @@ -0,0 +1,252 @@ +# CoreMarketing Social Curator — Configuration +# Copy this file to config.yaml and fill in your credentials. + +applications: +- name: "Discourse" + description: "Open source discussion platform and community forum software" + twitter_handle: "discourse" + youtube_channel_id: "UCAd42MxH-zyjD48QgAmb_dA" + instagram_handle: "discourse" + hashtags: + - "#Discourse" + - "#OpenSource" + - "#Community" + +- name: "LibreOffice" + description: "Free and open source office suite compatible with Microsoft Office formats" + twitter_handle: "libreoffice" + youtube_channel_id: "UCQAClQkZEm2rkWvU5bvCAXQ" + instagram_handle: "libreoffice" + hashtags: + - "#LibreOffice" + - "#WordExcelPowerpoint" + - "#FreeOffice" + +- name: "Collabora" + description: "Free and open source office suite compatible with Microsoft Office formats in the browser" + twitter_handle: "collabora" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#Collabora" + - "#WordExcelPowerpoint" + - "#FreeOffice" + +- name: "Plane App" + description: "Open source project management tool and alternative to Jira" + twitter_handle: "planepowers" + youtube_channel_id: "UC8VJ-7tPdHOf5VK9h_mMRBA" + instagram_handle: "" + hashtags: + - "#NoJira" + - "#ProjectManagement" + - "#Kanban" + +- name: "Cal.com" + description: "Open source scheduling infrastructure for everyone" + twitter_handle: "calcom" + youtube_channel_id: "UClEgmwP_8Sejae6KXCzd_bQ" + instagram_handle: "cal.com" + hashtags: + - "#CalCom" + - "#OpenSource" + - "#Scheduling" + +- name: "WordPress" + description: "Open source content management system powering millions of websites" + twitter_handle: "wordpress" + youtube_channel_id: "UCiR2d9r3QkBwuNVS8nqGNgg" + instagram_handle: "wordpressdotcom" + hashtags: + - "#WordPress" + - "#CMS" + - "#Publishing" + +- name: "Bitwarden" + description: "Open source password manager for individuals and teams" + twitter_handle: "bitwarden" + youtube_channel_id: "UCId9a_jQqvJre0_dE2lE_Rw" + instagram_handle: "bitwarden" + hashtags: + - "#Bitwarden" + - "#PasswordManager" + - "#Passwords" + +- name: "Roundcube" + description: "Open source web-based email client with a desktop-like interface" + twitter_handle: "roundcube" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#Roundcube" + - "#Webmail" + - "#Email" + +- name: "Kimai" + description: "Open source time-tracking application for freelancers and teams" + twitter_handle: "kimai_org" + youtube_channel_id: "UCARu_H8IW2MkIWYsZVP571g1" + instagram_handle: "" + hashtags: + - "#Kimai" + - "#TimeTracking" + - "#Workforce" + +- name: "PowerDNS" + description: "Open source DNS server software suite with advanced features" + twitter_handle: "powerdns" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#PowerDNS" + - "#DNS" + - "#Networking" + +- name: "Nextcloud" + description: "Open source cloud platform for file sync, collaboration, and communication" + twitter_handle: "Nextclouders" + youtube_channel_id: "UCQjN5Fs5QSz1loJqLb5bkew" + instagram_handle: "" + hashtags: + - "#Nextcloud" + - "#Groupware" + - "#SelfHosted" + +- name: "Jitsi" + description: "Open source video conferencing and communication platform" + twitter_handle: "jitsinews" + youtube_channel_id: "" + instagram_handle: "jitsi" + hashtags: + - "#Jitsi" + - "#VideoConferencing" + - "#VideoCall" + +- name: "Gitea" + description: "Lightweight open source self-hosted Git service" + twitter_handle: "giteaio" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#Gitea" + - "#Git" + - "#Code" + +- name: "FreeScout" + description: "Open source self-hosted help desk and shared mailbox application" + twitter_handle: "freescoutnews" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#FreeScout" + - "#HelpDesk" + - "#SharedEmail" + +- name: "EspoCRM" + description: "Open source CRM platform for managing customer relationships" + twitter_handle: "espocrm" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#EspoCRM" + - "#CRM" + - "#SalesForceAutomation" + +- name: "Headscale" + description: "Open source self-hosted implementation of the Tailscale control server" + twitter_handle: "" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#Headscale" + - "#VPN" + - "#SelfHosted" + +- name: "Element" + description: "Open source messaging app built on the Matrix protocol" + twitter_handle: "element_hq" + youtube_channel_id: "UCTW5bZLYK97SllqUQDwuxnA" + instagram_handle: "" + hashtags: + - "#Element" + - "#Matrix" + - "#Chat" + +- name: "BookStack" + description: "Open source platform for organising and storing information" + twitter_handle: "bookstack_app" + youtube_channel_id: "UCH66RFWfw6CSm2T1EM4ik1g" + instagram_handle: "" + hashtags: + - "#BookStack" + - "#Wiki" + - "#Knowledgebase" + +- name: "Matrix" + description: "Open standard and communication protocol for decentralized messaging" + twitter_handle: "matrixdotorg" + youtube_channel_id: "" + instagram_handle: "" + hashtags: + - "#Matrix" + - "#Decentralized Messaging" + - "#Chat" + +- name: "Baserow" + description: "Open source no-code database and Airtable alternative" + twitter_handle: "baserow" + youtube_channel_id: "UCPfzyP0FnZNXnqUJKiXZbiA" + instagram_handle: "" + hashtags: + - "#Baserow" + - "#NoCode" + - "#Database" + +- name: "Switch and Click" + description: "Helping normal people use open source" + twitter_handle: "switch_click" + youtube_channel_id: "UCT6AJiTYspOILBK3hMWEq2g" + instagram_handle: "" + hashtags: + - "#SwitchAndClick" + - "#OpenSource" + - "#Guides" + +credentials: + twitter: + # Requires Twitter/X API Basic tier ($100/mo) or higher for read access. + bearer_token: "" + # OAuth 2.0 credentials — required for posting. Run `coremarketing auth` to + # obtain oauth2_access_token automatically via the PKCE flow. + client_id: "" + client_secret: "" # omit or leave blank for public-client apps + oauth2_access_token: "" # populated automatically by `coremarketing auth twitter` + linkedin: + # OAuth 2.0 credentials for posting. Run `coremarketing auth linkedin` to + # obtain access_token and author_urn automatically. + client_id: "" + client_secret: "" + access_token: "" # populated automatically by `coremarketing auth linkedin` + author_urn: "" # populated automatically by `coremarketing auth linkedin` + youtube: + # Free with quota. Get yours at https://console.cloud.google.com + api_key: "" + 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: "claude-sonnet-4-6" + +posting: + # The X.com account handle we post TO (without @) + twitter_handle: "federatedcomp" + # Maximum post length (280 standard, up to 25000 for X Premium) + max_length: 280 + +settings: + # Where to persist "last checked" timestamps + state_file: "state.json" + # Max results to fetch per source per application + max_results: 20 + # Days to look back if no prior state exists + default_lookback_days: 7 diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..850ef4d --- /dev/null +++ b/go.mod @@ -0,0 +1,35 @@ +module coremarketing + +go 1.22.0 + +require ( + github.com/anthropics/anthropic-sdk-go v0.2.0-alpha.4 + github.com/charmbracelet/bubbles v0.20.0 + github.com/charmbracelet/bubbletea v1.1.0 + github.com/charmbracelet/lipgloss v0.13.1 + gopkg.in/yaml.v3 v3.0.1 +) + +require ( + github.com/atotto/clipboard v0.1.4 // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/x/ansi v0.3.2 // indirect + github.com/charmbracelet/x/term v0.2.0 // indirect + github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-localereader v0.0.1 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect + github.com/muesli/cancelreader v0.2.2 // indirect + github.com/muesli/termenv v0.15.2 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/sahilm/fuzzy v0.1.1 // indirect + github.com/tidwall/gjson v1.14.4 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/sjson v1.2.5 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.16.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d72d7f1 --- /dev/null +++ b/go.sum @@ -0,0 +1,63 @@ +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/anthropics/anthropic-sdk-go v0.2.0-alpha.4 h1:TdGQS+RoR4AUO6gqUL74yK1dz/Arrt/WG+dxOj6Yo6A= +github.com/anthropics/anthropic-sdk-go v0.2.0-alpha.4/go.mod h1:GJxtdOs9K4neo8Gg65CjJ7jNautmldGli5/OFNabOoo= +github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= +github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE= +github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU= +github.com/charmbracelet/bubbletea v1.1.0 h1:FjAl9eAL3HBCHenhz/ZPjkKdScmaS5SK69JAK2YJK9c= +github.com/charmbracelet/bubbletea v1.1.0/go.mod h1:9Ogk0HrdbHolIKHdjfFpyXJmiCzGwy+FesYkZr7hYU4= +github.com/charmbracelet/lipgloss v0.13.1 h1:Oik/oqDTMVA01GetT4JdEC033dNzWoQHdWnHnQmXE2A= +github.com/charmbracelet/lipgloss v0.13.1/go.mod h1:zaYVJ2xKSKEnTEEbX6uAHabh2d975RJ+0yfkFpRBz5U= +github.com/charmbracelet/x/ansi v0.3.2 h1:wsEwgAN+C9U06l9dCVMX0/L3x7ptvY1qmjMwyfE6USY= +github.com/charmbracelet/x/ansi v0.3.2/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= +github.com/charmbracelet/x/term v0.2.0 h1:cNB9Ot9q8I711MyZ7myUR5HFWL/lc3OpU8jZ4hwm0x0= +github.com/charmbracelet/x/term v0.2.0/go.mod h1:GVxgxAbjUrmpvIINHIQnJJKpMlHiZ4cktEQCN6GWyF0= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4= +github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4= +github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= +github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= +github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..be9993e --- /dev/null +++ b/install.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail + +BINARY="coremarketing" +INSTALL_DIR="$HOME/.local/bin" + +# Find Go — check common locations if not in PATH +GO=$(command -v go 2>/dev/null || echo "") +for candidate in /run/host/usr/lib/go/bin/go /usr/local/go/bin/go; do + if [[ -z "$GO" && -x "$candidate" ]]; then + GO="$candidate" + fi +done + +if [[ -z "$GO" ]]; then + echo "Error: Go not found. Install Go from https://go.dev/dl/" >&2 + exit 1 +fi + +echo "Using Go: $GO ($($GO version))" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$SCRIPT_DIR" + +echo "Building $BINARY..." +"$GO" build -o "$BINARY" . + +mkdir -p "$INSTALL_DIR" +mv "$BINARY" "$INSTALL_DIR/$BINARY" + +CONFIG_DIR="$HOME/.local/state/coremarketing" +mkdir -p "$CONFIG_DIR" + +if [[ -d "$CONFIG_DIR" ]] && compgen -G "$CONFIG_DIR/*" > /dev/null 2>&1; then + read -r -p "Delete all files in $CONFIG_DIR? [y/N] " answer + if [[ "${answer,,}" == "y" ]]; then + rm -rf "${CONFIG_DIR:?}"/* + echo "Cleared: $CONFIG_DIR" + fi +fi + +if [[ ! -f "$CONFIG_DIR/config.yaml" ]]; then + cp "$SCRIPT_DIR/config.yaml" "$CONFIG_DIR/config.yaml" + echo "Config installed: $CONFIG_DIR/config.yaml" +else + echo "Config already exists, skipping: $CONFIG_DIR/config.yaml" +fi + +echo "Installed: $INSTALL_DIR/$BINARY" + +if ! echo "$PATH" | grep -q "$INSTALL_DIR"; then + echo "" + echo "Note: $INSTALL_DIR is not in your PATH." + echo "Add this to your shell config (~/.bashrc or ~/.zshrc):" + echo " export PATH=\"\$HOME/.local/bin:\$PATH\"" +fi diff --git a/internal/api/claude/client.go b/internal/api/claude/client.go new file mode 100644 index 0000000..3cf3b6b --- /dev/null +++ b/internal/api/claude/client.go @@ -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...)) +} diff --git a/internal/api/linkedin/client.go b/internal/api/linkedin/client.go new file mode 100644 index 0000000..1b981f5 --- /dev/null +++ b/internal/api/linkedin/client.go @@ -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"` +} diff --git a/internal/api/twitter/client.go b/internal/api/twitter/client.go new file mode 100644 index 0000000..768b86e --- /dev/null +++ b/internal/api/twitter/client.go @@ -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 +} diff --git a/internal/api/youtube/client.go b/internal/api/youtube/client.go new file mode 100644 index 0000000..22a7fb2 --- /dev/null +++ b/internal/api/youtube/client.go @@ -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 +} diff --git a/internal/auth/auth.go b/internal/auth/auth.go new file mode 100644 index 0000000..d682b83 --- /dev/null +++ b/internal/auth/auth.go @@ -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, "

Authorization successful!

You can close this tab.

") + 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, "

Authorization successful!

You can close this tab.

") + 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 +} + diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..7c2b4ee --- /dev/null +++ b/internal/config/config.go @@ -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) +} diff --git a/internal/fetcher/fetcher.go b/internal/fetcher/fetcher.go new file mode 100644 index 0000000..d2ad122 --- /dev/null +++ b/internal/fetcher/fetcher.go @@ -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 +} diff --git a/internal/models/models.go b/internal/models/models.go new file mode 100644 index 0000000..d24b5a1 --- /dev/null +++ b/internal/models/models.go @@ -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 +} diff --git a/internal/state/state.go b/internal/state/state.go new file mode 100644 index 0000000..6cb475e --- /dev/null +++ b/internal/state/state.go @@ -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 +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..2954968 --- /dev/null +++ b/internal/store/store.go @@ -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 +} diff --git a/internal/ui/app.go b/internal/ui/app.go new file mode 100644 index 0000000..838ddc2 --- /dev/null +++ b/internal/ui/app.go @@ -0,0 +1,1013 @@ +package ui + +import ( + "context" + "fmt" + "io" + "strings" + "time" + "unicode/utf8" + + "github.com/charmbracelet/bubbles/list" + "github.com/charmbracelet/bubbles/spinner" + "github.com/charmbracelet/bubbles/textarea" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + + claudeapi "coremarketing/internal/api/claude" + "coremarketing/internal/config" + "coremarketing/internal/fetcher" + "coremarketing/internal/models" + "coremarketing/internal/state" + "coremarketing/internal/store" +) + +// --- view states --- + +type viewState int + +const ( + viewHome viewState = iota + viewFetching + viewContentBrowser + viewGenerating + viewPostPreview + viewGeneratedPosts + viewPosting + viewResult +) + +// --- tea messages --- + +type fetchDoneMsg struct { + result fetcher.Result +} + +type prefetchDoneMsg struct { + appName string + result fetcher.Result +} + +type generateDoneMsg struct { + post string +} + +type batchGenerateMsg struct { + contents []string + sourceURLs []string +} + +type batchPostedMsg struct { + postedIDs []string + urls []string + errors []string +} + +type errMsg struct { + err error + from viewState +} + +// --- content list items & delegate --- + +type appListItem struct { + app models.Application + count int + loaded bool +} + +func (i appListItem) FilterValue() string { return i.app.Name } +func (i appListItem) Title() string { + if !i.loaded { + return "(…) " + i.app.Name + } + if i.count > 0 { + return fmt.Sprintf("(%d) %s", i.count, i.app.Name) + } + return i.app.Name +} +func (i appListItem) Description() string { return i.app.Description } + +type contentListItem struct { + models.ContentItem +} + +func (i contentListItem) FilterValue() string { return i.Author + " " + i.Body } +func (i contentListItem) Title() string { return string(i.Source) } +func (i contentListItem) Description() string { return i.Body } + +type selectableDelegate struct { + selected map[string]bool +} + +const maxBodyLines = 4 + +func (d selectableDelegate) Height() int { return 2 + maxBodyLines + 1 } +func (d selectableDelegate) Spacing() int { return 0 } +func (d selectableDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil } + +func (d selectableDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) { + ci, ok := item.(contentListItem) + if !ok { + return + } + isFocused := index == m.Index() + isSelected := d.selected[ci.ID] + + check := checkboxOff + if isSelected { + check = checkboxOn + } + + source := fmt.Sprintf("%-14s", string(ci.Source)) + line1 := fmt.Sprintf("%s %s @%s · %s", check, source, ci.AuthorHandle, ci.PublishedAt.Format("Jan 2")) + + // Build display text: title (if set) + body + displayText := ci.Body + if ci.ContentItem.Title != "" { + displayText = ci.ContentItem.Title + "\n" + ci.Body + } + bodyWidth := m.Width() - 6 + if bodyWidth < 20 { + bodyWidth = 20 + } + wrapped := wordWrap(displayText, bodyWidth) + if len(wrapped) > maxBodyLines { + wrapped = wrapped[:maxBodyLines] + last := wrapped[maxBodyLines-1] + if utf8.RuneCountInString(last) > bodyWidth-1 { + runes := []rune(last) + wrapped[maxBodyLines-1] = string(runes[:bodyWidth-1]) + "…" + } else { + wrapped[maxBodyLines-1] += "…" + } + } + + urlLine := " " + ci.URL + + var s1, s2, s3 lipgloss.Style + if isFocused { + s1 = lipgloss.NewStyle().Foreground(colorPurple).Bold(true) + s2 = lipgloss.NewStyle().Foreground(colorWhite) + s3 = lipgloss.NewStyle().Foreground(colorGray) + } else { + s1 = lipgloss.NewStyle().Foreground(colorWhite) + s2 = lipgloss.NewStyle().Foreground(colorGray) + s3 = lipgloss.NewStyle().Foreground(colorFaint) + } + if isSelected { + s1 = s1.Foreground(colorGreen) + } + + fmt.Fprintln(w, s1.Render(line1)) + for i := 0; i < maxBodyLines; i++ { + if i < len(wrapped) { + fmt.Fprintln(w, s2.Render(" "+wrapped[i])) + } else { + fmt.Fprintln(w, "") + } + } + fmt.Fprintln(w, s3.Render(urlLine)) +} + +// --- generated post list items & delegate --- + +type genPostItem struct { + store.GeneratedPost +} + +func (i genPostItem) FilterValue() string { return i.AppName + " " + i.Content } +func (i genPostItem) Title() string { return i.AppName } +func (i genPostItem) Description() string { return i.Content } + +type genPostDelegate struct { + selected map[string]bool +} + +func (d genPostDelegate) Height() int { return 4 } +func (d genPostDelegate) Spacing() int { return 0 } +func (d genPostDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil } + +func (d genPostDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) { + pi, ok := item.(genPostItem) + if !ok { + return + } + isFocused := index == m.Index() + isSelected := d.selected[pi.ID] + + check := checkboxOff + if isSelected { + check = checkboxOn + } + + 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)) + + var s1, s2, s3 lipgloss.Style + if isFocused { + s1 = lipgloss.NewStyle().Foreground(colorPurple).Bold(true) + s2 = lipgloss.NewStyle().Foreground(colorWhite) + s3 = lipgloss.NewStyle().Foreground(colorGray) + } else { + s1 = lipgloss.NewStyle().Foreground(colorWhite) + s2 = lipgloss.NewStyle().Foreground(colorGray) + s3 = lipgloss.NewStyle().Foreground(colorFaint) + } + if isSelected { + s1 = s1.Foreground(colorGreen) + } + + fmt.Fprintln(w, s1.Render(line1)) + fmt.Fprintln(w, s2.Render(line2)) + fmt.Fprintln(w, s3.Render(line3)) + fmt.Fprintln(w, "") +} + +// --- posting client interface --- + +type postingClient interface { + PostTweet(ctx context.Context, text string) (string, error) +} + +type linkedinPostingClient interface { + PostUpdate(ctx context.Context, text, sourceURL string) (string, error) +} + +// --- main model --- + +type Model struct { + view viewState + + cfg *config.Config + appState *state.State + postStore *store.Store + fetch *fetcher.Fetcher + claude *claudeapi.Client + poster postingClient + liPoster linkedinPostingClient + + appList list.Model + contentList list.Model + selDelegate selectableDelegate + selected map[string]bool + + genList list.Model + genDelegate genPostDelegate + genSelected map[string]bool + + spinner spinner.Model + textarea textarea.Model + + selectedApp *models.Application + fetchResult fetcher.Result + prefetchResults map[string]fetcher.Result + pendingItemIDs map[string]bool + + generatedPost string + pendingSourceURL string + + resultURLs []string + resultErrors []string + statusMsg string + errorMsg string + fetchLabel string + + width int + height int +} + +func New(cfg *config.Config, st *state.State, ps *store.Store, f *fetcher.Fetcher, cl *claudeapi.Client, poster postingClient, liPoster linkedinPostingClient) Model { + s := spinner.New() + s.Spinner = spinner.Dot + s.Style = spinnerStyle + + ta := textarea.New() + ta.CharLimit = cfg.Posting.MaxLength * 2 + ta.ShowLineNumbers = false + + items := make([]list.Item, len(cfg.Applications)) + for i, app := range cfg.Applications { + items[i] = appListItem{app: app} + } + appList := list.New(items, list.NewDefaultDelegate(), 60, 20) + appList.Title = "Select Application" + appList.SetShowStatusBar(false) + appList.SetFilteringEnabled(true) + appList.Styles.Title = titleStyle + + return Model{ + view: viewHome, + cfg: cfg, + appState: st, + postStore: ps, + fetch: f, + claude: cl, + poster: poster, + liPoster: liPoster, + appList: appList, + selected: map[string]bool{}, + genSelected: map[string]bool{}, + prefetchResults: map[string]fetcher.Result{}, + spinner: s, + textarea: ta, + } +} + +func (m Model) Init() tea.Cmd { + cmds := []tea.Cmd{m.spinner.Tick} + for _, app := range m.cfg.Applications { + cmds = append(cmds, m.doPrefetch(app)) + } + return tea.Batch(cmds...) +} + +func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + + case tea.WindowSizeMsg: + m.width = msg.Width + m.height = msg.Height + m.appList.SetSize(msg.Width-4, msg.Height-8) + if m.view == viewContentBrowser { + m.contentList.SetSize(msg.Width-4, msg.Height-10) + } + if m.view == viewGeneratedPosts { + m.genList.SetSize(msg.Width-4, msg.Height-10) + } + m.textarea.SetWidth(msg.Width - 6) + m.textarea.SetHeight(8) + + case spinner.TickMsg: + var cmd tea.Cmd + m.spinner, cmd = m.spinner.Update(msg) + return m, cmd + + case fetchDoneMsg: + m.fetchResult = msg.result + m.selected = map[string]bool{} + + items := make([]list.Item, len(msg.result.Items)) + for i, item := range msg.result.Items { + items[i] = contentListItem{item} + } + m.selDelegate = selectableDelegate{selected: m.selected} + m.contentList = list.New(items, m.selDelegate, m.width-4, m.height-10) + m.contentList.Title = fmt.Sprintf("Content for %s [Space=select Enter=generate]", m.selectedApp.Name) + m.contentList.SetShowStatusBar(true) + m.contentList.SetFilteringEnabled(true) + m.contentList.Styles.Title = titleStyle + + if len(msg.result.Errors) > 0 { + m.statusMsg = warningStyle.Render("⚠ Some sources failed: " + strings.Join(msg.result.Errors, "; ")) + } else { + m.statusMsg = "" + } + if len(msg.result.Items) == 0 { + m.errorMsg = "No content found. Try adjusting your lookback window or check your API credentials." + } + m.view = viewContentBrowser + + case generateDoneMsg: + m.generatedPost = msg.post + m.textarea.SetValue(msg.post) + focusCmd := m.textarea.Focus() + m.appState.SetLastChecked(m.selectedApp.Name, time.Now()) + _ = m.appState.Save() + removeUsedItems(&m) + m.view = viewPostPreview + return m, focusCmd + + case batchGenerateMsg: + 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))) + m.view = viewHome + return m, nil + + case prefetchDoneMsg: + m.prefetchResults[msg.appName] = msg.result + rebuildAppList(&m) + return m, nil + + case batchPostedMsg: + // Remove successfully posted items from the store + postedSet := map[string]bool{} + for _, id := range msg.postedIDs { + postedSet[id] = true + } + m.postStore.Remove(postedSet) + _ = m.postStore.Save() + m.resultURLs = msg.urls + m.resultErrors = msg.errors + m.view = viewResult + + case errMsg: + m.errorMsg = msg.err.Error() + m.view = msg.from + return m, nil + + case tea.KeyMsg: + switch msg.String() { + case "ctrl+c": + return m, tea.Quit + } + + switch m.view { + case viewHome: + return m.updateHome(msg) + case viewContentBrowser: + return m.updateContentBrowser(msg) + case viewPostPreview: + return m.updatePostPreview(msg) + case viewGeneratedPosts: + return m.updateGeneratedPosts(msg) + case viewResult: + switch msg.String() { + case "enter", "q", "esc": + m.view = viewHome + m.errorMsg = "" + m.statusMsg = "" + m.resultURLs = nil + m.resultErrors = nil + m.selectedApp = nil + } + } + } + + return m, nil +} + +func (m Model) updateHome(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "q", "esc": + return m, tea.Quit + case "p": + m.genSelected = map[string]bool{} + m.genList = m.buildGenList() + m.view = viewGeneratedPosts + return m, nil + case "enter": + item, ok := m.appList.SelectedItem().(appListItem) + if !ok { + return m, nil + } + app := item.app + m.selectedApp = &app + m.errorMsg = "" + m.statusMsg = "" + if result, ok := m.prefetchResults[app.Name]; ok { + return m, func() tea.Msg { return fetchDoneMsg{result: result} } + } + since := m.appState.GetLastChecked(app.Name, m.cfg.Settings.DefaultLookbackDays) + m.fetchLabel = fmt.Sprintf("Fetching content for %s since %s…", app.Name, since.Format("Jan 2")) + m.view = viewFetching + return m, tea.Batch(m.spinner.Tick, m.doFetch(app, since)) + } + var cmd tea.Cmd + m.appList, cmd = m.appList.Update(msg) + return m, cmd +} + +func (m Model) updateContentBrowser(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "q", "esc": + m.view = viewHome + m.errorMsg = "" + return m, nil + case " ": + item, ok := m.contentList.SelectedItem().(contentListItem) + if !ok { + return m, nil + } + m.selected[item.ID] = !m.selected[item.ID] + m.selDelegate.selected = m.selected + m.contentList.SetDelegate(m.selDelegate) + return m, nil + case "enter": + var chosen []models.ContentItem + for _, raw := range m.contentList.Items() { + ci, ok := raw.(contentListItem) + if ok && m.selected[ci.ID] { + chosen = append(chosen, ci.ContentItem) + } + } + if len(chosen) == 0 { + m.errorMsg = "Select at least one item with Space before pressing Enter." + return m, nil + } + m.errorMsg = "" + m.view = viewGenerating + m.pendingItemIDs = make(map[string]bool, len(chosen)) + for _, item := range chosen { + m.pendingItemIDs[item.ID] = true + } + if len(chosen) == 1 { + m.pendingSourceURL = firstSourceURL(chosen) + return m, tea.Batch(m.spinner.Tick, m.doGenerate(chosen)) + } + return m, tea.Batch(m.spinner.Tick, m.doBatchGenerate(chosen)) + } + + var cmd tea.Cmd + m.contentList, cmd = m.contentList.Update(msg) + return m, cmd +} + +func (m Model) updatePostPreview(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "ctrl+r": + var chosen []models.ContentItem + for _, raw := range m.contentList.Items() { + ci, ok := raw.(contentListItem) + if ok && m.selected[ci.ID] { + chosen = append(chosen, ci.ContentItem) + } + } + m.view = viewGenerating + m.textarea.Blur() + m.pendingItemIDs = make(map[string]bool, len(chosen)) + for _, item := range chosen { + m.pendingItemIDs[item.ID] = true + } + m.pendingSourceURL = firstSourceURL(chosen) + return m, tea.Batch(m.spinner.Tick, m.doGenerate(chosen)) + case "ctrl+s", "enter", "esc": + // Prefer textarea value (captures edits); fall back to the original + // generated post in case the textarea state is not yet initialised. + text := strings.TrimSpace(m.textarea.Value()) + if text == "" { + text = strings.TrimSpace(m.generatedPost) + } + if text == "" { + m.view = viewContentBrowser + m.textarea.Blur() + return m, nil + } + m.postStore.Add(m.selectedApp.Name, text, m.pendingSourceURL) + if err := m.postStore.Save(); err != nil { + m.errorMsg = "Could not save post: " + err.Error() + return m, nil + } + m.textarea.Blur() + m.errorMsg = "" + m.view = viewHome + return m, nil + } + + var cmd tea.Cmd + m.textarea, cmd = m.textarea.Update(msg) + return m, cmd +} + +func (m Model) updateGeneratedPosts(msg tea.KeyMsg) (tea.Model, tea.Cmd) { + switch msg.String() { + case "q", "esc": + m.view = viewHome + m.errorMsg = "" + return m, nil + case " ": + item, ok := m.genList.SelectedItem().(genPostItem) + if !ok { + return m, nil + } + m.genSelected[item.ID] = !m.genSelected[item.ID] + m.genDelegate.selected = m.genSelected + m.genList.SetDelegate(m.genDelegate) + return m, nil + case "d": + // Delete selected posts from the store + if len(m.genSelected) == 0 { + m.errorMsg = "Select posts with Space first." + return m, nil + } + m.postStore.Remove(m.genSelected) + if err := m.postStore.Save(); err != nil { + m.errorMsg = "Could not save: " + err.Error() + return m, nil + } + m.genSelected = map[string]bool{} + m.genList = m.buildGenList() + m.errorMsg = "" + return m, nil + case "ctrl+p": + if m.poster == nil && m.liPoster == nil { + m.errorMsg = "Posting is not configured. Set credentials in config.yaml." + return m, nil + } + var chosen []store.GeneratedPost + for _, raw := range m.genList.Items() { + pi, ok := raw.(genPostItem) + if ok && m.genSelected[pi.ID] { + chosen = append(chosen, pi.GeneratedPost) + } + } + if len(chosen) == 0 { + m.errorMsg = "Select at least one post with Space before posting." + return m, nil + } + m.errorMsg = "" + m.view = viewPosting + return m, tea.Batch(m.spinner.Tick, m.doPostBatch(chosen)) + } + + var cmd tea.Cmd + m.genList, cmd = m.genList.Update(msg) + return m, cmd +} + +func (m Model) View() string { + switch m.view { + case viewHome: + return m.renderHome() + case viewFetching: + return m.renderSpinner(m.fetchLabel) + case viewContentBrowser: + return m.renderContentBrowser() + case viewGenerating: + return m.renderSpinner("Generating post with Claude…") + case viewPostPreview: + return m.renderPostPreview() + case viewGeneratedPosts: + return m.renderGeneratedPosts() + case viewPosting: + return m.renderSpinner(fmt.Sprintf("Posting to @%s…", m.cfg.Posting.TwitterHandle)) + case viewResult: + return m.renderResult() + } + return "" +} + +// --- view renderers --- + +func (m Model) renderHome() string { + var sb strings.Builder + sb.WriteString(m.header("CoreMarketing — Social Curator")) + sb.WriteString("\n") + + if n := len(m.postStore.Posts); n > 0 { + sb.WriteString(" " + successStyle.Render(fmt.Sprintf("● %d post(s) ready to publish", n)) + "\n") + } + + sb.WriteString(m.appList.View()) + sb.WriteString("\n") + + hints := []string{ + keyHint("↑↓", "navigate"), + keyHint("/", "filter"), + keyHint("enter", "fetch content"), + } + if len(m.postStore.Posts) > 0 { + hints = append(hints, keyHint("p", "view posts")) + } + hints = append(hints, keyHint("q", "quit")) + sb.WriteString(m.renderStatusBar(hints...)) + return sb.String() +} + +func (m Model) renderSpinner(label string) string { + var sb strings.Builder + sb.WriteString(m.header("CoreMarketing — Social Curator")) + sb.WriteString("\n\n") + sb.WriteString(" " + m.spinner.View() + " " + label + "\n") + return sb.String() +} + +func (m Model) renderContentBrowser() string { + var sb strings.Builder + title := "Social Curator" + if m.selectedApp != nil { + title += " — " + m.selectedApp.Name + } + sb.WriteString(m.header(title)) + sb.WriteString("\n") + + if m.errorMsg != "" { + sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n") + } + if m.statusMsg != "" { + sb.WriteString(" " + m.statusMsg + "\n") + } + + selCount := 0 + for _, v := range m.selected { + if v { + selCount++ + } + } + sb.WriteString(lipgloss.NewStyle().Foreground(colorGray).Render( + fmt.Sprintf(" %d item(s) found · %d selected\n", len(m.fetchResult.Items), selCount), + )) + sb.WriteString(m.contentList.View()) + sb.WriteString("\n") + sb.WriteString(m.renderStatusBar( + keyHint("↑↓", "navigate"), + keyHint("space", "select/deselect"), + keyHint("enter", "generate post"), + keyHint("esc", "back"), + )) + return sb.String() +} + +func (m Model) renderPostPreview() string { + var sb strings.Builder + sb.WriteString(m.header("Post Preview — Edit then Save")) + sb.WriteString("\n") + + text := m.textarea.Value() + charCount := utf8.RuneCountInString(text) + limit := m.cfg.Posting.MaxLength + + var countStyle lipgloss.Style + switch { + case charCount > limit: + countStyle = charCountOver + case charCount > limit-20: + countStyle = charCountWarn + default: + countStyle = charCountOK + } + + countLine := countStyle.Render(fmt.Sprintf(" %d / %d characters", charCount, limit)) + if charCount > limit { + countLine += " " + errorStyle.Render(fmt.Sprintf("(%d over!)", charCount-limit)) + } + sb.WriteString(countLine + "\n\n") + sb.WriteString(borderStyle.Width(m.width - 4).Render(m.textarea.View())) + sb.WriteString("\n\n") + + if m.errorMsg != "" { + sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n") + } + + sb.WriteString(m.renderStatusBar( + keyHint("enter/esc", "save to queue"), + keyHint("ctrl+r", "regenerate"), + )) + return sb.String() +} + +func (m Model) renderGeneratedPosts() string { + var sb strings.Builder + sb.WriteString(m.header("Generated Posts — Select to Publish")) + sb.WriteString("\n") + + if m.errorMsg != "" { + sb.WriteString(" " + errorStyle.Render(m.errorMsg) + "\n") + } + + selCount := 0 + for _, v := range m.genSelected { + if v { + selCount++ + } + } + sb.WriteString(lipgloss.NewStyle().Foreground(colorGray).Render( + fmt.Sprintf(" %d post(s) · %d selected\n", len(m.postStore.Posts), selCount), + )) + + if len(m.postStore.Posts) == 0 { + sb.WriteString("\n " + lipgloss.NewStyle().Foreground(colorGray).Render("No generated posts yet. Fetch content and generate some first.") + "\n") + } else { + sb.WriteString(m.genList.View()) + } + + sb.WriteString("\n") + sb.WriteString(m.renderStatusBar( + keyHint("↑↓", "navigate"), + keyHint("space", "select/deselect"), + keyHint("ctrl+p", "post selected"), + keyHint("d", "delete selected"), + keyHint("esc", "back"), + )) + return sb.String() +} + +func (m Model) renderResult() string { + var sb strings.Builder + sb.WriteString(m.header("CoreMarketing — Result")) + sb.WriteString("\n\n") + + if len(m.resultErrors) > 0 { + sb.WriteString(" " + errorStyle.Render("Errors:") + "\n") + for _, e := range m.resultErrors { + sb.WriteString(" " + lipgloss.NewStyle().Foreground(colorRed).Render("• "+e) + "\n") + } + sb.WriteString("\n") + } + if len(m.resultURLs) > 0 { + sb.WriteString(" " + successStyle.Render(fmt.Sprintf("✓ %d post(s) published:", len(m.resultURLs))) + "\n") + for _, u := range m.resultURLs { + sb.WriteString(" " + lipgloss.NewStyle().Foreground(colorPurple).Render("• "+u) + "\n") + } + } + + sb.WriteString("\n") + sb.WriteString(m.renderStatusBar(keyHint("enter", "return to home"))) + return sb.String() +} + +// --- helpers --- + +func (m Model) header(title string) string { + return headerStyle.Width(m.width).Render(" " + title) +} + +func (m Model) renderStatusBar(hints ...string) string { + return statusBarStyle.Render(" " + strings.Join(hints, " · ")) +} + +func (m Model) buildGenList() list.Model { + items := make([]list.Item, len(m.postStore.Posts)) + for i, p := range m.postStore.Posts { + items[i] = genPostItem{p} + } + m.genDelegate = genPostDelegate{selected: m.genSelected} + 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) + l.SetFilteringEnabled(false) + l.Styles.Title = titleStyle + return l +} + +func wordWrap(s string, width int) []string { + var lines []string + for _, paragraph := range strings.Split(s, "\n") { + paragraph = strings.TrimSpace(paragraph) + if paragraph == "" { + continue + } + var current strings.Builder + for _, word := range strings.Fields(paragraph) { + wordLen := utf8.RuneCountInString(word) + if current.Len() == 0 { + current.WriteString(word) + } else if utf8.RuneCountInString(current.String())+1+wordLen <= width { + current.WriteByte(' ') + current.WriteString(word) + } else { + lines = append(lines, current.String()) + current.Reset() + current.WriteString(word) + } + } + if current.Len() > 0 { + lines = append(lines, current.String()) + } + } + return lines +} + +func firstSourceURL(items []models.ContentItem) string { + for _, item := range items { + if item.URL != "" { + return item.URL + } + } + return "" +} + +func truncate(s string, n int) string { + r := []rune(s) + if len(r) > n { + return string(r[:n-3]) + "..." + } + return s +} + +// --- async commands --- + +func removeUsedItems(m *Model) { + if m.selectedApp == nil || len(m.pendingItemIDs) == 0 { + return + } + result, ok := m.prefetchResults[m.selectedApp.Name] + if !ok { + return + } + filtered := result.Items[:0] + for _, item := range result.Items { + if !m.pendingItemIDs[item.ID] { + filtered = append(filtered, item) + } + } + result.Items = filtered + m.prefetchResults[m.selectedApp.Name] = result + rebuildAppList(m) + m.pendingItemIDs = nil +} + +func rebuildAppList(m *Model) { + idx := m.appList.Index() + items := make([]list.Item, len(m.cfg.Applications)) + for i, app := range m.cfg.Applications { + item := appListItem{app: app} + if result, ok := m.prefetchResults[app.Name]; ok { + item.count = len(result.Items) + item.loaded = true + } + items[i] = item + } + m.appList.SetItems(items) + m.appList.Select(idx) +} + +func (m Model) doPrefetch(app models.Application) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + since := m.appState.GetLastChecked(app.Name, m.cfg.Settings.DefaultLookbackDays) + result := m.fetch.FetchForApp(ctx, &app, since) + return prefetchDoneMsg{appName: app.Name, result: result} + } +} + +func (m Model) doFetch(app models.Application, since time.Time) tea.Cmd { + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + return fetchDoneMsg{result: m.fetch.FetchForApp(ctx, &app, since)} + } +} + +func (m Model) doGenerate(items []models.ContentItem) tea.Cmd { + app := m.selectedApp + cl := m.claude + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + post, err := cl.GeneratePost(ctx, app, items) + if err != nil { + return errMsg{err: err, from: viewContentBrowser} + } + return generateDoneMsg{post: post} + } +} + +func (m Model) doBatchGenerate(items []models.ContentItem) tea.Cmd { + app := m.selectedApp + cl := m.claude + 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}) + if err != nil { + return errMsg{err: err, from: viewContentBrowser} + } + contents = append(contents, post) + sourceURLs = append(sourceURLs, item.URL) + } + return batchGenerateMsg{contents: contents, sourceURLs: sourceURLs} + } +} + +func (m Model) doPostBatch(posts []store.GeneratedPost) tea.Cmd { + poster := m.poster + liPoster := m.liPoster + return func() tea.Msg { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + var postedIDs, urls, errs []string + for _, p := range posts { + anySuccess := false + + if poster != nil { + text := p.Content + if p.SourceURL != "" { + text += "\n\n" + p.SourceURL + } + u, err := poster.PostTweet(ctx, text) + if err != nil { + errs = append(errs, fmt.Sprintf("%s (X): %v", p.AppName, err)) + } else { + urls = append(urls, u) + anySuccess = true + } + } + + if liPoster != nil { + 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 + } + } + + if anySuccess { + postedIDs = append(postedIDs, p.ID) + } + } + return batchPostedMsg{postedIDs: postedIDs, urls: urls, errors: errs} + } +} diff --git a/internal/ui/styles.go b/internal/ui/styles.go new file mode 100644 index 0000000..d839698 --- /dev/null +++ b/internal/ui/styles.go @@ -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) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..49718aa --- /dev/null +++ b/main.go @@ -0,0 +1,221 @@ +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + + 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 [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, run auth before the TUI. + if cfg.Credentials.Twitter.ClientID != "" && !cfg.HasTwitterPost() { + 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") + + 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) + } + + 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) + } + + // 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, + ) + } + + 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, + cfg.Posting.MaxLength, + ) + + 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, 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.UpdateOAuth2Token(cfgPath, result.AccessToken); 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) +}