package web import ( "context" "errors" "fmt" "net/http" "strconv" "strings" "time" "supermarket/internal/ai" "supermarket/internal/api/reddit" "supermarket/internal/api/sitemap" "supermarket/internal/content" "supermarket/internal/fetcher" "supermarket/internal/inventory" "supermarket/internal/models" "supermarket/internal/profile" ) // maxPerItem caps "one post per item", which makes one AI call per item. const maxPerItem = 10 // --- Sources: entries and their fetched items --- type contentRow struct { Entry inventory.Entry Own bool Name string Sources []string Waiting int LastChecked time.Time } func (s *Server) contentIndex(w http.ResponseWriter, r *http.Request) { entries, err := inventory.List(s.DB, "") if err != nil { s.serverError(w, err) return } counts, err := content.Counts(s.DB) if err != nil { s.serverError(w, err) return } p, err := profile.Load(s.DB) if err != nil { s.serverError(w, err) return } own := content.OwnEntry(p) ownLast, _ := content.LastChecked(s.DB, own.Name) ownSources := fetcher.Sources(own) if len(p.Products) > 0 { ownSources = append([]string{plural(len(p.Products), "product")}, ownSources...) } rows := make([]contentRow, 0, len(entries)+1) rows = append(rows, contentRow{Entry: *own, Own: true, Name: ifElse(p.Name != "", p.Name, "Your company"), Sources: ownSources, Waiting: counts[own.Name], LastChecked: ownLast}) for _, e := range entries { last, _ := content.LastChecked(s.DB, e.Name) rows = append(rows, contentRow{Entry: e, Name: e.Name, Sources: fetcher.Sources(&e), Waiting: counts[strings.ToLower(e.Name)], LastChecked: last}) } s.render(w, r, "content", page{Title: "Sources", Nav: "content/sources", Data: map[string]any{"Rows": rows}}) } type channelChoice struct { content.Channel Connected bool } type entryPage struct { Entry *inventory.Entry Own bool // the company's own products, feeds and pages Base string // the page's address: /content/ or /content/own Name string // what to call the entry Products []content.Item Sources []string Items []content.Item ShowDismissed bool LastChecked time.Time Since time.Time Channels []channelChoice ProfileSet bool Subreddits []string // suggestions: the entry's, then the profile's // After a fetch Fetched bool NewItems int Errors []string Skipped []string } func (s *Server) loadEntry(w http.ResponseWriter, r *http.Request) *inventory.Entry { if r.PathValue("id") == "own" { p, err := profile.Load(s.DB) if err != nil { s.serverError(w, err) return nil } if err := content.SyncProducts(s.DB, p); err != nil { s.serverError(w, err) return nil } return content.OwnEntry(p) } id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) if err != nil { http.NotFound(w, r) return nil } e, err := inventory.Get(s.DB, id) if err != nil { s.serverError(w, err) return nil } if e == nil { http.NotFound(w, r) } return e } func (s *Server) entryData(e *inventory.Entry, showDismissed bool) (*entryPage, error) { items, err := content.ListItems(s.DB, e.Name, showDismissed, 200) if err != nil { return nil, err } // Products are always there to pick from; they're listed on their own. var products []content.Item if content.IsOwn(e) { rest := items[:0] for _, it := range items { if it.Source == models.SourceProduct { products = append(products, it) } else { rest = append(rest, it) } } items = rest } last, err := content.LastChecked(s.DB, e.Name) if err != nil { return nil, err } since, _ := content.Since(s.DB, e.Name, time.Now()) p, err := profile.Load(s.DB) if err != nil { return nil, err } conn := s.connected() var chans []channelChoice for _, c := range content.Channels { chans = append(chans, channelChoice{c, conn[c.ID]}) } var subs []string seen := map[string]bool{} for _, list := range [][]string{e.Subreddits, p.Accounts.Subreddits} { for _, sr := range list { if n := reddit.CleanName(sr); n != "" && !seen[strings.ToLower(n)] { seen[strings.ToLower(n)] = true subs = append(subs, n) } } } base, name := fmt.Sprintf("/content/%d", e.ID), e.Name if content.IsOwn(e) { base, name = "/content/own", ifElse(p.Name != "", p.Name, "Your company") } return &entryPage{Own: content.IsOwn(e), Base: base, Name: name, Products: products, Subreddits: subs, Entry: e, Sources: fetcher.Sources(e), Items: items, ShowDismissed: showDismissed, LastChecked: last, Since: since, Channels: chans, ProfileSet: p.IsSet()}, nil } func (s *Server) contentEntry(w http.ResponseWriter, r *http.Request) { e := s.loadEntry(w, r) if e == nil { return } d, err := s.entryData(e, r.URL.Query().Get("dismissed") == "1") if err != nil { s.serverError(w, err) return } s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content/sources", Data: d}) } func (s *Server) contentFetch(w http.ResponseWriter, r *http.Request) { e := s.loadEntry(w, r) if e == nil { return } now := time.Now() since, err := content.Since(s.DB, e.Name, now) if err != nil { s.serverError(w, err) return } ctx, cancel := context.WithTimeout(r.Context(), 90*time.Second) defer cancel() f := s.fetcher() if content.IsOwn(e) { f.Sitemap = sitemap.New("Supermarket/" + s.Version + " (sitemap reader)") } res := f.Fetch(ctx, e, since) n, err := content.SaveItems(s.DB, res.Items) if err != nil { s.serverError(w, err) return } // Only move the start of the next fetch on if every source answered, so // a failed source is read from the same point next time. if len(res.Errors) == 0 { if err := content.SetLastChecked(s.DB, e.Name, now); err != nil { s.serverError(w, err) return } } d, err := s.entryData(e, false) if err != nil { s.serverError(w, err) return } d.Fetched, d.NewItems, d.Errors, d.Skipped = true, n, res.Errors, res.Skipped s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content/sources", Data: d}) } // contentItems handles the item list's buttons: dismiss, restore, write. func (s *Server) contentItems(w http.ResponseWriter, r *http.Request) { e := s.loadEntry(w, r) if e == nil { return } if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } ids := r.PostForm["item"] back := fmt.Sprintf("/content/%d", e.ID) if content.IsOwn(e) { back = "/content/own" } showErr := func(msg string) { d, err := s.entryData(e, r.PostForm.Get("dismissed") == "1") if err != nil { s.serverError(w, err) return } s.render(w, r, "content-entry", page{Title: d.Name, Nav: "content/sources", Error: msg, Data: d}) } if len(ids) == 0 { showErr("Select at least one item first.") return } switch r.PostForm.Get("action") { case "dismiss": if err := content.Dismiss(s.DB, ids); err != nil { s.serverError(w, err) return } redirect(w, r, back, "dismissed") case "restore": if err := content.Restore(s.DB, ids); err != nil { s.serverError(w, err) return } redirect(w, r, back+"?dismissed=1", "restored") case "write": if err := s.writeDrafts(r, e, ids); err != nil { showErr(err.Error()) return } redirect(w, r, "/inbox", "drafted") default: http.Error(w, "unknown action", http.StatusBadRequest) } } func (s *Server) writeDrafts(r *http.Request, e *inventory.Entry, ids []string) error { channels := r.PostForm["channel"] if len(channels) == 0 { return errors.New("choose at least one channel to write for") } perItem := r.PostForm.Get("mode") == "each" if perItem && len(ids) > maxPerItem { return fmt.Errorf("one post per item works on up to %d items at a time; you selected %d", maxPerItem, len(ids)) } p, err := profile.Load(s.DB) if err != nil { return err } cfg, err := ai.LoadConfig(s.DB) if err != nil { return err } client, err := ai.New(cfg, s.Secrets) if err != nil { return err } items, err := content.GetItems(s.DB, ids) if err != nil { return err } // Keep channels in display order whatever order the form sent. var ordered []string for _, c := range content.Channels { for _, ch := range channels { if ch == c.ID { ordered = append(ordered, c.ID) break } } } req := content.Request{Profile: p, Entry: e} for _, ch := range ordered { if ch == content.ChannelReddit { req.Subreddit = reddit.CleanName(r.PostForm.Get("subreddit")) if req.Subreddit == "" { return errors.New("choose a subreddit for the Reddit post") } // The rules go into the prompt; without them the model is told // to be careful, and the Inbox warns. info, err := s.subreddit(r.Context(), req.Subreddit, false) if err != nil { s.Log.Warn("reddit: couldn't read the subreddit's rules", "subreddit", req.Subreddit, "err", err) } req.SubredditInfo = info } } groups := [][]content.Item{items} if perItem { groups = groups[:0] for _, it := range items { groups = append(groups, []content.Item{it}) } } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute) defer cancel() written := 0 for _, g := range groups { req.Items, req.Channels = g, ordered drafts, err := content.Generate(ctx, client, req) if err != nil { if written > 0 { return fmt.Errorf("wrote %d set(s) of drafts, then: %w", written, err) } return err } if _, err := content.CreateDrafts(s.DB, drafts); err != nil { return err } written++ } return nil }