package web import ( "context" "errors" "fmt" "net/http" "strconv" "strings" "time" "supermarket/internal/api/reddit" "supermarket/internal/content" "supermarket/internal/profile" "supermarket/internal/utm" ) // --- The Inbox: everything waiting for the user's approval --- // inboxSection is one module's share of the Inbox. Later phases add their // own (prospects to send to the CRM, SEO changes to open as pull requests). type inboxSection struct { Module string Batches []*draftBatch } type draftBatch struct { Batch string InventoryName string Kind string CreatedAt time.Time SourceURL string Drafts []content.Draft } // inboxCount is the number shown next to Inbox in the menu. func (s *Server) inboxCount() int { n, err := content.CountDrafts(s.DB) if err != nil { s.Log.Error("counting the inbox", "err", err) } return n } // groupBatches puts drafts written together side by side, channels in // display order, keeping the order the drafts came in. func groupBatches(drafts []content.Draft) []*draftBatch { var batches []*draftBatch byID := map[string]*draftBatch{} for _, d := range drafts { b := byID[d.Batch] if b == nil { b = &draftBatch{Batch: d.Batch, InventoryName: d.InventoryName, Kind: d.Kind, CreatedAt: d.CreatedAt, SourceURL: d.SourceURL} byID[d.Batch] = b batches = append(batches, b) } b.Drafts = append(b.Drafts, d) } for _, b := range batches { ordered := make([]content.Draft, 0, len(b.Drafts)) for _, c := range content.Channels { for _, d := range b.Drafts { if d.Channel == c.ID { ordered = append(ordered, d) } } } b.Drafts = ordered } return batches } func (s *Server) connected() map[string]bool { out := map[string]bool{} for id := range s.publishers() { out[id] = true } return out } func (s *Server) inboxPage(w http.ResponseWriter, r *http.Request) { s.renderInbox(w, r, "") } func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg string) { pending, err := content.ListDrafts(s.DB, 200, content.StatusDraft, content.StatusFailed) if err != nil { s.serverError(w, err) return } var sections []inboxSection if len(pending) > 0 { sections = append(sections, inboxSection{Module: "Content", Batches: groupBatches(pending)}) } s.render(w, r, "inbox", page{Title: "Inbox", Nav: "inbox", Error: errMsg, Data: map[string]any{ "Sections": sections, "Reddit": s.redditViews(r.Context(), pending), "Connected": s.connected(), "Tagged": s.tagger() != nil, "Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal), "Zone": time.Now().Format("MST"), }}) } // redditView is what the Inbox shows with a Reddit draft. type redditView struct { Info *reddit.Subreddit Warnings []string } // redditViews works out the rules and warnings for the Reddit drafts. It // reads the account's recent posts once (cached for a few minutes). func (s *Server) redditViews(ctx context.Context, drafts []content.Draft) map[int64]*redditView { views := map[int64]*redditView{} var history []reddit.Submission historyRead := false tags := s.tagger() for _, d := range drafts { if d.Channel != content.ChannelReddit { continue } if !historyRead { hctx, cancel := context.WithTimeout(ctx, 8*time.Second) history = s.redditHistory(hctx) cancel() historyRead = true } info, _ := content.GetSubreddit(s.DB, d.Target) check := content.RedditCheck{Target: d.Target, HasLink: d.SourceURL != "", Info: info, History: history, Now: time.Now()} if tags != nil { check.Own = tags.Own check.OwnLink = tags.Own(d.SourceURL) || tags.HasOwnLink(d.Content) } views[d.ID] = &redditView{Info: info, Warnings: content.RedditWarnings(check)} } return views } // refreshRules fetches a subreddit's rules again. func (s *Server) refreshRules(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() if _, err := s.subreddit(ctx, r.PathValue("name"), true); err != nil { s.renderInbox(w, r, "Couldn't read the subreddit's rules: "+err.Error()) return } redirect(w, r, "/inbox", "rules-refreshed") } // The Content module's own lists of approved and published drafts. func (s *Server) scheduledPage(w http.ResponseWriter, r *http.Request) { s.renderScheduled(w, r, "") } func (s *Server) renderScheduled(w http.ResponseWriter, r *http.Request, errMsg string) { drafts, err := content.ListDrafts(s.DB, 500, content.StatusScheduled) if err != nil { s.serverError(w, err) return } s.render(w, r, "content-scheduled", page{Title: "Scheduled", Nav: "content", Error: errMsg, Data: map[string]any{ "Drafts": drafts, "Connected": s.connected(), "Zone": time.Now().Format("MST"), }}) } func (s *Server) publishedPage(w http.ResponseWriter, r *http.Request) { drafts, err := content.ListDrafts(s.DB, 200, content.StatusPublished) if err != nil { s.serverError(w, err) return } s.render(w, r, "content-published", page{Title: "Published", Nav: "content", Data: map[string]any{"Drafts": drafts}}) } // dateTimeLocal is the format of , read in the // app's time zone (the computer's; see compose.yaml). const dateTimeLocal = "2006-01-02T15:04" func parseWhen(v string, now time.Time) (time.Time, error) { v = strings.TrimSpace(v) if v == "" { return time.Time{}, errors.New("choose a date and time to publish") } at, err := time.ParseInLocation(dateTimeLocal, v, time.Local) if err != nil { return time.Time{}, fmt.Errorf("%q isn't a date and time", v) } // A minute's grace for a time picked as "now". if at.Before(now.Add(-time.Minute)) { return time.Time{}, errors.New("that time has passed: pick a later one, or publish now") } return at, nil } // draftAction saves, publishes, schedules, unschedules or discards one draft. func (s *Server) draftAction(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 := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Where the form was: the Inbox, or the Scheduled list. fromScheduled := r.PostForm.Get("from") == "scheduled" back := "/inbox" if fromScheduled { back = "/content/scheduled" } fail := func(err error) { if errors.Is(err, content.ErrNoDraft) { http.NotFound(w, r) return } if fromScheduled { s.renderScheduled(w, r, err.Error()) } else { s.renderInbox(w, r, err.Error()) } } action := r.PathValue("action") switch action { case "save", "publish", "schedule": if title, sent := r.PostForm["title"]; sent { if err := content.UpdateTitle(s.DB, id, title[0]); err != nil { fail(err) return } } if text, sent := r.PostForm["content"]; sent { if err := content.UpdateDraft(s.DB, id, text[0]); err != nil { fail(err) return } } } switch action { case "save": redirect(w, r, back, "saved") case "publish": ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) defer cancel() d, err := content.Publish(ctx, s.DB, s.publishers(), s.tagger(), id) if err != nil { name := "the channel" if d != nil { name = d.ChannelName() } fail(fmt.Errorf("Couldn't publish to %s: %w", name, err)) return } if d.Channel == content.ChannelReddit { s.forgetRedditHistory() } redirect(w, r, back, "published") case "schedule": at, err := parseWhen(r.PostForm.Get("when"), time.Now()) if err != nil { fail(err) return } d, err := content.GetDraft(s.DB, id) if err != nil { fail(err) return } if problem := d.Problem(); problem != "" { fail(fmt.Errorf("%s: fix it before scheduling", problem)) return } if err := content.Schedule(s.DB, id, at); err != nil { fail(err) return } redirect(w, r, back, "scheduled") case "unschedule": if err := content.Unschedule(s.DB, id); err != nil { fail(err) return } redirect(w, r, "/inbox", "unscheduled") case "discard": if err := content.DiscardDraft(s.DB, id); err != nil { fail(err) return } redirect(w, r, back, "discarded") default: http.NotFound(w, r) } } // tagger adds UTM tags to links to the company's websites and product // pages; nil if the profile lists none. func (s *Server) tagger() *utm.Tagger { p, err := profile.Load(s.DB) if err != nil { s.Log.Error("loading the profile for UTM tags", "err", err) return nil } var sites []string for _, w := range p.Websites { sites = append(sites, w.URL) } for _, pr := range p.Products { sites = append(sites, pr.URL) } t := utm.NewTagger(sites) if !t.Any() { return nil } return t } // --- The scheduler --- // schedulerInterval is how often due drafts are looked for. const schedulerInterval = 30 * time.Second // RunScheduler publishes scheduled drafts when they're due, until ctx ends. // The container runs all the time, so the browser needn't be open. func (s *Server) RunScheduler(ctx context.Context) { tick := time.NewTicker(schedulerInterval) defer tick.Stop() for { s.publishDue(ctx, time.Now()) select { case <-ctx.Done(): return case <-tick.C: } } } func (s *Server) publishDue(ctx context.Context, now time.Time) { due, err := content.Due(s.DB, now) if err != nil { s.Log.Error("scheduler: listing due drafts", "err", err) return } if len(due) == 0 { return } pubs, tags := s.publishers(), s.tagger() for _, d := range due { if ctx.Err() != nil { return } pctx, cancel := context.WithTimeout(ctx, 60*time.Second) _, err := content.Publish(pctx, s.DB, pubs, tags, d.ID) cancel() if err != nil { // A failed post is recorded on the draft by Publish. One refused // before posting (not connected, too long) is still scheduled: // send it back to the Inbox rather than retry it forever. if ferr := content.FailScheduled(s.DB, d.ID, err.Error()); ferr != nil && !errors.Is(ferr, content.ErrNotEditable) { s.Log.Error("scheduler: recording a failure", "draft", d.ID, "err", ferr) } s.Log.Warn("scheduler: publishing failed", "draft", d.ID, "channel", d.Channel, "err", err) continue } s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel) } }