package web import ( "context" "errors" "fmt" "net/http" "strings" "time" "supermarket/internal/api/listmonk" "supermarket/internal/prospects" "supermarket/internal/secrets" "supermarket/internal/signals" ) // Mailing lists: adding a prospect to a list on Listmonk (Settings → // Email → Mailing lists, and Add to a mailing list on a person in Review). type listmonkSettings struct { URL string `json:"url"` User string `json:"user"` } const ( listmonkKey = "listmonk:settings" listmonkListsKey = "listmonk:lists" // the lists, as last read listsFresh = time.Hour ) var listmonkToken = secretField{"listmonk", secrets.ListmonkToken, "API token", "In Listmonk: Admin → Users → New, of the API type; it shows the token once.", ""} // listmonkConfig is the saved settings, with Listmonk's usual address on // the Core when none is saved. func (s *Server) listmonkConfig() listmonkSettings { var set listmonkSettings _, _ = s.DB.GetJSON(listmonkKey, &set) if set.URL == "" && s.Core != nil { set.URL = "https://listmonk." + s.Core.Domain } return set } // listmonk is the client, or nil until a user and token are saved. func (s *Server) listmonk() *listmonk.Client { set := s.listmonkConfig() tok := s.Secrets.Get(secrets.ListmonkToken) if set.URL == "" || set.User == "" || tok == "" { return nil } return listmonk.New(set.URL, set.User, tok) } type cachedLists struct { At time.Time `json:"at"` Lists []listmonk.List `json:"lists"` } // mailingLists are Listmonk's lists, read at most once an hour (or now, // with fresh). func (s *Server) mailingLists(ctx context.Context, fresh bool) ([]listmonk.List, error) { c := s.listmonk() if c == nil { return nil, nil } var cached cachedLists if ok, _ := s.DB.GetJSON(listmonkListsKey, &cached); ok && !fresh && time.Since(cached.At) < listsFresh { return cached.Lists, nil } lists, err := c.Lists(ctx) if err != nil { return cached.Lists, err } _ = s.DB.PutJSON(listmonkListsKey, cachedLists{At: time.Now(), Lists: lists}) return lists, nil } // listmonkSave saves the address, the API user and its token. func (s *Server) listmonkSave(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } set := listmonkSettings{URL: strings.TrimRight(strings.TrimSpace(r.PostFormValue("listmonk_url")), "/"), User: strings.TrimSpace(r.PostFormValue("listmonk_user"))} if set.URL != "" && !strings.HasPrefix(set.URL, "https://") && !strings.HasPrefix(set.URL, "http://") { set, _ := s.outreachSettings() s.renderEmail(w, r, set, "Listmonk's address starts with https://") return } if err := s.DB.PutJSON(listmonkKey, set); err != nil { s.serverError(w, err) return } if err := s.saveSecrets(r, []secretField{listmonkToken}); err != nil { s.serverError(w, err) return } _, _ = s.DB.Exec(`DELETE FROM settings WHERE key = ?`, listmonkListsKey) // read them again redirect(w, r, "/settings/email#lists", "saved") } // listmonkTest reads the lists: the user and token work if it can. func (s *Server) listmonkTest(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() data := map[string]any{} if s.listmonk() == nil { data["Error"] = "Save the API user and its token first." } else if lists, err := s.mailingLists(ctx, true); err != nil { data["Error"] = err.Error() } else { data["Lists"] = lists } s.noteCheck("listmonk", data) s.fragment(w, r, "email", "listmonk-test", data) } // addToList adds a person to a mailing list. func (s *Server) addToList(r *http.Request, id int64) error { ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() return s.addToListID(ctx, id, r.PostFormValue("list"), r.PostFormValue("agreed") == "on") } // addToListID adds a person to a mailing list, by the list's ID. confirmed // says they agreed to receive it; without that, only a double opt-in list // takes them (it asks them first). func (s *Server) addToListID(ctx context.Context, id int64, listID string, confirmed bool) error { c := s.listmonk() if c == nil { return errors.New("set up Listmonk under Settings → Email first") } p, err := prospects.GetContact(s.DB, id) if err != nil { return err } if p.Email == "" { return errors.New(p.Name() + " has no email address") } domain := "" if _, after, ok := strings.Cut(p.Email, "@"); ok { domain = after } if sup, err := prospects.IsSuppressed(s.DB, p.Email, domain); err != nil { return err } else if sup { return errors.New(p.Email + " is on your suppression list, so it can't go on a mailing list") } lists, err := s.mailingLists(ctx, false) if err != nil && len(lists) == 0 { return err } var list *listmonk.List for i := range lists { if fmt.Sprint(lists[i].ID) == listID { list = &lists[i] } } if list == nil { return errors.New("choose a mailing list") } if !confirmed && !list.Double() { return errors.New(list.Name + " sends its mail without asking first: add someone there only once they've agreed to receive it, or choose a double opt-in list") } attribs := map[string]any{"source": "supermarket"} if p.Title != "" { attribs["title"] = p.Title } if p.CompanyID != 0 { if co, err := prospects.GetCompany(s.DB, p.CompanyID); err == nil { attribs["company"] = co.Name } } if p.SignalID != 0 { if sig, err := signals.Get(s.DB, p.SignalID); err == nil { attribs["signal"] = sig.Slug } } if _, _, err := c.Subscribe(ctx, listmonk.Subscriber{Email: p.Email, Name: p.Name(), Attribs: attribs}, *list, confirmed); err != nil { return err } return prospects.AddedToList(s.DB, id, list.ID, list.Name, confirmed || !list.Double(), time.Now()) } // reviewLists are the lists Review offers, quickly: what's cached, or a // short read; nil until Listmonk is set up. func (s *Server) reviewLists(r *http.Request) []listmonk.List { if s.listmonk() == nil { return nil } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() lists, _ := s.mailingLists(ctx, false) return lists } // onLists are the lists each person was added to, by contact ID. func (s *Server) onLists() map[int64][]prospects.ListMember { m, _ := prospects.ListsOf(s.DB) return m } // optOutSync is what the last sync of Listmonk's opt-outs did. type optOutSync struct { At time.Time `json:"at"` Seen int `json:"seen"` // people Listmonk says don't want mail Added int `json:"added"` // of them, newly on the suppression list Error string `json:"error,omitempty"` } const ( optOutKey = "listmonk:optouts" optOutEvery = time.Hour ) // syncOptOuts puts everyone blocklisted in Listmonk, or unsubscribed from // one of its lists, on the suppression list (an address already there // keeps its reason), and forgets the list they left. func (s *Server) syncOptOuts(ctx context.Context) (*optOutSync, error) { res := &optOutSync{At: time.Now()} finish := func(err error) (*optOutSync, error) { if err != nil { res.Error = err.Error() } _ = s.DB.PutJSON(optOutKey, res) return res, err } c := s.listmonk() if c == nil { return finish(errors.New("set up Listmonk first")) } lists, err := s.mailingLists(ctx, true) if err != nil { return finish(err) } out, err := c.OptedOut(ctx, lists) if err != nil && len(out) == 0 { return finish(err) } seen := map[string]bool{} for _, o := range out { if !seen[o.Email] { seen[o.Email] = true res.Seen++ } if o.List != "" { if _, derr := s.DB.Exec(`DELETE FROM list_members WHERE list_name = ? AND contact_id IN (SELECT id FROM prospect_contacts WHERE email = ?)`, o.List, o.Email); derr != nil { return finish(derr) } } if already, serr := prospects.IsSuppressed(s.DB, o.Email, ""); serr != nil { return finish(serr) } else if already { continue } reason := "Blocklisted in Listmonk" if o.List != "" { reason = "Unsubscribed from “" + o.List + "” in Listmonk" } if serr := prospects.Suppress(s.DB, "email", o.Email, reason, res.At); serr != nil { return finish(serr) } res.Added++ } return finish(err) // a list that failed partway still reports its error } // listmonkSync syncs the opt-outs now. func (s *Server) listmonkSync(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) defer cancel() res, err := s.syncOptOuts(ctx) if err != nil { redirect(w, r, "/settings/email#lists", "") // the card shows the error return } redirectCounts(w, r, "/settings/email#lists", "optouts-synced", res.Added) } // hourlyOptOuts syncs Listmonk's opt-outs once an hour. func (s *Server) hourlyOptOuts(ctx context.Context) { if s.listmonk() == nil { return } var last optOutSync if ok, _ := s.DB.GetJSON(optOutKey, &last); ok && time.Since(last.At) < optOutEvery { return } sctx, cancel := context.WithTimeout(ctx, 5*time.Minute) defer cancel() if res, err := s.syncOptOuts(sctx); err != nil { s.Log.Warn("listmonk: syncing opt-outs", "err", err) } else if res.Added > 0 { s.Log.Info("listmonk: opt-outs added to the suppression list", "count", res.Added) } } func (s *Server) lastOptOuts() *optOutSync { var last optOutSync if ok, _ := s.DB.GetJSON(optOutKey, &last); !ok { return nil } return &last }