diff --git a/internal/api/bing/client.go b/internal/api/bing/client.go index ccd6cfc..255dc79 100644 --- a/internal/api/bing/client.go +++ b/internal/api/bing/client.go @@ -1,6 +1,7 @@ // Package bing reads Bing Webmaster Tools through its API // (https://learn.microsoft.com/en-us/bingwebmaster/getting-access): -// a site's traffic, its searches and its crawl issues. It only reads. +// a site's traffic, its searches, its crawl issues and the links to it. +// It only reads. package bing import ( @@ -38,8 +39,11 @@ func (c *Client) WithBase(u string) *Client { return c } -func (c *Client) get(ctx context.Context, method, site string, out any) error { +func (c *Client) get(ctx context.Context, method, site string, out any, extra ...string) error { q := url.Values{"apikey": {c.key}, "siteUrl": {site}} + for i := 0; i+1 < len(extra); i += 2 { + q.Set(extra[i], extra[i+1]) + } req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/"+method+"?"+q.Encode(), nil) if err != nil { return err @@ -135,3 +139,37 @@ func (c *Client) CrawlIssues(ctx context.Context, site string) ([]CrawlIssue, er err := c.get(ctx, "GetCrawlIssues", site, &out) return out, err } + +// LinkCount is how many links Bing knows to one page of the site. +type LinkCount struct { + URL string `json:"Url"` + Count int `json:"Count"` +} + +// LinkCounts are one page (from 0) of the site's pages with the number of +// links to each, and how many pages of results there are. +func (c *Client) LinkCounts(ctx context.Context, site string, page int) ([]LinkCount, int, error) { + var out struct { + Links []LinkCount `json:"Links"` + TotalPages int `json:"TotalPages"` + } + err := c.get(ctx, "GetLinkCounts", site, &out, "page", strconv.Itoa(page)) + return out.Links, out.TotalPages, err +} + +// Link is a page that links to the site, with its anchor text. +type Link struct { + URL string `json:"Url"` + Anchor string `json:"AnchorText"` +} + +// URLLinks are one page (from 0) of the pages linking to one page of the +// site, and how many pages of results there are. +func (c *Client) URLLinks(ctx context.Context, site, target string, page int) ([]Link, int, error) { + var out struct { + Details []Link `json:"Details"` + TotalPages int `json:"TotalPages"` + } + err := c.get(ctx, "GetUrlLinks", site, &out, "link", target, "page", strconv.Itoa(page)) + return out.Details, out.TotalPages, err +} diff --git a/internal/backlinks/backlinks.go b/internal/backlinks/backlinks.go new file mode 100644 index 0000000..96ac19d --- /dev/null +++ b/internal/backlinks/backlinks.go @@ -0,0 +1,272 @@ +// Package backlinks keeps the links from other sites to the company's +// websites: the ones Bing has found, the ones Plausible saw bring visitors +// (the tracking package records those), and ones added by hand; whether +// each is still there; and where a link could be won. +package backlinks + +import ( + "context" + "fmt" + "net/url" + "slices" + "strings" + "time" + + "supermarket/internal/api/bing" + "supermarket/internal/db" +) + +// Where a link was found. +const ( + OriginBing = "bing" + OriginPlausible = "plausible" + OriginManual = "manual" +) + +const dayFormat = "2006-01-02" + +// Limits on one Bing read: pages of link counts, how many of the site's +// pages get their linking pages read, and pages of those per page. +const ( + maxCountPages = 10 + maxTargets = 25 + maxLinkPages = 5 + bingEvery = 7 * 24 * time.Hour + countsKeyStart = "backlinks:counts:" +) + +// Counted is a page of the site with the number of links Bing knows to it. +type Counted struct { + Path string `json:"path"` + URL string `json:"url"` + Count int `json:"count"` +} + +// BingState is what the last Bing read found. +type BingState struct { + At time.Time `json:"at"` + First string `json:"first"` // the day of the first read: links seen then aren't "new" + Pages []Counted `json:"pages"` // the site's pages by links to them, most first + Total int `json:"total"` + Linked int `json:"linked"` // linking pages stored this time + Error string `json:"error,omitempty"` +} + +func bingKey(site string) string { return countsKeyStart + site } + +// LastBing is the last Bing read of a site, or nil. +func LastBing(d *db.DB, site string) (*BingState, error) { + var st BingState + ok, err := d.GetJSON(bingKey(site), &st) + if err != nil || !ok { + return nil, err + } + return &st, nil +} + +// DueBing says whether a site's links should be read from Bing again. +func DueBing(d *db.DB, site string, now time.Time) bool { + st, _ := LastBing(d, site) + return st == nil || now.Sub(st.At) > bingEvery +} + +// SyncBing reads the links Bing knows to a website: how many to each of +// its pages, and for the most linked pages, which pages link there and +// with what text. bingSite is how Bing names the site; siteURL is the +// website's address in the profile, which the links are kept under. +func SyncBing(ctx context.Context, d *db.DB, c *bing.Client, siteURL, bingSite string, now time.Time) (*BingState, error) { + prev, _ := LastBing(d, siteURL) + st := &BingState{At: now, First: now.Format(dayFormat)} + if prev != nil && prev.First != "" { + st.First = prev.First + } + fail := func(err error) (*BingState, error) { + st.Error = err.Error() + if prev != nil { // keep what was read last time + st.Pages, st.Total, st.First = prev.Pages, prev.Total, prev.First + } + _ = d.PutJSON(bingKey(siteURL), st) + return st, err + } + for page := 0; page < maxCountPages; page++ { + counts, total, err := c.LinkCounts(ctx, bingSite, page) + if err != nil { + return fail(err) + } + for _, lc := range counts { + st.Pages = append(st.Pages, Counted{Path: pathOf(lc.URL), URL: lc.URL, Count: lc.Count}) + st.Total += lc.Count + } + if page+1 >= total { + break + } + } + slices.SortStableFunc(st.Pages, func(a, b Counted) int { return b.Count - a.Count }) + today := now.Format(dayFormat) + for i, t := range st.Pages { + if i == maxTargets { + break + } + for page := 0; page < maxLinkPages; page++ { + links, total, err := c.URLLinks(ctx, bingSite, t.URL, page) + if err != nil { + return fail(fmt.Errorf("the links to %s: %w", t.Path, err)) + } + for _, l := range links { + if l.URL == "" { + continue + } + if err := upsert(d, siteURL, l.URL, t.Path, strings.TrimSpace(l.Anchor), OriginBing, today); err != nil { + return fail(err) + } + st.Linked++ + } + if page+1 >= total { + break + } + } + } + return st, d.PutJSON(bingKey(siteURL), st) +} + +// upsert keeps a link, first and last seen; a link found again by another +// origin keeps its first origin, and gains an anchor it lacked. +func upsert(d *db.DB, site, source, target, anchor, origin, day string) error { + if u, err := url.Parse(source); err == nil { + u.Fragment = "" + source = u.String() + } + _, err := d.Exec(`INSERT INTO backlinks (site, source_url, target, anchor, origin, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (site, source_url, target) DO UPDATE SET + last_seen = max(last_seen, excluded.last_seen), + anchor = CASE WHEN anchor = '' THEN excluded.anchor ELSE anchor END`, + site, source, target, anchor, origin, day, day) + return err +} + +// Link is a known link to the site. +type Link struct { + ID int64 + Source string // the linking page + Target string // our page's path + Anchor string + Origin string + FirstSeen string + LastSeen string + Status string + CheckedAt time.Time + Note string +} + +// Host is the linking page's site, without www. +func (l Link) Host() string { return hostOf(l.Source) } + +// Links are a website's known links, newest first. +func Links(d *db.DB, site string) ([]Link, error) { + rows, err := d.Query(`SELECT id, source_url, target, anchor, origin, first_seen, last_seen, status, coalesce(checked_at, ''), note + FROM backlinks WHERE site = ? ORDER BY first_seen DESC, source_url`, site) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Link + for rows.Next() { + var l Link + var checked string + if err := rows.Scan(&l.ID, &l.Source, &l.Target, &l.Anchor, &l.Origin, &l.FirstSeen, &l.LastSeen, &l.Status, &checked, &l.Note); err != nil { + return nil, err + } + l.CheckedAt, _ = time.Parse(time.RFC3339, checked) + out = append(out, l) + } + return out, rows.Err() +} + +// Site is a linking site: its links to the website, grouped. +type Site struct { + Host string + Links int // linking pages + Targets []string // our pages it links to, most linked first + Anchors []string // a few of its anchor texts + Example string // one linking page + FirstSeen string + New bool // first seen after the first read +} + +// Sites groups a website's links by linking site, new ones first, then by +// how many pages link. +func Sites(links []Link, first string) []Site { + by := map[string]*Site{} + targets := map[string]map[string]int{} + for _, l := range links { + h := l.Host() + s := by[h] + if s == nil { + s = &Site{Host: h, Example: l.Source, FirstSeen: l.FirstSeen} + by[h] = s + targets[h] = map[string]int{} + } + s.Links++ + if l.FirstSeen < s.FirstSeen { + s.FirstSeen = l.FirstSeen + } + if l.Target != "" { + targets[h][l.Target]++ + } + if l.Anchor != "" && len(s.Anchors) < 3 && !slices.Contains(s.Anchors, l.Anchor) { + s.Anchors = append(s.Anchors, l.Anchor) + } + } + var out []Site + for h, s := range by { + for t := range targets[h] { + s.Targets = append(s.Targets, t) + } + tc := targets[h] + slices.SortFunc(s.Targets, func(a, b string) int { + if tc[a] != tc[b] { + return tc[b] - tc[a] + } + return strings.Compare(a, b) + }) + s.New = first != "" && s.FirstSeen > first + out = append(out, *s) + } + slices.SortFunc(out, func(a, b Site) int { + if a.New != b.New { + if a.New { + return -1 + } + return 1 + } + if a.Links != b.Links { + return b.Links - a.Links + } + return strings.Compare(a.Host, b.Host) + }) + return out +} + +func hostOf(u string) string { + if p, err := url.Parse(u); err == nil && p.Hostname() != "" { + return strings.TrimPrefix(strings.ToLower(p.Hostname()), "www.") + } + return u +} + +// pathOf is a page's path, with a trailing slash, as the site's other +// tables key pages. +func pathOf(u string) string { + p := u + if pu, err := url.Parse(u); err == nil { + p = pu.Path + } + p = strings.ToLower(p) + if !strings.HasSuffix(p, "/") { + p += "/" + } + if !strings.HasPrefix(p, "/") { + p = "/" + p + } + return p +} diff --git a/internal/backlinks/backlinks_test.go b/internal/backlinks/backlinks_test.go new file mode 100644 index 0000000..1522fa2 --- /dev/null +++ b/internal/backlinks/backlinks_test.go @@ -0,0 +1,89 @@ +package backlinks + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "supermarket/internal/api/bing" + "supermarket/internal/db" +) + +func openDB(t *testing.T) *db.DB { + t.Helper() + d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Close() }) + return d +} + +func TestSyncBing(t *testing.T) { + d := openDB(t) + extra := false + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("apikey") != "k" || q.Get("siteUrl") != "https://example.com/" { + w.WriteHeader(http.StatusUnauthorized) + return + } + var d any + switch r.URL.Path { + case "/GetLinkCounts": + d = map[string]any{"TotalPages": 1, "Links": []map[string]any{ + {"Url": "https://example.com/", "Count": 3}, {"Url": "https://example.com/freescout", "Count": 5}}} + case "/GetUrlLinks": + switch q.Get("link") { + case "https://example.com/freescout": + links := []map[string]any{{"Url": "https://selfhosted.blog/hosts/#top", "AnchorText": "Federated"}, + {"Url": "https://selfhosted.blog/freescout/", "AnchorText": "FreeScout hosting"}} + if extra { + links = append(links, map[string]any{"Url": "https://newsite.example/list", "AnchorText": "a host"}) + } + d = map[string]any{"TotalPages": 1, "Details": links} + default: + d = map[string]any{"TotalPages": 1, "Details": []map[string]any{{"Url": "https://wdtprs.com/2026/11/post/", "AnchorText": ""}}} + } + } + json.NewEncoder(w).Encode(map[string]any{"d": d}) + })) + defer srv.Close() + c := bing.New("k").WithBase(srv.URL) + now := time.Date(2026, 11, 24, 9, 0, 0, 0, time.UTC) + + st, err := SyncBing(context.Background(), d, c, "https://example.com/", "https://example.com/", now) + if err != nil { + t.Fatal(err) + } + if st.Total != 8 || len(st.Pages) != 2 || st.Pages[0].Path != "/freescout/" || st.Linked != 3 { + t.Errorf("state: %+v", st) + } + links, _ := Links(d, "https://example.com/") + sites := Sites(links, st.First) + if len(sites) != 2 || sites[0].Host != "selfhosted.blog" || sites[0].Links != 2 || sites[0].New || sites[0].Targets[0] != "/freescout/" { + t.Errorf("sites: %+v", sites) + } + if DueBing(d, "https://example.com/", now.Add(time.Hour)) || !DueBing(d, "https://example.com/", now.Add(8*24*time.Hour)) { + t.Error("DueBing") + } + + // A week later Bing knows one more site: it's new; nothing doubles. + extra = true + st, _ = SyncBing(context.Background(), d, c, "https://example.com/", "https://example.com/", now.AddDate(0, 0, 7)) + links, _ = Links(d, "https://example.com/") + sites = Sites(links, st.First) + if len(links) != 4 || sites[0].Host != "newsite.example" || !sites[0].New { + t.Errorf("a week later: %d %+v", len(links), sites) + } + + // A refused key keeps what was read before, with the error. + bad := bing.New("x").WithBase(srv.URL) + if st, err := SyncBing(context.Background(), d, bad, "https://example.com/", "https://example.com/", now.AddDate(0, 0, 14)); err == nil || st.Total != 8 || st.Error == "" { + t.Errorf("refused: %+v %v", st, err) + } +} diff --git a/internal/web/links.go b/internal/web/links.go index eff97da..5b81605 100644 --- a/internal/web/links.go +++ b/internal/web/links.go @@ -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() + } +} diff --git a/internal/web/seo.go b/internal/web/seo.go index 9ff9218..f02e389 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -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) diff --git a/internal/web/seo_test.go b/internal/web/seo_test.go index 8bb50d6..636561b 100644 --- a/internal/web/seo_test.go +++ b/internal/web/seo_test.go @@ -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) + } + } +} diff --git a/internal/web/server.go b/internal/web/server.go index efffc22..bdcdfae 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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.", diff --git a/internal/web/templates/seo-links.html b/internal/web/templates/seo-links.html index 85c270e..4633e26 100644 --- a/internal/web/templates/seo-links.html +++ b/internal/web/templates/seo-links.html @@ -27,6 +27,37 @@ {{end}} {{template "last-read" $d.Last}} + +
+

Who links to you

+

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.

+ {{if not $d.BingKey}} +

Save a Bing Webmaster API key under Settings → Search engines: 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.

+ {{else}} +
+ {{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 {{$d.BingSite}}. + +
+ {{with $d.Bing}}{{with .Error}}

{{.}}

{{end}}{{end}} + {{end}} + {{with $d.LinkingSites}} + + + {{range .}} + + + + + {{end}} +
Linking sitePagesTo your pagesLink text
{{.Host}}{{if .New}} new{{end}}
since {{.FirstSeen}}
{{num .Links}}{{range $i, $t := .Targets}}{{if lt $i 3}}{{if $i}}, {{end}}{{$t}}{{end}}{{end}}{{range $i, $a := .Anchors}}{{if $i}} · {{end}}“{{$a}}”{{end}}
+ {{with $d.MoreSites}}

And {{.}} more sites.

{{end}} + {{else}}{{if $d.Bing}}

Bing hasn't found links to the site yet.

{{end}}{{end}} + {{with $d.Bing}}{{with .Pages}} +
Your most linked pages, by Bing's count + {{range $i, $p := .}}{{if lt $i 15}}{{end}}{{end}}
{{$p.Path}}{{num $p.Count}}
+
+ {{end}}{{end}} +
{{end}} {{end}}{{end}}