Phase 8 part 2: who links to you, from Bing

With a Bing Webmaster key, Supermarket reads once a week (or on Read
now) how many links Bing knows to each page of the site, and for the 25
most linked pages, the pages that link and their anchor text, into the
backlinks table. SEO → Links lists the linking sites, new ones first,
with the pages they link to and their link text; without a key it says
how to get one. A refused key keeps the last read, with the error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-24 08:31:27 -07:00
co-authored by Claude Opus 5.5
parent 54ed2e73c6
commit fc7dcf1f66
8 changed files with 532 additions and 2 deletions
+65
View File
@@ -1,8 +1,12 @@
package web
import (
"context"
"net/http"
"strconv"
"time"
"supermarket/internal/backlinks"
"supermarket/internal/profile"
"supermarket/internal/tracking"
)
@@ -44,7 +48,68 @@ func (s *Server) seoLinksPage(w http.ResponseWriter, r *http.Request) {
_ = s.DB.QueryRow(`SELECT count(*) FROM backlinks WHERE site = ?`, cur.URL).Scan(&known)
data["Known"] = known
}
if cur != nil {
data["BingKey"] = s.bing() != nil
data["BingSite"] = s.bingSite(*cur)
st, err := backlinks.LastBing(s.DB, cur.URL)
if err != nil {
s.serverError(w, err)
return
}
data["Bing"] = st
links, err := backlinks.Links(s.DB, cur.URL)
if err != nil {
s.serverError(w, err)
return
}
first := ""
if st != nil {
first = st.First
}
sites := backlinks.Sites(links, first)
data["LinkingSites"], data["LinkCount"] = sites, len(links)
if len(sites) > 30 {
data["MoreSites"], data["LinkingSites"] = len(sites)-30, sites[:30]
}
}
last, _ := tracking.Last(s.DB, "referrers")
data["Last"] = last
s.render(w, r, "seo-links", page{Title: "Links", Nav: "seo/links", 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)
c := s.bing()
if cur == nil || c == nil {
redirect(w, r, "/seo/links", "")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
back := "/seo/links?site=" + strconv.Itoa(cur.Index) + "#bing"
if _, err := backlinks.SyncBing(ctx, s.DB, c, cur.URL, s.bingSite(*cur), time.Now()); err != nil {
redirect(w, r, back, "") // the card shows the error
return
}
redirect(w, r, back, "bing-read")
}
// weeklyBingLinks reads each website's links from Bing once a week.
func (s *Server) weeklyBingLinks(ctx context.Context) {
c := s.bing()
if c == nil {
return
}
now := time.Now()
for _, site := range s.seoSites() {
if site.URL == "" || !backlinks.DueBing(s.DB, site.URL, now) {
continue
}
bctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
if _, err := backlinks.SyncBing(bctx, s.DB, c, site.URL, s.bingSite(site), now); err != nil {
s.Log.Warn("backlinks: reading Bing", "site", site.URL, "err", err)
}
cancel()
}
}
+1
View File
@@ -296,6 +296,7 @@ func (s *Server) RunSEO(ctx context.Context) {
s.weeklyReports(ctx, time.Now())
s.dailyChecks(ctx)
}
s.weeklyBingLinks(ctx)
s.refreshChanges(ctx)
s.refreshBriefs(ctx)
s.refreshSitePages(ctx)
+32
View File
@@ -171,3 +171,35 @@ func TestWhatToWriteNext(t *testing.T) {
t.Error("New pages wasn't filled in")
}
}
func TestLinksFromBing(t *testing.T) {
b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var d any
switch r.URL.Path {
case "/GetLinkCounts":
d = map[string]any{"TotalPages": 1, "Links": []map[string]any{{"Url": "https://acme.example/freescout", "Count": 2}}}
case "/GetUrlLinks":
d = map[string]any{"TotalPages": 1, "Details": []map[string]any{{"Url": "https://selfhosted.blog/hosts/", "AnchorText": "Acme hosting"}}}
}
json.NewEncoder(w).Encode(map[string]any{"d": d})
}))
defer b.Close()
bingBase = b.URL
defer func() { bingBase = "" }()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example/", SearchConsoleProperty: "sc-domain:acme.example"}}})
if body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String(); !strings.Contains(body, "Save a Bing Webmaster API key") {
t.Errorf("without a key: %s", body)
}
postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}})
if rec := postForm(h, "/seo/links/bing?site=0", nil); rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "msg=bing-read") {
t.Fatalf("read: %d %s", rec.Code, rec.Header().Get("Location"))
}
body := do(h, http.MethodGet, "/seo/links", nil, nil).Body.String()
for _, want := range []string{"selfhosted.blog", "“Acme hosting”", "/freescout/", "2 links to 1 page"} {
if !strings.Contains(body, want) {
t.Errorf("links page lacks %q", want)
}
}
}
+2
View File
@@ -224,6 +224,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /seo/report", s.seoReportPage)
mux.HandleFunc("GET /seo/next", s.seoNextPage)
mux.HandleFunc("GET /seo/links", s.seoLinksPage)
mux.HandleFunc("POST /seo/links/bing", s.seoLinksBing)
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
@@ -546,6 +547,7 @@ 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.",
"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.",
"no-data": "There isn't two weeks of Search Console data yet.",
+31
View File
@@ -27,6 +27,37 @@
{{end}}
{{template "last-read" $d.Last}}
</section>
<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>
{{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}}
<form method="post" action="/seo/links/bing?site={{$d.Current.Index}}" data-busy="Reading Bing…" class="row">
<span class="small muted">{{with $d.Bing}}Read {{ago .At}}{{if .Total}}: {{num .Total}} {{if eq .Total 1}}link{{else}}links{{end}} to {{len .Pages}} {{if eq (len .Pages) 1}}page{{else}}pages{{end}}{{end}}.{{else}}Not read yet.{{end}} Bing names the site <code>{{$d.BingSite}}</code>.</span>
<button type="submit" class="secondary small">Read now</button>
</form>
{{with $d.Bing}}{{with .Error}}<p class="error-text small">{{.}}</p>{{end}}{{end}}
{{end}}
{{with $d.LinkingSites}}
<table class="list">
<thead><tr><th>Linking site</th><th class="num">Pages</th><th>To your pages</th><th>Link text</th></tr></thead>
<tbody>{{range .}}<tr>
<td><a href="{{.Example}}" target="_blank" rel="noopener noreferrer">{{.Host}}</a>{{if .New}} <span class="badge published">new</span>{{end}}<br><span class="small muted">since {{.FirstSeen}}</span></td>
<td class="num">{{num .Links}}</td>
<td class="small">{{range $i, $t := .Targets}}{{if lt $i 3}}{{if $i}}, {{end}}{{$t}}{{end}}{{end}}</td>
<td class="small">{{range $i, $a := .Anchors}}{{if $i}} · {{end}}“{{$a}}”{{end}}</td>
</tr>{{end}}</tbody>
</table>
{{with $d.MoreSites}}<p class="help">And {{.}} more sites.</p>{{end}}
{{else}}{{if $d.Bing}}<p class="help">Bing hasn't found links to the site yet.</p>{{end}}{{end}}
{{with $d.Bing}}{{with .Pages}}
<details class="small"><summary>Your most linked pages, by Bing's count</summary>
<table class="list compact"><tbody>{{range $i, $p := .}}{{if lt $i 15}}<tr><td>{{$p.Path}}</td><td class="num">{{num $p.Count}}</td></tr>{{end}}{{end}}</tbody></table>
</details>
{{end}}{{end}}
</section>
{{end}}
{{end}}{{end}}