internal/jobs keeps named locks as leases in the database (schema 31: locks, instances), taken with one conditional UPDATE on SQLite or Postgres, renewed while the work runs and lapsing if its copy stops. Each background loop's turn, sending an email, audits, discovery runs and imports run under a lock; OAuth sign-ins under way are kept in the database. Copies check in, and work marked running is recovered at start only when no other copy is alive. Settings -> About lists the copies and work under way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
461 lines
14 KiB
Go
461 lines
14 KiB
Go
package web
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"supermarket/internal/jobs"
|
|
"time"
|
|
|
|
"supermarket/internal/ai"
|
|
"supermarket/internal/outreach"
|
|
"supermarket/internal/profile"
|
|
"supermarket/internal/prospects"
|
|
"supermarket/internal/secrets"
|
|
"supermarket/internal/signals"
|
|
)
|
|
|
|
var mailPassword = secretField{"mail", secrets.MailPassword, "Password",
|
|
"The mailbox's password, or an app password if your mail server has them.", ""}
|
|
|
|
// outreachSettings are the saved email settings, or the defaults.
|
|
func (s *Server) outreachSettings() (outreach.Settings, bool) {
|
|
p, _ := profile.Load(s.DB)
|
|
set, ok, err := outreach.Load(s.DB, s.Core, p)
|
|
if err != nil {
|
|
s.Log.Error("loading the email settings", "err", err)
|
|
}
|
|
return set, ok
|
|
}
|
|
|
|
// mailbox is the sender for the saved settings, or why there's none.
|
|
func (s *Server) mailbox() (outreach.Settings, outreach.Mailbox, error) {
|
|
set, ok := s.outreachSettings()
|
|
pw := s.Secrets.Get(secrets.MailPassword)
|
|
if !ok {
|
|
return set, outreach.Mailbox{}, errors.New("set up email first, under Settings → Email")
|
|
}
|
|
if err := set.Ready(pw); err != nil {
|
|
return set, outreach.Mailbox{}, err
|
|
}
|
|
return set, outreach.Mailbox{Settings: set, Password: pw}, nil
|
|
}
|
|
|
|
// outreachDrafts is how many drafts wait, for the menu.
|
|
func (s *Server) outreachDrafts() int {
|
|
counts, err := outreach.Counts(s.DB)
|
|
if err != nil {
|
|
s.Log.Error("counting outreach", "err", err)
|
|
}
|
|
return counts[outreach.StatusDraft]
|
|
}
|
|
|
|
// --- Settings → Email ---
|
|
|
|
func (s *Server) emailPage(w http.ResponseWriter, r *http.Request) {
|
|
set, _ := s.outreachSettings()
|
|
s.renderEmail(w, r, set, "")
|
|
}
|
|
|
|
func (s *Server) renderEmail(w http.ResponseWriter, r *http.Request, set outreach.Settings, errMsg string) {
|
|
s.render(w, r, "email", page{Title: "Email", Nav: "settings/email", Error: errMsg, Data: map[string]any{
|
|
"S": set,
|
|
"Password": mailPassword,
|
|
"Set": s.Secrets.Has(secrets.MailPassword),
|
|
"Hours": hours(),
|
|
"Listmonk": s.listmonkConfig(),
|
|
"LMToken": listmonkToken,
|
|
"LMSet": s.Secrets.Has(secrets.ListmonkToken),
|
|
"OptOuts": s.lastOptOuts(),
|
|
}})
|
|
}
|
|
|
|
func hours() []int {
|
|
h := make([]int, 25)
|
|
for i := range h {
|
|
h[i] = i
|
|
}
|
|
return h
|
|
}
|
|
|
|
func (s *Server) emailSave(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
f := r.PostFormValue
|
|
num := func(k string) int { n, _ := strconv.Atoi(strings.TrimSpace(f(k))); return n }
|
|
set := outreach.Settings{
|
|
SMTPHost: f("smtp_host"), SMTPPort: num("smtp_port"), IMAPHost: f("imap_host"), IMAPPort: num("imap_port"),
|
|
Username: f("username"), FromName: f("from_name"), FromAddress: f("from_address"),
|
|
DailyLimit: num("daily_limit"), GapMinutes: num("gap_minutes"), StartHour: num("start_hour"), EndHour: num("end_hour"),
|
|
Weekends: f("weekends") == "on", Footer: strings.TrimSpace(strings.ReplaceAll(f("footer"), "\r\n", "\n")),
|
|
SchedulingLink: f("scheduling_link"), SaveToSent: f("save_to_sent") == "on", ReadReplies: f("read_replies") == "on",
|
|
BookingFrom: f("booking_from"),
|
|
}
|
|
if err := outreach.Save(s.DB, set); err != nil {
|
|
s.renderEmail(w, r, set, err.Error())
|
|
return
|
|
}
|
|
if err := s.saveSecrets(r, []secretField{mailPassword}); err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
redirect(w, r, "/settings/email", "saved")
|
|
}
|
|
|
|
// emailTest signs in to the mail server and the mailbox, and looks up the
|
|
// domain's mail records. Nothing is sent.
|
|
func (s *Server) emailTest(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
set, _ := s.outreachSettings()
|
|
pw := s.Secrets.Get(secrets.MailPassword)
|
|
type line struct {
|
|
OK bool
|
|
Text string
|
|
}
|
|
var lines []line
|
|
if err := set.Ready(pw); err != nil {
|
|
lines = append(lines, line{false, "Save the settings and password first: " + err.Error() + "."})
|
|
} else {
|
|
if err := outreach.CheckSMTP(ctx, set, pw); err != nil {
|
|
lines = append(lines, line{false, "Sending: " + err.Error()})
|
|
} else {
|
|
lines = append(lines, line{true, "Sending: signed in to " + set.SMTPHost + "."})
|
|
}
|
|
if n, err := outreach.CheckIMAP(ctx, set, pw); err != nil {
|
|
lines = append(lines, line{false, "Reading replies: " + err.Error()})
|
|
} else {
|
|
lines = append(lines, line{true, "Reading replies: opened the inbox (" + strconv.Itoa(int(n)) + " messages), read-only."})
|
|
}
|
|
}
|
|
if dom := set.FromDomain(); dom != "" {
|
|
c := outreach.CheckDNS(ctx, dom)
|
|
lines = append(lines,
|
|
line{c.SPF != "", "SPF for " + dom + ": " + or(c.SPF, "none found. Without it, many servers treat your email as suspect.")},
|
|
line{c.DKIMSelector != "", "DKIM: " + or(dkimText(c.DKIMSelector), "no key found at the usual names; check with whoever runs your mail server that outgoing mail is signed.")},
|
|
line{c.DMARC != "", "DMARC: " + or(c.DMARC, "none found. Add a DMARC record (start with p=none) so receivers trust your domain.")},
|
|
)
|
|
}
|
|
s.fragment(w, "email", "email-test", lines)
|
|
}
|
|
|
|
func or(a, b string) string {
|
|
if a != "" {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
func dkimText(sel string) string {
|
|
if sel == "" {
|
|
return ""
|
|
}
|
|
return "a key is published (selector “" + sel + "”)."
|
|
}
|
|
|
|
func (s *Server) emailSendTest(w http.ResponseWriter, r *http.Request) {
|
|
set, mb, err := s.mailbox()
|
|
if err == nil {
|
|
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
|
|
defer cancel()
|
|
err = outreach.SendTest(ctx, set, mb, time.Now())
|
|
}
|
|
if err != nil {
|
|
s.renderEmail(w, r, set, "The test email didn't go: "+err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/settings/email", "test-sent")
|
|
}
|
|
|
|
// --- The outreach page ---
|
|
|
|
func outreachTab(v string) string {
|
|
for _, t := range outreach.Tabs {
|
|
if v == t.ID {
|
|
return v
|
|
}
|
|
}
|
|
return outreach.StatusDraft
|
|
}
|
|
|
|
func (s *Server) outreachPage(w http.ResponseWriter, r *http.Request) {
|
|
s.renderOutreach(w, r, outreachTab(r.URL.Query().Get("tab")), "")
|
|
}
|
|
|
|
func (s *Server) renderOutreach(w http.ResponseWriter, r *http.Request, tab, errMsg string) {
|
|
msgs, err := outreach.List(s.DB, tab, 200)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
counts, err := outreach.Counts(s.DB)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
set, ok := s.outreachSettings()
|
|
_, _, notReady := s.mailbox()
|
|
today, _ := outreach.SentToday(s.DB, time.Now())
|
|
last, _ := outreach.LastCheck(s.DB)
|
|
list, _ := signals.List(s.DB)
|
|
names := map[int64]string{}
|
|
for _, sg := range list {
|
|
names[sg.ID] = sg.Name
|
|
}
|
|
emailable, _ := outreach.Candidates(s.DB, 0, outreach.ChannelEmail, 1000)
|
|
linkable, _ := outreach.Candidates(s.DB, 0, outreach.ChannelLinkedIn, 1000)
|
|
var window string
|
|
if err := set.Window(time.Now()); err != nil {
|
|
window = err.Error()
|
|
}
|
|
s.render(w, r, "outreach", page{Title: "Outreach", Nav: "prospects/outreach", Error: errMsg, Data: map[string]any{
|
|
"Tab": tab,
|
|
"Tabs": outreach.Tabs,
|
|
"Counts": counts,
|
|
"Messages": msgs,
|
|
"S": set,
|
|
"Configured": ok,
|
|
"NotReady": notReady,
|
|
"SentToday": today,
|
|
"Window": window,
|
|
"LastCheck": last,
|
|
"Signals": list,
|
|
"SignalNames": names,
|
|
"Emailable": len(emailable),
|
|
"Linkable": len(linkable),
|
|
"Limit": outreach.LinkedInLimit,
|
|
}})
|
|
}
|
|
|
|
// newAIClient is ai.New; tests replace it.
|
|
var newAIClient = ai.New
|
|
|
|
// draftClient is the AI client and profile for drafting.
|
|
func (s *Server) draftClient() (ai.Client, *profile.Profile, error) {
|
|
p, err := profile.Load(s.DB)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
cfg, err := ai.LoadConfig(s.DB)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
c, err := newAIClient(cfg, s.Secrets)
|
|
if err != nil {
|
|
return nil, nil, errors.New("drafting needs the AI: choose a provider under Settings → AI")
|
|
}
|
|
return c, p, nil
|
|
}
|
|
|
|
// outreachDraft writes one message, from the review screen.
|
|
func (s *Server) outreachDraft(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
id, _ := strconv.ParseInt(r.PostFormValue("contact"), 10, 64)
|
|
channel := r.PostFormValue("channel")
|
|
tab := reviewTab(r.PostFormValue("tab"))
|
|
filter, _ := strconv.ParseInt(r.PostFormValue("filter"), 10, 64)
|
|
c, p, err := s.draftClient()
|
|
if err == nil {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
|
defer cancel()
|
|
set, _ := s.outreachSettings()
|
|
var m *outreach.Message
|
|
if m, err = outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err == nil {
|
|
redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach")
|
|
return
|
|
}
|
|
}
|
|
if errors.Is(err, prospects.ErrNotFound) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
s.renderProspects(w, r, tab, filter, "Couldn't draft it: "+err.Error())
|
|
}
|
|
|
|
// maxDraftMany is how many messages one click drafts.
|
|
const maxDraftMany = 5
|
|
|
|
// outreachDraftMany drafts for accepted people who haven't been written to.
|
|
func (s *Server) outreachDraftMany(w http.ResponseWriter, r *http.Request) {
|
|
if err := r.ParseForm(); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
sig, _ := strconv.ParseInt(r.PostFormValue("signal"), 10, 64)
|
|
channel := r.PostFormValue("channel")
|
|
if channel != outreach.ChannelLinkedIn {
|
|
channel = outreach.ChannelEmail
|
|
}
|
|
c, p, err := s.draftClient()
|
|
if err != nil {
|
|
s.renderOutreach(w, r, outreach.StatusDraft, err.Error())
|
|
return
|
|
}
|
|
ids, err := outreach.Candidates(s.DB, sig, channel, maxDraftMany)
|
|
if err != nil {
|
|
s.serverError(w, err)
|
|
return
|
|
}
|
|
if len(ids) == 0 {
|
|
s.renderOutreach(w, r, outreach.StatusDraft, "Nobody to write to: accept people in Review first (with an email address, or a LinkedIn profile).")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Minute)
|
|
defer cancel()
|
|
set, _ := s.outreachSettings()
|
|
var failed []string
|
|
for _, id := range ids {
|
|
if _, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil {
|
|
failed = append(failed, err.Error())
|
|
if ctx.Err() != nil {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if len(failed) > 0 {
|
|
s.renderOutreach(w, r, outreach.StatusDraft, "Some weren't drafted: "+strings.Join(failed, "; "))
|
|
return
|
|
}
|
|
redirect(w, r, "/outreach", "drafted-outreach")
|
|
}
|
|
|
|
// outreachAction handles a message's buttons.
|
|
func (s *Server) outreachAction(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
|
|
}
|
|
tab := outreachTab(r.PostFormValue("tab"))
|
|
now := time.Now()
|
|
var msg string
|
|
switch r.PathValue("action") {
|
|
case "save", "queue":
|
|
if _, has := r.PostForm["body"]; has {
|
|
err = outreach.Edit(s.DB, id, r.PostFormValue("subject"), r.PostFormValue("body"))
|
|
}
|
|
msg = "saved"
|
|
if err == nil && r.PathValue("action") == "queue" {
|
|
err, msg = outreach.Queue(s.DB, id, now), "queued"
|
|
}
|
|
case "unqueue":
|
|
err, msg = outreach.Unqueue(s.DB, id), "unqueued"
|
|
case "discard":
|
|
err, msg = outreach.Discard(s.DB, id), "discarded"
|
|
case "send-now":
|
|
var set outreach.Settings
|
|
var mb outreach.Mailbox
|
|
if set, mb, err = s.mailbox(); err == nil {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
|
|
var sctx context.Context
|
|
var release func()
|
|
if sctx, release, err = s.jobs().Lock(ctx, sendLock); err == nil {
|
|
err = outreach.SendNow(sctx, s.DB, set, mb, s.tagger(), id, now)
|
|
release()
|
|
} else if errors.Is(err, jobs.ErrBusy) {
|
|
err = errors.New("another email is still being sent; try again in a minute")
|
|
}
|
|
cancel()
|
|
}
|
|
msg = "sent"
|
|
case "mark-sent":
|
|
err, msg = outreach.MarkSent(s.DB, id, r.PostFormValue("body"), now), "marked-sent"
|
|
case "replied":
|
|
err, msg = outreach.MarkReplied(s.DB, id, r.PostFormValue("reply"), "", now), "reply-recorded"
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if errors.Is(err, outreach.ErrNotFound) {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
s.renderOutreach(w, r, tab, "Couldn't do that: "+err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/outreach?tab="+tab+"#m-"+strconv.FormatInt(id, 10), msg)
|
|
}
|
|
|
|
// outreachCheck reads the inbox now.
|
|
func (s *Server) outreachCheck(w http.ResponseWriter, r *http.Request) {
|
|
set, mb, err := s.mailbox()
|
|
if err == nil {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
|
|
defer cancel()
|
|
_, err = outreach.CheckReplies(ctx, s.DB, set, mb.Password, time.Now())
|
|
}
|
|
if err != nil {
|
|
s.renderOutreach(w, r, outreachTab(r.PostFormValue("tab")), "Couldn't read the inbox: "+err.Error())
|
|
return
|
|
}
|
|
redirect(w, r, "/outreach?tab=replied", "checked")
|
|
}
|
|
|
|
// RunOutreach sends queued emails as their turn comes, and reads replies
|
|
// every 10 minutes.
|
|
// repliesCheckedKey is when the mailbox was last read for replies.
|
|
const repliesCheckedKey = "outreach:replies-checked"
|
|
|
|
func (s *Server) RunOutreach(ctx context.Context) {
|
|
tick := time.NewTicker(time.Minute)
|
|
defer tick.Stop()
|
|
for {
|
|
s.jobDo(ctx, "outreach", func(ctx context.Context) {
|
|
set, mb, err := s.mailbox()
|
|
if err != nil {
|
|
return
|
|
}
|
|
sctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
|
|
if lctx, release, err := s.jobs().Lock(sctx, sendLock); err == nil {
|
|
m, err := outreach.SendDue(lctx, s.DB, set, mb, s.tagger(), time.Now())
|
|
release()
|
|
if err != nil {
|
|
s.Log.Warn("outreach: sending", "message", idOf(m), "err", err)
|
|
} else if m != nil {
|
|
s.Log.Info("outreach: sent", "message", m.ID, "to", m.To)
|
|
}
|
|
}
|
|
cancel()
|
|
// Replies, every 10 minutes (kept in the database: another copy
|
|
// may have read them last).
|
|
var last time.Time
|
|
_, _ = s.DB.GetJSON(repliesCheckedKey, &last)
|
|
if set.ReadReplies && time.Since(last) >= 10*time.Minute {
|
|
_ = s.DB.PutJSON(repliesCheckedKey, time.Now())
|
|
cctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
|
if res, err := outreach.CheckReplies(cctx, s.DB, set, mb.Password, time.Now()); err != nil {
|
|
s.Log.Warn("outreach: reading replies", "err", err)
|
|
} else if res.Replies+res.Bounces > 0 {
|
|
s.Log.Info("outreach: replies", "replies", res.Replies, "bounces", res.Bounces, "stops", res.Stops)
|
|
}
|
|
cancel()
|
|
}
|
|
})
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func idOf(m *outreach.Message) int64 {
|
|
if m == nil {
|
|
return 0
|
|
}
|
|
return m.ID
|
|
}
|