If the Subreddits box is empty, the AI suggests up to eight, by the relationship, each with who is there. Each is looked up on Reddit (with the app's client ID and secret) and left out if it doesn't exist, is private, 18+, restricted or archived; the first five kept fill the box. The form lists every suggestion with members, post types and why any was left out. Lookups are cached for drafting. Without Reddit keys the suggestions are kept and the form says they weren't checked. The Reddit client now returns ErrNotFound and ErrForbidden, and treats an empty about listing as not found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
276 lines
7.7 KiB
Go
276 lines
7.7 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"supermarket/examples"
|
|
"supermarket/internal/ai"
|
|
"supermarket/internal/api/reddit"
|
|
"supermarket/internal/content"
|
|
"supermarket/internal/inventory"
|
|
"supermarket/internal/profile"
|
|
)
|
|
|
|
func (s *Server) inventoryList(w http.ResponseWriter, r *http.Request) {
|
|
rel := r.URL.Query().Get("relationship")
|
|
entries, err := inventory.List(s.DB, rel)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
s.render(w, r, "inventory", page{Title: "Inventory", Nav: "inventory", Data: map[string]any{
|
|
"Entries": entries,
|
|
"Relationship": rel,
|
|
"Relationships": inventory.Relationships,
|
|
}})
|
|
}
|
|
|
|
type entryData struct {
|
|
E *inventory.Entry
|
|
Relationships []string
|
|
NoAI bool // no AI provider yet: filling in from the website can't work
|
|
DraftURL string // the address to fill in from
|
|
Filled []string // after filling in: what was filled
|
|
Suggestions []inventory.Suggestion
|
|
CanCheck bool // Reddit could be asked about the suggestions
|
|
Drafted bool
|
|
}
|
|
|
|
func (s *Server) entryForm(e *inventory.Entry) entryData {
|
|
d := entryData{E: e, Relationships: inventory.Relationships, NoAI: !s.aiReady()}
|
|
if len(e.Websites) > 0 {
|
|
d.DraftURL = e.Websites[0]
|
|
}
|
|
return d
|
|
}
|
|
|
|
func (s *Server) inventoryEdit(w http.ResponseWriter, r *http.Request) {
|
|
e := &inventory.Entry{Relationship: inventory.Partner}
|
|
if idStr := r.PathValue("id"); idStr != "" {
|
|
id, err := strconv.ParseInt(idStr, 10, 64)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
e, err = inventory.Get(s.DB, id)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
if e == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
}
|
|
title := "New entry"
|
|
if e.ID != 0 {
|
|
title = e.Name
|
|
}
|
|
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Data: s.entryForm(e)})
|
|
}
|
|
|
|
func (s *Server) inventorySave(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
e := entryFromForm(r)
|
|
if err := inventory.Save(s.DB, e); err != nil {
|
|
title := e.Name
|
|
if title == "" {
|
|
title = "New entry"
|
|
}
|
|
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Error: err.Error(), Data: s.entryForm(e)})
|
|
return
|
|
}
|
|
redirect(w, r, "/inventory", "saved")
|
|
}
|
|
|
|
func entryFromForm(r *http.Request) *inventory.Entry {
|
|
f := r.PostForm
|
|
id, _ := strconv.ParseInt(f.Get("id"), 10, 64)
|
|
return &inventory.Entry{
|
|
ID: id,
|
|
Name: f.Get("name"),
|
|
Relationship: f.Get("relationship"),
|
|
Description: f.Get("description"),
|
|
Websites: profile.Lines(f.Get("websites")),
|
|
TwitterHandle: f.Get("twitter_handle"),
|
|
YouTubeChannelID: f.Get("youtube_channel_id"),
|
|
InstagramHandle: f.Get("instagram_handle"),
|
|
LinkedIn: f.Get("linkedin"),
|
|
Subreddits: profile.Lines(f.Get("subreddits")),
|
|
RSS: profile.Lines(f.Get("rss")),
|
|
Hashtags: strings.Fields(strings.ReplaceAll(f.Get("hashtags"), ",", " ")),
|
|
Keywords: profile.Lines(f.Get("keywords")),
|
|
TalkingPoints: f.Get("talking_points"),
|
|
MentionPolicy: f.Get("mention_policy"),
|
|
}
|
|
}
|
|
|
|
// inventoryFill fills the form's empty boxes from the entry's website, with
|
|
// the AI, and shows the form again, unsaved.
|
|
func (s *Server) inventoryFill(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
e := entryFromForm(r)
|
|
d := s.entryForm(e)
|
|
d.DraftURL = strings.TrimSpace(r.PostForm.Get("draft_url"))
|
|
title := e.Name
|
|
if title == "" {
|
|
title = "New entry"
|
|
}
|
|
show := func(errMsg string) {
|
|
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Error: errMsg, Data: d})
|
|
}
|
|
if d.DraftURL == "" {
|
|
show("Enter their website to fill in from.")
|
|
return
|
|
}
|
|
cfg, err := ai.LoadConfig(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
client, err := ai.New(cfg, s.Secrets)
|
|
if err != nil {
|
|
show(err.Error() + ".")
|
|
return
|
|
}
|
|
ours, err := profile.Load(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
|
|
defer cancel()
|
|
check := s.subredditCheck(ctx)
|
|
d.CanCheck = check != nil
|
|
res, err := inventory.Fill(ctx, client, e, d.DraftURL, ours, check)
|
|
d.Filled, d.Suggestions, d.Drafted = res.Filled, res.Suggestions, true
|
|
if err != nil {
|
|
// Links read before the model failed are kept.
|
|
show("Couldn't fill in everything: " + err.Error())
|
|
return
|
|
}
|
|
show("")
|
|
}
|
|
|
|
func (s *Server) inventoryDelete(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if err := inventory.Delete(s.DB, id); err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
redirect(w, r, "/inventory", "deleted")
|
|
}
|
|
|
|
func (s *Server) inventoryImportPage(w http.ResponseWriter, r *http.Request) {
|
|
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Data: map[string]any{
|
|
"Relationships": inventory.Relationships,
|
|
}})
|
|
}
|
|
|
|
const maxImportBytes = 4 << 20
|
|
|
|
func (s *Server) inventoryImport(w http.ResponseWriter, r *http.Request) {
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxImportBytes+64<<10)
|
|
if err := r.ParseMultipartForm(maxImportBytes); err != nil && !errors.Is(err, http.ErrNotMultipart) {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
rel := r.FormValue("relationship")
|
|
overwrite := r.FormValue("overwrite") == "on"
|
|
show := func(errMsg string, res *inventory.ImportResult) {
|
|
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Error: errMsg, Data: map[string]any{
|
|
"Relationships": inventory.Relationships,
|
|
"Result": res,
|
|
"YAML": r.FormValue("yaml"),
|
|
}})
|
|
}
|
|
|
|
var data []byte
|
|
switch {
|
|
case r.FormValue("example") == "federated":
|
|
data = examples.FederatedInventory
|
|
case r.MultipartForm != nil && len(r.MultipartForm.File["file"]) > 0:
|
|
f, err := r.MultipartForm.File["file"][0].Open()
|
|
if err != nil {
|
|
show(err.Error(), nil)
|
|
return
|
|
}
|
|
data, err = io.ReadAll(io.LimitReader(f, maxImportBytes))
|
|
f.Close()
|
|
if err != nil {
|
|
show(err.Error(), nil)
|
|
return
|
|
}
|
|
default:
|
|
data = []byte(r.FormValue("yaml"))
|
|
}
|
|
if len(strings.TrimSpace(string(data))) == 0 {
|
|
show("Paste a list, choose a file, or load the example.", nil)
|
|
return
|
|
}
|
|
|
|
entries, err := inventory.ParseYAML(data, rel)
|
|
if err != nil {
|
|
show(err.Error(), nil)
|
|
return
|
|
}
|
|
res := inventory.Import(s.DB, entries, overwrite)
|
|
show("", &res)
|
|
}
|
|
|
|
func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) {
|
|
entries, err := inventory.List(s.DB, "")
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
data, err := inventory.ExportYAML(entries)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/yaml")
|
|
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-inventory.yaml"`)
|
|
w.Write(data)
|
|
}
|
|
|
|
// subredditCheck looks subreddits up on Reddit for Fill, using the cache
|
|
// and caching what it reads (drafting for the subreddit uses it later). It's
|
|
// nil if Reddit can't be asked: no client ID and secret.
|
|
func (s *Server) subredditCheck(ctx context.Context) inventory.SubredditCheck {
|
|
c, err := s.redditReader(ctx)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return func(ctx context.Context, name string) (*reddit.Subreddit, error) {
|
|
if cached, err := content.GetSubreddit(s.DB, name); err == nil && cached != nil &&
|
|
time.Since(cached.FetchedAt) < content.SubredditMaxAge {
|
|
return cached, nil
|
|
}
|
|
info, err := c.SubredditInfo(ctx, name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := content.SaveSubreddit(s.DB, info); err != nil {
|
|
s.Log.Error("caching subreddit", "name", name, "err", err)
|
|
}
|
|
return info, nil
|
|
}
|
|
}
|