Move to Federated Gitea

This commit is contained in:
2026-04-29 06:55:00 -06:00
commit 0aac727cc1
18 changed files with 3208 additions and 0 deletions
+150
View File
@@ -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.
+252
View File
@@ -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
+35
View File
@@ -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
)
+63
View File
@@ -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=
Executable
+56
View File
@@ -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
+112
View File
@@ -0,0 +1,112 @@
package claude
import (
"context"
"fmt"
"os"
"strings"
"time"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"coremarketing/internal/models"
)
const systemPrompt = `You are a product manager at a company that champions open source software. You write posts for X.com (Twitter) to help users get more value from open source SaaS applications.
Your voice:
- Knowledgeable but approachable — you know this product deeply and want to share that knowledge
- Practical — you share specific workflows, features, and tips users can immediately apply
- Community-minded — you reference the broader ecosystem and encourage engagement
- Authentic — no corporate buzzwords, write like a real PM sharing genuine insights
Your posts should:
- Lead with the most valuable insight or tip
- Be specific rather than generic
- Include a call to action when appropriate (question, try it yourself, share your experience)
- Stay within the character limit INCLUDING hashtags
- End with 2-3 relevant hashtags
- May include 1-2 emojis for visual interest
Output ONLY the post text. No explanations, no alternatives — just the post.`
type Client struct {
client *anthropic.Client
model string
maxLength int
logFile string
}
func New(apiKey, model, stateDir string, maxLength int) *Client {
c := anthropic.NewClient(option.WithAPIKey(apiKey))
return &Client{
client: c,
model: model,
maxLength: maxLength,
logFile: stateDir + "/coremarketing.log",
}
}
// GeneratePost creates a post in the voice of a product manager based on selected content.
func (c *Client) GeneratePost(ctx context.Context, app *models.Application, items []models.ContentItem) (string, error) {
// Combine system instructions with the user prompt in a single user message.
// This avoids SDK version ambiguity around the System parameter content block type.
fullPrompt := systemPrompt + "\n\n---\n\n" + c.buildUserPrompt(app, items)
msg, err := c.client.Messages.New(ctx, anthropic.MessageNewParams{
Model: anthropic.F(c.model),
MaxTokens: anthropic.F(int64(512)),
Messages: anthropic.F([]anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(fullPrompt)),
}),
})
if err != nil {
c.log("GeneratePost error: %v", err)
return "", fmt.Errorf("claude API: %w", err)
}
for _, block := range msg.Content {
if block.Type == "text" {
return strings.TrimSpace(block.Text), nil
}
}
c.log("GeneratePost: no text block in response (stop_reason=%s)", msg.StopReason)
return "", fmt.Errorf("no text content in claude response (stop_reason=%s)", msg.StopReason)
}
func (c *Client) buildUserPrompt(app *models.Application, items []models.ContentItem) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Application: %s\n", app.Name))
sb.WriteString(fmt.Sprintf("Description: %s\n\n", app.Description))
sb.WriteString(fmt.Sprintf("Character limit: %d\n\n", c.maxLength))
sb.WriteString("Selected content from social media and community:\n\n")
for i, item := range items {
sb.WriteString(fmt.Sprintf("--- Item %d [%s] ---\n", i+1, string(item.Source)))
if item.Title != "" {
sb.WriteString(fmt.Sprintf("Title: %s\n", item.Title))
}
sb.WriteString(fmt.Sprintf("Author: @%s\n", item.AuthorHandle))
sb.WriteString(fmt.Sprintf("Date: %s\n", item.PublishedAt.Format("Jan 2, 2006")))
sb.WriteString(fmt.Sprintf("Content: %s\n", item.Body))
sb.WriteString(fmt.Sprintf("URL: %s\n\n", item.URL))
}
sb.WriteString(fmt.Sprintf(
"Based on this content, write ONE X.com post (max %d characters including hashtags) in the voice of a product manager helping users better use %s.",
c.maxLength, app.Name,
))
return sb.String()
}
func (c *Client) log(format string, args ...any) {
f, err := os.OpenFile(c.logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return
}
defer f.Close()
fmt.Fprintf(f, "[%s] %s\n", time.Now().Format(time.RFC3339), fmt.Sprintf(format, args...))
}
+137
View File
@@ -0,0 +1,137 @@
package linkedin
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
const (
apiBase = "https://api.linkedin.com"
linkedinVersion = "202501"
)
type Client struct {
accessToken string
authorURN string
http *http.Client
}
func New(accessToken, authorURN string) *Client {
return &Client{
accessToken: accessToken,
authorURN: authorURN,
http: &http.Client{Timeout: 15 * time.Second},
}
}
// PostUpdate creates a LinkedIn post. If sourceURL is non-empty it is attached
// as an article card (LinkedIn will fetch the title and thumbnail automatically).
func (c *Client) PostUpdate(ctx context.Context, text, sourceURL string) (string, error) {
pr := postRequest{
Author: c.authorURN,
Commentary: text,
Visibility: "PUBLIC",
Distribution: distribution{
FeedDistribution: "MAIN_FEED",
TargetEntities: []any{},
ThirdPartyDistributionChannels: []any{},
},
LifecycleState: "PUBLISHED",
IsReshareDisabledByAuthor: false,
}
if sourceURL != "" {
pr.Content = &postContent{Article: articleContent{Source: sourceURL}}
}
body, err := json.Marshal(pr)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBase+"/rest/posts", strings.NewReader(string(body)))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("LinkedIn-Version", linkedinVersion)
req.Header.Set("X-Restli-Protocol-Version", "2.0.0")
res, err := c.http.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusCreated {
return "", fmt.Errorf("linkedin HTTP %d: %s", res.StatusCode, raw)
}
postID := res.Header.Get("X-RestLi-Id")
if postID == "" {
return "", nil
}
return "https://www.linkedin.com/feed/update/" + postID + "/", nil
}
// GetAuthorURN fetches the LinkedIn person URN for the owner of accessToken.
func GetAuthorURN(ctx context.Context, accessToken string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/v2/userinfo", nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("userinfo HTTP %d: %s", res.StatusCode, raw)
}
var info struct {
Sub string `json:"sub"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &info); err != nil {
return "", err
}
if info.Sub == "" {
return "", fmt.Errorf("no sub in userinfo response: %s", raw)
}
return "urn:li:person:" + info.Sub, nil
}
type postRequest struct {
Author string `json:"author"`
Commentary string `json:"commentary"`
Visibility string `json:"visibility"`
Distribution distribution `json:"distribution"`
Content *postContent `json:"content,omitempty"`
LifecycleState string `json:"lifecycleState"`
IsReshareDisabledByAuthor bool `json:"isReshareDisabledByAuthor"`
}
type distribution struct {
FeedDistribution string `json:"feedDistribution"`
TargetEntities []any `json:"targetEntities"`
ThirdPartyDistributionChannels []any `json:"thirdPartyDistributionChannels"`
}
type postContent struct {
Article articleContent `json:"article"`
}
type articleContent struct {
Source string `json:"source"`
}
+254
View File
@@ -0,0 +1,254 @@
package twitter
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"coremarketing/internal/models"
)
const apiBase = "https://api.twitter.com/2"
type Client struct {
bearerToken string
oauth2AccessToken string
maxResults int
http *http.Client
}
func New(bearerToken, oauth2AccessToken string, maxResults int) *Client {
// Bearer tokens are raw base64 strings. If copied from a URL or form they
// may arrive URL-encoded (%2F, %3D, etc.) — decode to the raw form.
if decoded, err := url.QueryUnescape(bearerToken); err == nil {
bearerToken = decoded
}
return &Client{
bearerToken: bearerToken,
oauth2AccessToken: oauth2AccessToken,
maxResults: maxResults,
http: &http.Client{Timeout: 15 * time.Second},
}
}
// GetUserTweets fetches tweets from a specific account's timeline since `since`.
func (c *Client) GetUserTweets(ctx context.Context, handle string, since time.Time, appName string) ([]models.ContentItem, error) {
userID, err := c.lookupUserID(ctx, handle)
if err != nil {
return nil, fmt.Errorf("lookup user %s: %w", handle, err)
}
endpoint := fmt.Sprintf("%s/users/%s/tweets", apiBase, userID)
params := url.Values{
"max_results": {strconv.Itoa(clamp(c.maxResults, 5, 100))},
"start_time": {since.UTC().Format(time.RFC3339)},
"tweet.fields": {"created_at,author_id,entities"},
"expansions": {"author_id"},
"exclude": {"retweets,replies"},
}
var resp tweetsResponse
if err := c.getBearer(ctx, endpoint+"?"+params.Encode(), &resp); err != nil {
return nil, err
}
return c.tweetsToItems(resp, handle, models.SourceTwitterAccount, appName), nil
}
// SearchTweets searches recent tweets using the provided query since `since`.
func (c *Client) SearchTweets(ctx context.Context, query string, since time.Time, appName string) ([]models.ContentItem, error) {
endpoint := apiBase + "/tweets/search/recent"
params := url.Values{
"query": {query},
"max_results": {strconv.Itoa(clamp(c.maxResults, 10, 100))},
"start_time": {since.UTC().Format(time.RFC3339)},
"tweet.fields": {"created_at,author_id,entities"},
"expansions": {"author_id"},
}
var resp tweetsResponse
if err := c.getBearer(ctx, endpoint+"?"+params.Encode(), &resp); err != nil {
return nil, err
}
return c.tweetsToItems(resp, "", models.SourceTwitterSearch, appName), nil
}
// PostTweet posts a tweet using OAuth 2.0 user context.
func (c *Client) PostTweet(ctx context.Context, text string) (string, error) {
endpoint := apiBase + "/tweets"
payload := map[string]string{"text": text}
body, _ := json.Marshal(payload)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
res, err := c.http.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusCreated {
return "", fmt.Errorf("post tweet HTTP %d: %s", res.StatusCode, raw)
}
var out struct {
Data struct {
ID string `json:"id"`
Text string `json:"text"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return "", err
}
return "https://x.com/" + out.Data.ID, nil
}
// BuildSearchQuery constructs an X search query from hashtags.
func BuildSearchQuery(hashtags []string, excludeHandle string) string {
var terms []string
for _, h := range hashtags {
tag := strings.TrimPrefix(h, "#")
terms = append(terms, "#"+tag)
}
q := "(" + strings.Join(terms, " OR ") + ") -is:retweet lang:en"
if excludeHandle != "" {
q += " -from:" + excludeHandle
}
return q
}
// --- internal helpers ---
func (c *Client) lookupUserID(ctx context.Context, username string) (string, error) {
var resp struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
endpoint := fmt.Sprintf("%s/users/by/username/%s", apiBase, username)
if err := c.getBearer(ctx, endpoint, &resp); err != nil {
return "", err
}
return resp.Data.ID, nil
}
// VerifyCredentials returns the username of the account the oauth2 token belongs to.
func (c *Client) VerifyCredentials(ctx context.Context) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/users/me", nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+c.oauth2AccessToken)
res, err := c.http.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d: %s", res.StatusCode, raw)
}
var out struct {
Data struct {
Username string `json:"username"`
} `json:"data"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return "", err
}
return out.Data.Username, nil
}
func (c *Client) getBearer(ctx context.Context, endpoint string, out interface{}) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.bearerToken)
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return fmt.Errorf("twitter HTTP %d: %s", res.StatusCode, raw)
}
return json.Unmarshal(raw, out)
}
type tweetsResponse struct {
Data []struct {
ID string `json:"id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
AuthorID string `json:"author_id"`
} `json:"data"`
Includes struct {
Users []struct {
ID string `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"users"`
} `json:"includes"`
}
func (c *Client) tweetsToItems(resp tweetsResponse, defaultHandle string, source models.ContentSource, appName string) []models.ContentItem {
userMap := map[string]struct{ name, username string }{}
for _, u := range resp.Includes.Users {
userMap[u.ID] = struct{ name, username string }{u.Name, u.Username}
}
var items []models.ContentItem
for _, t := range resp.Data {
u := userMap[t.AuthorID]
handle := u.username
if handle == "" {
handle = defaultHandle
}
name := u.name
if name == "" {
name = handle
}
ts, _ := time.Parse(time.RFC3339, t.CreatedAt)
items = append(items, models.ContentItem{
ID: t.ID,
Source: source,
Author: name,
AuthorHandle: handle,
Body: t.Text,
URL: fmt.Sprintf("https://x.com/%s/status/%s", handle, t.ID),
PublishedAt: ts,
AppName: appName,
})
}
return items
}
func clamp(v, min, max int) int {
if v < min {
return min
}
if v > max {
return max
}
return v
}
+124
View File
@@ -0,0 +1,124 @@
package youtube
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"coremarketing/internal/models"
)
const apiBase = "https://www.googleapis.com/youtube/v3"
type Client struct {
apiKey string
maxResults int
http *http.Client
}
func New(apiKey string, maxResults int) *Client {
return &Client{
apiKey: apiKey,
maxResults: maxResults,
http: &http.Client{Timeout: 15 * time.Second},
}
}
// SearchVideos searches YouTube for videos matching the query published after `since`.
func (c *Client) SearchVideos(ctx context.Context, query string, since time.Time, appName string) ([]models.ContentItem, error) {
params := url.Values{
"part": {"snippet"},
"q": {query},
"type": {"video"},
"order": {"date"},
"publishedAfter": {since.UTC().Format(time.RFC3339)},
"maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))},
"key": {c.apiKey},
}
return c.doSearch(ctx, params, appName)
}
// GetChannelVideos fetches recent videos from a specific YouTube channel.
func (c *Client) GetChannelVideos(ctx context.Context, channelID string, since time.Time, appName string) ([]models.ContentItem, error) {
params := url.Values{
"part": {"snippet"},
"channelId": {channelID},
"type": {"video"},
"order": {"date"},
"publishedAfter": {since.UTC().Format(time.RFC3339)},
"maxResults": {strconv.Itoa(clamp(c.maxResults, 1, 50))},
"key": {c.apiKey},
}
return c.doSearch(ctx, params, appName)
}
func (c *Client) doSearch(ctx context.Context, params url.Values, appName string) ([]models.ContentItem, error) {
endpoint := apiBase + "/search?" + params.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
res, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("youtube HTTP %d: %s", res.StatusCode, raw)
}
var resp searchResponse
if err := json.Unmarshal(raw, &resp); err != nil {
return nil, err
}
var items []models.ContentItem
for _, r := range resp.Items {
ts, _ := time.Parse(time.RFC3339, r.Snippet.PublishedAt)
videoURL := "https://www.youtube.com/watch?v=" + r.ID.VideoID
items = append(items, models.ContentItem{
ID: r.ID.VideoID,
Source: models.SourceYouTube,
Author: r.Snippet.ChannelTitle,
AuthorHandle: r.Snippet.ChannelTitle,
Title: r.Snippet.Title,
Body: r.Snippet.Description,
URL: videoURL,
PublishedAt: ts,
AppName: appName,
})
}
return items, nil
}
type searchResponse struct {
Items []struct {
ID struct {
VideoID string `json:"videoId"`
} `json:"id"`
Snippet struct {
Title string `json:"title"`
Description string `json:"description"`
ChannelTitle string `json:"channelTitle"`
PublishedAt string `json:"publishedAt"`
} `json:"snippet"`
} `json:"items"`
}
func clamp(v, min, max int) int {
if v < min {
return min
}
if v > max {
return max
}
return v
}
+272
View File
@@ -0,0 +1,272 @@
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
const (
authURL = "https://twitter.com/i/oauth2/authorize"
tokenURL = "https://api.twitter.com/2/oauth2/token"
redirectURI = "http://localhost:8080/callback"
scopes = "tweet.read tweet.write users.read"
)
type Result struct {
AccessToken string
}
// TwitterOAuth2 runs the OAuth 2.0 PKCE flow for Twitter/X. It opens the
// browser, starts a local callback server on :8080, and exchanges the
// authorization code for a user access token.
func TwitterOAuth2(ctx context.Context, clientID, clientSecret string) (*Result, error) {
verifier, challenge, state, err := generatePKCE()
if err != nil {
return nil, fmt.Errorf("generating PKCE values: %w", err)
}
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {redirectURI},
"scope": {scopes},
"state": {state},
"code_challenge": {challenge},
"code_challenge_method": {"S256"},
}
authFullURL := authURL + "?" + params.Encode()
codeCh := make(chan string, 1)
errCh := make(chan error, 1)
mux := http.NewServeMux()
srv := &http.Server{Addr: ":8080", Handler: mux}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("state") != state {
http.Error(w, "state mismatch", http.StatusBadRequest)
errCh <- fmt.Errorf("OAuth state mismatch — possible CSRF")
return
}
if e := q.Get("error"); e != "" {
http.Error(w, e, http.StatusBadRequest)
errCh <- fmt.Errorf("authorization denied: %s", e)
return
}
code := q.Get("code")
if code == "" {
http.Error(w, "missing code", http.StatusBadRequest)
errCh <- fmt.Errorf("no code in OAuth callback")
return
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprintln(w, "<html><body><h2>Authorization successful!</h2><p>You can close this tab.</p></body></html>")
codeCh <- code
})
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- fmt.Errorf("local callback server: %w", err)
}
}()
defer srv.Shutdown(context.Background())
fmt.Printf("Open this URL in your browser to authorize:\n\n %s\n\n", authFullURL)
var code string
select {
case code = <-codeCh:
case err = <-errCh:
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(5 * time.Minute):
return nil, fmt.Errorf("timed out waiting for authorization")
}
return exchangeCode(ctx, clientID, clientSecret, code, verifier)
}
func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier string) (*Result, error) {
data := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {redirectURI},
"code_verifier": {verifier},
}
if clientSecret == "" {
data.Set("client_id", clientID)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if clientSecret != "" {
req.SetBasicAuth(clientID, clientSecret)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token exchange HTTP %d: %s", res.StatusCode, raw)
}
var out struct {
AccessToken string `json:"access_token"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return nil, err
}
if out.AccessToken == "" {
return nil, fmt.Errorf("no access_token in response: %s", raw)
}
return &Result{AccessToken: out.AccessToken}, nil
}
// LinkedInOAuth2 runs the standard OAuth 2.0 authorization code flow for
// LinkedIn. Unlike Twitter, LinkedIn uses client_secret instead of PKCE.
func LinkedInOAuth2(ctx context.Context, clientID, clientSecret string) (*Result, error) {
state, err := generateState()
if err != nil {
return nil, fmt.Errorf("generating state: %w", err)
}
params := url.Values{
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {redirectURI},
"scope": {"w_member_social openid profile"},
"state": {state},
}
authFullURL := "https://www.linkedin.com/oauth/v2/authorization?" + params.Encode()
codeCh := make(chan string, 1)
errCh := make(chan error, 1)
mux := http.NewServeMux()
srv := &http.Server{Addr: ":8080", Handler: mux}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
if q.Get("state") != state {
http.Error(w, "state mismatch", http.StatusBadRequest)
errCh <- fmt.Errorf("OAuth state mismatch — possible CSRF")
return
}
if e := q.Get("error"); e != "" {
http.Error(w, e, http.StatusBadRequest)
errCh <- fmt.Errorf("authorization denied: %s", e)
return
}
code := q.Get("code")
if code == "" {
http.Error(w, "missing code", http.StatusBadRequest)
errCh <- fmt.Errorf("no code in OAuth callback")
return
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprintln(w, "<html><body><h2>Authorization successful!</h2><p>You can close this tab.</p></body></html>")
codeCh <- code
})
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- fmt.Errorf("local callback server: %w", err)
}
}()
defer srv.Shutdown(context.Background())
fmt.Printf("Open this URL in your browser to authorize LinkedIn:\n\n %s\n\n", authFullURL)
var code string
select {
case code = <-codeCh:
case err = <-errCh:
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(5 * time.Minute):
return nil, fmt.Errorf("timed out waiting for authorization")
}
return linkedinExchangeCode(ctx, clientID, clientSecret, code)
}
func linkedinExchangeCode(ctx context.Context, clientID, clientSecret, code string) (*Result, error) {
data := url.Values{
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {redirectURI},
"client_id": {clientID},
"client_secret": {clientSecret},
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://www.linkedin.com/oauth/v2/accessToken",
strings.NewReader(data.Encode()),
)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token exchange HTTP %d: %s", res.StatusCode, raw)
}
var out struct {
AccessToken string `json:"access_token"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return nil, err
}
if out.AccessToken == "" {
return nil, fmt.Errorf("no access_token in response: %s", raw)
}
return &Result{AccessToken: out.AccessToken}, nil
}
func generatePKCE() (verifier, challenge, state string, err error) {
vb := make([]byte, 32)
if _, err = rand.Read(vb); err != nil {
return
}
verifier = base64.RawURLEncoding.EncodeToString(vb)
h := sha256.Sum256([]byte(verifier))
challenge = base64.RawURLEncoding.EncodeToString(h[:])
state, err = generateState()
return
}
func generateState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
+182
View File
@@ -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)
}
+106
View File
@@ -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
}
+31
View File
@@ -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
}
+50
View File
@@ -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
}
+65
View File
@@ -0,0 +1,65 @@
package store
import (
"encoding/json"
"fmt"
"os"
"time"
)
type GeneratedPost struct {
ID string `json:"id"`
AppName string `json:"app_name"`
Content string `json:"content"`
SourceURL string `json:"source_url,omitempty"`
GeneratedAt time.Time `json:"generated_at"`
}
type Store struct {
Posts []GeneratedPost `json:"posts"`
path string
}
func Load(path string) (*Store, error) {
s := &Store{path: path}
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return s, nil
}
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, s); err != nil {
return nil, err
}
s.path = path
return s, nil
}
func (s *Store) Save() error {
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.path, data, 0644)
}
func (s *Store) Add(appName, content, sourceURL string) {
s.Posts = append(s.Posts, GeneratedPost{
ID: fmt.Sprintf("%d", time.Now().UnixNano()),
AppName: appName,
Content: content,
SourceURL: sourceURL,
GeneratedAt: time.Now(),
})
}
func (s *Store) Remove(ids map[string]bool) {
kept := s.Posts[:0]
for _, p := range s.Posts {
if !ids[p.ID] {
kept = append(kept, p)
}
}
s.Posts = kept
}
+1013
View File
File diff suppressed because it is too large Load Diff
+85
View File
@@ -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)
}
+221
View File
@@ -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 <twitter|linkedin> [config.yaml]\n")
os.Exit(1)
}
platform := rest[0]
rest = rest[1:]
if len(rest) > 0 {
cfgPath = rest[0]
}
switch platform {
case "twitter":
runAuth(cfgPath)
case "linkedin":
runLinkedInAuth(cfgPath)
default:
fmt.Fprintf(os.Stderr, "Unknown platform %q. Use twitter or linkedin.\n", platform)
os.Exit(1)
}
return
}
if len(os.Args) > 1 {
cfgPath = os.Args[1]
}
cfg, err := config.Load(cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n\n", err)
fmt.Fprintf(os.Stderr, "Copy config.yaml and fill in your credentials.\n")
os.Exit(1)
}
// If Twitter is configured but has no access token, 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)
}