Phase 8 part 3: lost links

Each known linking page (from Bing, Plausible or added by hand) is
opened once a week, at most 100 a day, to check it still links to the
site: kept, gone (the page no longer has the link), page gone (404, 410
or moved elsewhere) or pointing at a 404 (our page it links to is gone).
SEO → Links lists the lost ones with what happened, when last seen and
what the site brought; links can be added by hand (checked at once),
checked now, or forgotten. What to write next suggests a redirect for a
link to a 404, and asking for a lost link back when it brought visitors.
Links and What to write next now work for websites without Search
Console too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 08:43:30 -07:00
co-authored by Claude Opus 5.5
parent fc7dcf1f66
commit a1409d91ad
9 changed files with 539 additions and 7 deletions
+87 -3
View File
@@ -4,10 +4,12 @@ import (
"context"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/backlinks"
"supermarket/internal/profile"
"supermarket/internal/seo"
"supermarket/internal/tracking"
)
@@ -17,9 +19,16 @@ import (
const linkDays = 90
func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
data, cur := s.seoBase(r)
s.renderLinks(w, r, "")
}
func (s *Server) renderLinks(w http.ResponseWriter, r *http.Request, errMsg string) {
// Links don't need Search Console: every website with an address.
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur, "Connected": true}
data["Path"] = "/seo/links"
data["Plausible"] = s.plausible() != nil
data["Brought"] = map[string]tracking.Referrer{}
if cur != nil {
if p, _ := profile.Load(s.DB); p != nil {
for _, web := range p.Websites {
@@ -42,6 +51,11 @@ func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
}
}
data["Links"], data["Others"] = links, others
brought := map[string]tracking.Referrer{}
for _, ref := range list {
brought[strings.TrimPrefix(strings.ToLower(ref.Source), "www.")] = ref
}
data["Brought"] = brought
}
}
var known int
@@ -67,6 +81,15 @@ func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
first = st.First
}
sites := backlinks.Sites(links, first)
var lost []backlinks.Link
counts := map[string]int{}
for _, l := range links {
counts[l.Status]++
if l.Lost() {
lost = append(lost, l)
}
}
data["Lost"], data["Counts"] = lost, counts
data["LinkingSites"], data["LinkCount"] = sites, len(links)
if len(sites) > 30 {
data["MoreSites"], data["LinkingSites"] = len(sites)-30, sites[:30]
@@ -74,12 +97,12 @@ func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
}
last, _ := tracking.Last(s.DB, "referrers")
data["Last"] = last
s.render(w, r, "seo-links", page{Title: "Links", Nav: "seo/links", Data: data})
s.render(w, r, "seo-links", page{Title: "Links", Nav: "seo/links", Error: errMsg, Data: data})
}
// seoLinksBing reads the site's links from Bing now.
func (s *Server) seoLinksBing(w http.ResponseWriter, r *http.Request) {
_, cur := s.seoCurrent(r)
_, cur := s.auditSites(r)
c := s.bing()
if cur == nil || c == nil {
redirect(w, r, "/seo/links", "")
@@ -113,3 +136,64 @@ func (s *Server) weeklyBingLinks(ctx context.Context) {
cancel()
}
}
// linkFetcher reads other sites' pages for the link checks.
func (s *Server) linkFetcher() backlinks.Fetcher {
return seo.NewFetcher("Supermarket/" + s.Version + " (link check)")
}
// seoLinksAction adds a link by hand, checks links now, or forgets one.
func (s *Server) seoLinksAction(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
back := "/seo/links?site=" + strconv.Itoa(cur.Index) + "#lost"
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
now := time.Now()
switch r.PathValue("action") {
case "add":
l, err := backlinks.Add(s.DB, cur.URL, r.PostFormValue("source"), r.PostFormValue("target"), now)
if err != nil {
s.renderLinks(w, r, err.Error())
return
}
if err := backlinks.CheckOne(ctx, s.DB, s.linkFetcher(), cur.URL, l, now); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back, "link-added")
case "check":
n, err := backlinks.CheckDue(ctx, s.DB, s.linkFetcher(), cur.URL, 20, now)
if err != nil {
s.serverError(w, err)
return
}
redirectCounts(w, r, back, "links-checked", n)
case "forget":
id, _ := strconv.ParseInt(r.PostFormValue("id"), 10, 64)
if err := backlinks.Remove(s.DB, cur.URL, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, back, "link-forgotten")
default:
http.NotFound(w, r)
}
}
// dailyLinkChecks checks the links due, within the day's limit.
func (s *Server) dailyLinkChecks(ctx context.Context) {
for _, site := range s.seoSites() {
if site.URL == "" {
continue
}
cctx, cancel := context.WithTimeout(ctx, 20*time.Minute)
if _, err := backlinks.CheckDue(cctx, s.DB, s.linkFetcher(), site.URL, 0, time.Now()); err != nil {
s.Log.Warn("backlinks: checking links", "site", site.URL, "err", err)
}
cancel()
}
}
+51 -1
View File
@@ -2,16 +2,19 @@ package web
import (
"context"
"fmt"
"net/http"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/backlinks"
"supermarket/internal/inventory"
"supermarket/internal/next"
"supermarket/internal/profile"
"supermarket/internal/seo"
"supermarket/internal/tracking"
)
// What to write next (SEO → What to write next): SEO's suggestions and the
@@ -86,6 +89,7 @@ func (s *Server) nextFor(cur seoSite, now time.Time) (list []next.Suggestion, mo
all = append(all, ideas...)
}
}
all = append(all, s.lostLinkIdeas(cur)...)
stalled, err := next.Stalled(s.DB, cur.URL, cur.Index, now)
if err != nil {
return nil, 0, err
@@ -120,7 +124,10 @@ func (s *Server) nextFor(cur seoSite, now time.Time) (list []next.Suggestion, mo
}
func (s *Server) seoNextPage(w http.ResponseWriter, r *http.Request) {
data, cur := s.seoBase(r)
// Every website with an address: only some suggestions need Search
// Console, and those are skipped without it.
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur, "Connected": true}
data["Path"] = "/seo/next"
if cur != nil {
list, more, err := s.nextFor(*cur, time.Now())
@@ -209,3 +216,46 @@ func (s *Server) sectionIdeas(cur seoSite) ([]next.Suggestion, error) {
rate, _ := sc.Rate("")
return next.SectionIdeas(pages, searches, types, competitors, cur.Index, rate), nil
}
// lostLinkIdeas suggest fixing links lost or pointing at a 404: a redirect
// for the second, a word with the linking site for the first when it
// brought visitors.
func (s *Server) lostLinkIdeas(cur seoSite) []next.Suggestion {
links, err := backlinks.Links(s.DB, cur.URL)
if err != nil {
return nil
}
brought := map[string]tracking.Referrer{}
if p, _ := profile.Load(s.DB); p != nil {
for _, w := range p.Websites {
if w.URL == cur.URL {
list, _, _ := tracking.Referrers(s.DB, w, linkDays)
for _, ref := range list {
brought[strings.TrimPrefix(strings.ToLower(ref.Source), "www.")] = ref
}
}
}
}
rate, _ := s.scope(cur).Rate("")
var out []next.Suggestion
for _, l := range links {
b := brought[l.Host()]
worth := float64(b.Signups) + float64(b.Visitors)*rate
see := next.Action{Label: "See the link", Method: "GET", URL: "/seo/links?site=" + strconv.Itoa(cur.Index) + "#lost"}
visits := ""
if b.Visitors > 0 {
visits = fmt.Sprintf(" It brought %d visitors in 90 days.", b.Visitors)
}
switch {
case l.Status == backlinks.StatusTarget404:
out = append(out, next.Suggestion{Key: "link-404:" + l.Target, Kind: "Fix with a redirect", Title: l.Target,
Why: l.Host() + " links to " + l.Target + ", which answers 404: redirect it to where the page went, and the link works again." + visits,
Score: 0.3 + worth, Action: see})
case l.Lost() && b.Visitors > 0:
out = append(out, next.Suggestion{Key: "link-lost:" + l.Source, Kind: "Ask for the link back", Title: l.Host(),
Why: l.Note + visits + " A short note to the site often gets it back.",
Score: worth, Action: next.Action{Label: "Open their page", Method: "GET", URL: l.Source}})
}
}
return out
}
+1
View File
@@ -297,6 +297,7 @@ func (s *Server) RunSEO(ctx context.Context) {
s.dailyChecks(ctx)
}
s.weeklyBingLinks(ctx)
s.dailyLinkChecks(ctx)
s.refreshChanges(ctx)
s.refreshBriefs(ctx)
s.refreshSitePages(ctx)
+49
View File
@@ -2,6 +2,7 @@ package web
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
@@ -10,6 +11,7 @@ import (
"testing"
"time"
"supermarket/internal/backlinks"
"supermarket/internal/oauth"
"supermarket/internal/profile"
"supermarket/internal/secrets"
@@ -203,3 +205,50 @@ func TestLinksFromBing(t *testing.T) {
}
}
}
func TestLostLinks(t *testing.T) {
var site string
links := `<a href="SITE/freescout/">FreeScout hosting</a>`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/freescout/":
fmt.Fprint(w, "<html><body>FreeScout</body></html>")
case "/their/list":
fmt.Fprint(w, "<html><body>"+strings.ReplaceAll(links, "SITE", site)+"</body></html>")
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
// Our site and theirs on the same test server, told apart by host.
site = strings.Replace(srv.URL, "127.0.0.1", "localhost", 1)
theirs := srv.URL + "/their/list"
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: site + "/"}}})
if rec := postForm(h, "/seo/links/add?site=0", url.Values{"source": {theirs}}); rec.Code != http.StatusSeeOther {
t.Fatalf("add: %d %s", rec.Code, rec.Body.String())
}
p, _ := profile.Load(s.DB)
ls, _ := backlinks.Links(s.DB, p.Websites[0].URL)
if len(ls) != 1 || ls[0].Status != backlinks.StatusKept || ls[0].Target != "/freescout/" {
t.Fatalf("after adding: %+v", ls)
}
if body := postForm(h, "/seo/links/add?site=0", url.Values{"source": {site + "/blog/"}}).Body.String(); !strings.Contains(body, "a page of your own site") {
t.Error("took a page of the site itself")
}
// The page now links to a page of ours that's gone: a redirect fixes it.
links = `<a href="SITE/old-page/">old</a>`
s.DB.Exec(`UPDATE backlinks SET checked_at = '2020-01-01T00:00:00Z'`)
if rec := postForm(h, "/seo/links/check?site=0", nil); !strings.Contains(rec.Header().Get("Location"), "msg=links-checked&") && !strings.Contains(rec.Header().Get("Location"), "n1=1") {
t.Errorf("check: %s", rec.Header().Get("Location"))
}
body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String()
if !strings.Contains(body, "points at a 404") || !strings.Contains(body, "/old-page/") {
t.Errorf("links page: lost link not shown")
}
if body := do(h, http.MethodGet, "/seo/next", nil, nil).Body.String(); !strings.Contains(body, "Fix with a redirect") {
t.Errorf("next: no redirect suggestion")
}
}
+4
View File
@@ -225,6 +225,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /seo/next", s.seoNextPage)
mux.HandleFunc("GET /seo/links", s.seoLinksPage)
mux.HandleFunc("POST /seo/links/bing", s.seoLinksBing)
mux.HandleFunc("POST /seo/links/{action}", s.seoLinksAction)
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
@@ -547,6 +548,9 @@ var flashes = map[string]string{
"keyword-back": "Back among the candidates.",
"signups-saved": "Saved. The pages' sign-ups were read again with it.",
"next-dismissed": "Hidden for 90 days.",
"link-added": "Added, and checked.",
"links-checked": "Checked %d links.",
"link-forgotten": "Forgotten.",
"bing-read": "Read the links from Bing.",
"audited": "The audit is done.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
+28 -1
View File
@@ -30,7 +30,7 @@
<section class="card" id="bing">
<h2>Who links to you</h2>
<p class="small">From Bing Webmaster Tools, read once a week: how many links Bing has found to each of your pages, and, for the most linked ones, the pages that link and their link text. Google doesn't share its links through its API; Bing's index is a fair stand-in. The linking pages Plausible names are listed with them.</p>
<p class="small">From Bing Webmaster Tools, read once a week: how many links Bing has found to each of your pages, and, for the most linked ones, the pages that link and their link text. Google doesn't share its links through its API; Bing's index is a fair stand-in. The linking pages Plausible names, and ones you add under Lost links, are listed with them.</p>
{{if not $d.BingKey}}
<p class="warn-text small">Save a Bing Webmaster API key under <a href="/settings/search">Settings → Search engines</a>: in Bing Webmaster Tools, add and verify {{$d.Current.URL}} (it can import the site from Google Search Console), then Settings (the gear) → API access → API key.</p>
{{else}}
@@ -58,6 +58,33 @@
</details>
{{end}}{{end}}
</section>
<section class="card" id="lost">
<h2>Lost links</h2>
<p class="small">Every week Supermarket opens each known linking page (at most 100 a day, politely) and checks it still links to your site. A link is <em>gone</em> when the page no longer has it, <em>page gone</em> when the page answers 404 or moved, and <em>points at a 404</em> when the page of yours it links to no longer answers: a redirect on your side fixes that one.</p>
{{with $d.Counts}}<p class="small muted">{{with index . "kept"}}{{num .}} kept · {{end}}{{with index . "unchecked"}}{{num .}} not checked yet · {{end}}{{with index . "gone"}}{{num .}} gone · {{end}}{{with index . "page-gone"}}{{num .}} page gone · {{end}}{{with index . "target-404"}}{{num .}} pointing at a 404{{end}}</p>{{end}}
{{with $d.Lost}}
<table class="list">
<thead><tr><th>Linking page</th><th>What happened</th><th>Last seen</th><th>It brought</th><th></th></tr></thead>
<tbody>{{range .}}{{$b := index $d.Brought .Host}}<tr>
<td class="small"><a href="{{.Source}}" target="_blank" rel="noopener noreferrer">{{truncate 70 .Source}}</a>{{with .Target}}<br><span class="muted">to {{.}}</span>{{end}}</td>
<td class="small"><span class="badge {{if eq .Status "target-404"}}scheduled{{else}}competitor{{end}}">{{if eq .Status "gone"}}gone{{else if eq .Status "page-gone"}}page gone{{else}}points at a 404{{end}}</span><br>{{.Note}}</td>
<td class="small">{{.LastSeen}}</td>
<td class="small">{{if $b.Visitors}}<strong>{{num $b.Visitors}} visitors{{if $b.Signups}}, {{num $b.Signups}} sign-ups{{end}}</strong> in 90 days{{else}}<span class="muted">no visits seen</span>{{end}}</td>
<td><form method="post" action="/seo/links/forget?site={{$d.Current.Index}}" data-confirm="Forget this link?"><input type="hidden" name="id" value="{{.ID}}"><button type="submit" class="link small">Forget</button></form></td>
</tr>{{end}}</tbody>
</table>
{{else}}<p class="help">No lost links{{if $d.LinkCount}} among the {{num $d.LinkCount}} known{{end}}.</p>{{end}}
<div class="row">
<form method="post" action="/seo/links/check?site={{$d.Current.Index}}" data-busy="Checking…"><button type="submit" class="secondary small">Check the links due now</button></form>
<span class="small muted">Up to 20 at a time; the rest are checked daily.</span>
</div>
<form method="post" action="/seo/links/add?site={{$d.Current.Index}}" class="cols" data-busy="Adding and checking…">
<label>A page that links to you <input name="source" type="url" placeholder="https://their-site.example/hosting-providers/" required></label>
<label>Your page it links to <span class="muted">(optional)</span> <input name="target" placeholder="/freescout/"></label>
<div class="actions"><button type="submit" class="secondary">Add and check</button></div>
</form>
</section>
{{end}}
{{end}}{{end}}