Files
supermarket/internal/legacy/legacy.go
T
davidandClaude Opus 5.5 13bf18facc Phase 1, part 1: fetch, write and publish posts from the web app
Brings back posting, which Phase 0 removed with the terminal interface.

- Content page: per inventory entry, fetch its X account, X hashtag
  search, YouTube channel and RSS/Atom feeds (new), then select, dismiss
  or restore the fetched items, which are kept in the database.
- Writing: one AI call returns a draft per channel (X and LinkedIn),
  prompted from the company profile, the entry's relationship, talking
  points and mention policy, and each channel's rules. Fetched text is
  quoted as untrusted. An over-long X draft gets one request to shorten.
- Drafts page: edit with a live length counter that counts like X, then
  publish each draft on its own. A draft is claimed before posting so it
  can't go out twice; failures are kept on the draft for a retry; X
  tokens are refreshed and saved.
- Migration 2 adds content_items and drafts, and turns queued posts into
  drafts for the platforms they hadn't reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:24 -07:00

319 lines
8.8 KiB
Go

// Package legacy imports the data of the old terminal app (config.yaml,
// state.json, posts.json, dismissed.json) once, on the first start that finds
// them in the data folder's import/ directory. install.sh copies them there.
package legacy
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v3"
"supermarket/internal/ai"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
const doneKey = "legacy_import"
// ContentSettings are the old app's posting and fetching settings, which the
// content module reads.
type ContentSettings struct {
MaxLength int `json:"max_length"`
MaxResults int `json:"max_results"`
LookbackDays int `json:"lookback_days"`
}
const ContentSettingsKey = "content"
// Status records that the import ran, and what it did.
type Status struct {
At time.Time `json:"at"`
Summary []string `json:"summary"`
}
// LoadStatus returns the import's status, or nil if it never ran.
func LoadStatus(d *db.DB) (*Status, error) {
var s Status
ok, err := d.GetJSON(doneKey, &s)
if err != nil || !ok {
return nil, err
}
return &s, nil
}
type oldConfig struct {
Applications []inventory.Entry `yaml:"applications"`
Credentials struct {
Twitter struct {
BearerToken string `yaml:"bearer_token"`
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
OAuth2AccessToken string `yaml:"oauth2_access_token"`
OAuth2RefreshToken string `yaml:"oauth2_refresh_token"`
} `yaml:"twitter"`
LinkedIn struct {
ClientID string `yaml:"client_id"`
ClientSecret string `yaml:"client_secret"`
AccessToken string `yaml:"access_token"`
AuthorURN string `yaml:"author_urn"`
} `yaml:"linkedin"`
YouTube struct {
APIKey string `yaml:"api_key"`
} `yaml:"youtube"`
Claude struct {
APIKey string `yaml:"api_key"`
Model string `yaml:"model"`
} `yaml:"claude"`
} `yaml:"credentials"`
Posting struct {
TwitterHandle string `yaml:"twitter_handle"`
MaxLength int `yaml:"max_length"`
} `yaml:"posting"`
Settings struct {
MaxResults int `yaml:"max_results"`
DefaultLookbackDays int `yaml:"default_lookback_days"`
} `yaml:"settings"`
}
// Import imports dir's files if it hasn't already. Nothing in dir is
// changed or deleted. It returns nil, nil when there is nothing to do.
func Import(d *db.DB, sec *secrets.Store, dir string) (*Status, error) {
if s, err := LoadStatus(d); err != nil || s != nil {
return nil, err
}
cfgPath := filepath.Join(dir, "config.yaml")
raw, err := os.ReadFile(cfgPath)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var cfg oldConfig
if err := yaml.Unmarshal(raw, &cfg); err != nil {
return nil, fmt.Errorf("%s: %w", cfgPath, err)
}
st := &Status{At: time.Now().UTC()}
note := func(format string, args ...any) { st.Summary = append(st.Summary, fmt.Sprintf(format, args...)) }
// The old list was Federated Core's apps, which Federated promotes: import
// them as partners, for the user to re-label.
for i := range cfg.Applications {
if strings.TrimSpace(cfg.Applications[i].Relationship) == "" {
cfg.Applications[i].Relationship = inventory.Partner
}
}
res := inventory.Import(d, cfg.Applications, false)
note("Inventory: %d added as partners, %d already there", res.Added, res.Skipped)
for _, e := range res.Errors {
note("Inventory error: %s", e)
}
c := cfg.Credentials
creds := map[string]string{
secrets.XBearerToken: c.Twitter.BearerToken,
secrets.XClientID: c.Twitter.ClientID,
secrets.XClientSecret: c.Twitter.ClientSecret,
secrets.XAccessToken: c.Twitter.OAuth2AccessToken,
secrets.XRefreshToken: c.Twitter.OAuth2RefreshToken,
secrets.LinkedInClientID: c.LinkedIn.ClientID,
secrets.LinkedInClientSecret: c.LinkedIn.ClientSecret,
secrets.LinkedInAccessToken: c.LinkedIn.AccessToken,
secrets.LinkedInAuthorURN: c.LinkedIn.AuthorURN,
secrets.YouTubeAPIKey: c.YouTube.APIKey,
secrets.AnthropicAPIKey: c.Claude.APIKey,
}
// Only fill in what's missing, so a re-import never replaces newer
// credentials entered in the app.
updates := map[string]string{}
for k, v := range creds {
v = strings.TrimSpace(v)
if v != "" && !sec.Has(k) {
updates[k] = v
}
}
if len(updates) > 0 {
if err := sec.Set(updates); err != nil {
return nil, fmt.Errorf("saving imported credentials: %w", err)
}
}
note("Credentials: %d imported", len(updates))
if c.Claude.APIKey != "" {
aiCfg, err := ai.LoadConfig(d)
if err != nil {
return nil, err
}
if m := strings.TrimSpace(c.Claude.Model); m != "" {
aiCfg.Provider = ai.ProviderAnthropic
aiCfg.Model = m
if err := ai.SaveConfig(d, aiCfg); err != nil {
return nil, err
}
note("AI: Anthropic, model %s (from the old config; change it in Settings)", m)
}
}
if h := strings.TrimSpace(cfg.Posting.TwitterHandle); h != "" {
p, err := profile.Load(d)
if err != nil {
return nil, err
}
if p.Accounts.X == "" {
p.Accounts.X = h
if err := profile.Save(d, p); err != nil {
return nil, err
}
note("Profile: X account @%s", strings.TrimPrefix(h, "@"))
}
}
cs := ContentSettings{MaxLength: 280, MaxResults: 20, LookbackDays: 7}
if cfg.Posting.MaxLength > 0 {
cs.MaxLength = cfg.Posting.MaxLength
}
if cfg.Settings.MaxResults > 0 {
cs.MaxResults = cfg.Settings.MaxResults
}
if cfg.Settings.DefaultLookbackDays > 0 {
cs.LookbackDays = cfg.Settings.DefaultLookbackDays
}
if err := d.PutJSON(ContentSettingsKey, cs); err != nil {
return nil, err
}
n, err := importState(d, filepath.Join(dir, "state.json"))
if err != nil {
return nil, err
}
note("Last-checked times: %d", n)
n, err = importPosts(d, filepath.Join(dir, "posts.json"))
if err != nil {
return nil, err
}
note("Queued posts: %d", n)
n, err = importDismissed(d, filepath.Join(dir, "dismissed.json"))
if err != nil {
return nil, err
}
note("Dismissed items: %d", n)
if err := d.PutJSON(doneKey, st); err != nil {
return nil, err
}
return st, nil
}
// readJSON decodes path into out, reporting false if the file doesn't exist.
func readJSON(path string, out any) (bool, error) {
raw, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
if err != nil {
return false, err
}
if err := json.Unmarshal(raw, out); err != nil {
return false, fmt.Errorf("%s: %w", path, err)
}
return true, nil
}
func importState(d *db.DB, path string) (int, error) {
var st struct {
LastChecked map[string]time.Time `json:"last_checked"`
}
if ok, err := readJSON(path, &st); !ok || err != nil {
return 0, err
}
n := 0
for name, t := range st.LastChecked {
if _, err := d.Exec(`INSERT OR IGNORE INTO fetch_state (key, last_checked) VALUES (?, ?)`,
"inventory:"+name, t.UTC().Format(time.RFC3339)); err != nil {
return n, err
}
n++
}
return n, nil
}
func importPosts(d *db.DB, path string) (int, error) {
var ps struct {
Posts []struct {
ID string `json:"id"`
AppName string `json:"app_name"`
Content string `json:"content"`
SourceURL string `json:"source_url"`
GeneratedAt time.Time `json:"generated_at"`
PostedTo []string `json:"posted_to"`
} `json:"posts"`
}
if ok, err := readJSON(path, &ps); !ok || err != nil {
return 0, err
}
// Each queued post becomes a draft for every platform it hasn't reached.
n := 0
for _, p := range ps.Posts {
posted := map[string]bool{}
for _, ch := range p.PostedTo {
posted[ch] = true
}
at := p.GeneratedAt.UTC().Format(time.RFC3339)
added := false
for _, ch := range []string{"x", "linkedin"} {
if posted[ch] {
continue
}
// The batch is the old post's ID, so a re-run adds nothing twice.
var exists int
if err := d.QueryRow(`SELECT count(*) FROM drafts WHERE batch = ? AND channel = ?`, p.ID, ch).Scan(&exists); err != nil {
return n, err
}
if exists > 0 {
continue
}
if _, err := d.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, content, source_url, created_at, updated_at)
VALUES (?, ?, COALESCE((SELECT relationship FROM inventory WHERE name = ?), 'partner'), ?, ?, ?, ?, ?)`,
p.ID, p.AppName, p.AppName, ch, p.Content, p.SourceURL, at, at); err != nil {
return n, err
}
added = true
}
if added {
n++
}
}
return n, nil
}
func importDismissed(d *db.DB, path string) (int, error) {
var ds struct {
IDs map[string]bool `json:"ids"`
}
if ok, err := readJSON(path, &ds); !ok || err != nil {
return 0, err
}
n := 0
for id, dismissed := range ds.IDs {
if !dismissed {
continue
}
if _, err := d.Exec(`INSERT OR IGNORE INTO dismissed (item_id) VALUES (?)`, id); err != nil {
return n, err
}
n++
}
return n, nil
}