Phase 3 part 7: Bing, IndexNow and search engine setup

SEO → Search engines: a pull request that adds the IndexNow key file, a
robots.txt naming the sitemap, and turns the sitemap on when the Hugo
config disables it (checked with a build); IndexNow submissions of pages
that go live through Changes or Briefs once the key file is served; the
sitemaps Search Console has; and, with an API key, Bing's traffic,
searches and crawl issues. NewlyLive no longer queries while a result
set holds the database's only connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 08:45:13 -07:00
co-authored by Claude Opus 5.5
parent bf933971dd
commit 2302fb0436
18 changed files with 1061 additions and 4 deletions
+137
View File
@@ -0,0 +1,137 @@
// 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.
package bing
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
)
const apiBase = "https://ssl.bing.com/webmaster/api.svc/json"
// ErrUnauthorized means the key was refused.
var ErrUnauthorized = errors.New("Bing refused the API key")
// Client calls the API with one key.
type Client struct {
key, base string
http *http.Client
}
func New(key string) *Client {
return &Client{key: key, base: apiBase, http: &http.Client{Timeout: time.Minute}}
}
// WithBase points the client at another server (for tests).
func (c *Client) WithBase(u string) *Client {
c.base = strings.TrimRight(u, "/")
return c
}
func (c *Client) get(ctx context.Context, method, site string, out any) error {
q := url.Values{"apikey": {c.key}, "siteUrl": {site}}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/"+method+"?"+q.Encode(), nil)
if err != nil {
return err
}
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 16<<20))
if err != nil {
return err
}
if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
return ErrUnauthorized
}
if res.StatusCode != http.StatusOK {
var e struct {
Message string `json:"Message"`
}
if json.Unmarshal(raw, &e) == nil && e.Message != "" {
return fmt.Errorf("Bing %s: %s", method, e.Message)
}
return fmt.Errorf("Bing %s: HTTP %d", method, res.StatusCode)
}
var env struct {
D json.RawMessage `json:"d"`
}
if err := json.Unmarshal(raw, &env); err != nil {
return fmt.Errorf("Bing %s: %w", method, err)
}
return json.Unmarshal(env.D, out)
}
// Date is Bing's "/Date(1700000000000-0700)/".
type Date struct{ time.Time }
var msDate = regexp.MustCompile(`/Date\((-?\d+)`)
func (d *Date) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return nil
}
if m := msDate.FindStringSubmatch(s); m != nil {
ms, _ := strconv.ParseInt(m[1], 10, 64)
d.Time = time.UnixMilli(ms).UTC()
}
return nil
}
// Day is one day's (or week's) traffic.
type Day struct {
Date Date `json:"Date"`
Clicks int `json:"Clicks"`
Impressions int `json:"Impressions"`
}
// Traffic is the site's clicks and impressions over time.
func (c *Client) Traffic(ctx context.Context, site string) ([]Day, error) {
var out []Day
err := c.get(ctx, "GetRankAndTrafficStats", site, &out)
return out, err
}
// Query is a search's numbers.
type Query struct {
Query string `json:"Query"`
Date Date `json:"Date"`
Clicks int `json:"Clicks"`
Impressions int `json:"Impressions"`
Position float64 `json:"AvgImpressionPosition"`
}
// Queries are the site's searches, by week.
func (c *Client) Queries(ctx context.Context, site string) ([]Query, error) {
var out []Query
err := c.get(ctx, "GetQueryStats", site, &out)
return out, err
}
// CrawlIssue is a page Bing had trouble with.
type CrawlIssue struct {
URL string `json:"Url"`
HTTPCode int `json:"HttpCode"`
Issues int `json:"Issues"` // flags
InLinks int `json:"InLinks"`
}
// CrawlIssues lists the pages Bing had trouble crawling.
func (c *Client) CrawlIssues(ctx context.Context, site string) ([]CrawlIssue, error) {
var out []CrawlIssue
err := c.get(ctx, "GetCrawlIssues", site, &out)
return out, err
}
+46
View File
@@ -0,0 +1,46 @@
package bing
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
func TestClient(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("apikey") != "k" {
w.WriteHeader(http.StatusUnauthorized)
return
}
if r.URL.Query().Get("siteUrl") != "https://us.example/" {
t.Errorf("site: %s", r.URL)
}
switch r.URL.Path {
case "/GetRankAndTrafficStats":
w.Write([]byte(`{"d":[{"__type":"x","Clicks":12,"Date":"/Date(1763337600000-0800)/","Impressions":340}]}`))
case "/GetQueryStats":
w.Write([]byte(`{"d":[{"Query":"nextcloud hosting","Clicks":2,"Impressions":90,"AvgImpressionPosition":8.5,"Date":"/Date(1763337600000)/"}]}`))
case "/GetCrawlIssues":
w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404,"Issues":1}]}`))
}
}))
defer srv.Close()
ctx := context.Background()
c := New("k").WithBase(srv.URL)
days, err := c.Traffic(ctx, "https://us.example/")
if err != nil || len(days) != 1 || days[0].Clicks != 12 || days[0].Date.Year() != 2025 {
t.Errorf("traffic: %+v %v", days, err)
}
qs, err := c.Queries(ctx, "https://us.example/")
if err != nil || qs[0].Position != 8.5 {
t.Errorf("queries: %+v %v", qs, err)
}
is, err := c.CrawlIssues(ctx, "https://us.example/")
if err != nil || is[0].HTTPCode != 404 {
t.Errorf("issues: %+v %v", is, err)
}
if _, err := New("bad").WithBase(srv.URL).Traffic(ctx, "https://us.example/"); err != ErrUnauthorized {
t.Errorf("bad key: %v", err)
}
}
+25
View File
@@ -154,3 +154,28 @@ func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, er
q.StartRow += maxRows
}
}
// Sitemap is a sitemap Search Console knows about.
type Sitemap struct {
Path string `json:"path"`
LastSubmitted *time.Time `json:"lastSubmitted"`
LastDownloaded *time.Time `json:"lastDownloaded"`
IsPending bool `json:"isPending"`
Warnings string `json:"warnings"`
Errors string `json:"errors"`
Contents []struct {
Type string `json:"type"`
Submitted string `json:"submitted"`
} `json:"contents"`
}
// Sitemaps lists the sitemaps submitted for a property.
func (c *Client) Sitemaps(ctx context.Context, site string) ([]Sitemap, error) {
var out struct {
Sitemap []Sitemap `json:"sitemap"`
}
if err := c.do(ctx, http.MethodGet, "/sites/"+url.PathEscape(site)+"/sitemaps", nil, &out); err != nil {
return nil, err
}
return out.Sitemap, nil
}
+94 -2
View File
@@ -29,6 +29,8 @@ type Repo struct {
Token string // sent as a header, never stored in the copy
Branch string // the branch that gets published
Author string // "Name <email>" for commits
touched []string // files written outside content/, to commit
}
// git runs a git command in the working copy, with the token as an HTTP
@@ -103,7 +105,7 @@ func (r *Repo) NewBranch(ctx context.Context, name string) error {
// Diff is the working copy's uncommitted change, new files included.
func (r *Repo) Diff(ctx context.Context) (string, error) {
if _, err := r.git(ctx, "add", "-A", "--intent-to-add", "content"); err != nil {
if _, err := r.git(ctx, append([]string{"add", "-A", "--intent-to-add", "content"}, r.touched...)...); err != nil {
return "", err
}
return r.git(ctx, "diff")
@@ -111,7 +113,7 @@ func (r *Repo) Diff(ctx context.Context) (string, error) {
// CommitAndPush commits everything changed and pushes the current branch.
func (r *Repo) CommitAndPush(ctx context.Context, branch, message string) error {
if _, err := r.git(ctx, "add", "-A", "content"); err != nil {
if _, err := r.git(ctx, append([]string{"add", "-A", "content"}, r.touched...)...); err != nil {
return err
}
if _, err := r.git(ctx, "commit", "--quiet", "-am", message); err != nil {
@@ -442,3 +444,93 @@ func (r *Repo) ReplaceBody(rel, body string) error {
out := strings.Join(lines[:end+1], "\n") + "\n\n" + strings.TrimSpace(body) + "\n"
return os.WriteFile(path, []byte(out), 0o644)
}
// --- Files outside content ---
// inside resolves a path in the repository, refusing ones that leave it.
func (r *Repo) inside(rel string) (string, error) {
p := filepath.Clean(filepath.Join(r.Dir, rel))
if !strings.HasPrefix(p, filepath.Clean(r.Dir)+string(filepath.Separator)) {
return "", fmt.Errorf("%s is outside the repository", rel)
}
return p, nil
}
// Exists reports whether a file is in the working copy.
func (r *Repo) Exists(rel string) bool {
p, err := r.inside(rel)
if err != nil {
return false
}
_, err = os.Stat(p)
return err == nil
}
// WriteFile writes a file anywhere in the repository and marks it to be
// committed.
func (r *Repo) WriteFile(rel, content string) error {
p, err := r.inside(rel)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
return err
}
r.touched = append(r.touched, filepath.ToSlash(rel))
return nil
}
// ConfigFile is the site's main Hugo configuration file, or "".
func (r *Repo) ConfigFile() string {
for _, name := range []string{"hugo.toml", "hugo.yaml", "hugo.yml", "config.toml", "config.yaml", "config.yml",
"config/_default/hugo.toml", "config/_default/hugo.yaml", "config/_default/config.toml", "config/_default/config.yaml"} {
if r.Exists(name) {
return name
}
}
return ""
}
var disableKinds = regexp.MustCompile(`(?m)^(\s*disableKinds\s*[:=]\s*\[)([^\]]*)(\])`)
// EnableSitemap takes "sitemap" out of the config's disableKinds, when it's
// written on one line. It reports whether it changed anything.
func (r *Repo) EnableSitemap() (bool, error) {
cfg := r.ConfigFile()
if cfg == "" {
return false, nil
}
p, _ := r.inside(cfg)
raw, err := os.ReadFile(p)
if err != nil {
return false, err
}
changed := false
out := disableKinds.ReplaceAllStringFunc(string(raw), func(m string) string {
parts := disableKinds.FindStringSubmatch(m)
var keep []string
for _, k := range strings.Split(parts[2], ",") {
if t := strings.Trim(strings.TrimSpace(k), `"'`); strings.EqualFold(t, "sitemap") {
changed = true
continue
}
if strings.TrimSpace(k) != "" {
keep = append(keep, strings.TrimSpace(k))
}
}
return parts[1] + strings.Join(keep, ", ") + parts[3]
})
if !changed {
return false, nil
}
return true, r.WriteFile(cfg, out)
}
// BuiltFile reads a file from a build.
func BuiltFile(outDir, rel string) (string, error) {
raw, err := os.ReadFile(filepath.Join(outDir, rel))
return string(raw), err
}
+1
View File
@@ -44,6 +44,7 @@ const (
GoogleRefreshToken = "google.refresh_token" // Search Console, read-only
PageSpeedAPIKey = "pagespeed.api_key"
GiteaToken = "gitea.token" // opens pull requests on the sites' repositories
BingAPIKey = "bing.api_key"
PlausibleAPIKey = "plausible.api_key"
StripeAPIKey = "stripe.api_key" // restricted, read-only
+267
View File
@@ -0,0 +1,267 @@
package seo
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"supermarket/internal/db"
"supermarket/internal/hugorepo"
)
// --- IndexNow ---
// IndexNowURL is where pings go; it shares them with Bing, Yandex, Seznam,
// Naver and the other engines that take part (Google doesn't). Tests
// replace it.
var IndexNowURL = "https://api.indexnow.org/indexnow"
const indexNowKeyKey = "seo:indexnow-key"
// IndexNowKey is the site's IndexNow key, made the first time. It isn't a
// secret: it's published in a file on the site.
func IndexNowKey(d *db.DB) (string, error) {
var k string
if _, err := d.GetJSON(indexNowKeyKey, &k); err != nil {
return "", err
}
if k != "" {
return k, nil
}
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
k = hex.EncodeToString(b)
return k, d.PutJSON(indexNowKeyKey, k)
}
// KeyFileURL is where the key file must be on a site.
func KeyFileURL(site, key string) string {
return strings.TrimRight(site, "/") + "/" + key + ".txt"
}
// KeyLive reports whether the site serves its IndexNow key file.
func KeyLive(ctx context.Context, f *Fetcher, site, key string) bool {
r, err := f.get(ctx, KeyFileURL(site, key), http.MethodGet, 4096)
return err == nil && r.status == 200 && strings.TrimSpace(string(r.body)) == key
}
// Ping is one IndexNow submission.
type Ping struct {
At time.Time `json:"at"`
URLs []string `json:"urls"`
Status int `json:"status"`
Error string `json:"error,omitempty"`
}
func pingsKey(site string) string { return "seo:indexnow-pings:" + site }
// Pings are a site's recent submissions, newest first.
func Pings(d *db.DB, site string) []Ping {
var out []Ping
_, _ = d.GetJSON(pingsKey(site), &out)
return out
}
// pinged reports whether a page was submitted already.
func pinged(d *db.DB, site, page string) bool {
for _, p := range Pings(d, site) {
for _, u := range p.URLs {
if u == page && p.Error == "" {
return true
}
}
}
return false
}
// SubmitIndexNow tells the IndexNow engines that pages changed, and keeps
// the submission.
func SubmitIndexNow(ctx context.Context, d *db.DB, site, key string, pages []string, now time.Time) (*Ping, error) {
u, err := url.Parse(site)
if err != nil || u.Host == "" {
return nil, fmt.Errorf("%q isn't a website address", site)
}
body, _ := json.Marshal(map[string]any{"host": u.Host, "key": key, "keyLocation": KeyFileURL(site, key), "urlList": pages})
p := &Ping{At: now, URLs: pages}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, IndexNowURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
res, err := http.DefaultClient.Do(req)
if err != nil {
p.Error = err.Error()
} else {
p.Status = res.StatusCode
msg, _ := io.ReadAll(io.LimitReader(res.Body, 2048))
res.Body.Close()
// 200: accepted; 202: accepted, the key is being checked.
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted {
p.Error = fmt.Sprintf("IndexNow said HTTP %d %s", res.StatusCode, strings.TrimSpace(string(msg)))
}
}
list := append([]Ping{*p}, Pings(d, site)...)
if len(list) > 30 {
list = list[:30]
}
if perr := d.PutJSON(pingsKey(site), list); perr != nil {
return p, perr
}
if p.Error != "" {
return p, errors.New(p.Error)
}
return p, nil
}
// NewlyLive are the site's pages that went live in the last 14 days (from
// changes and briefs) and haven't been submitted to IndexNow yet.
func NewlyLive(d *db.DB, site string, now time.Time) ([]string, error) {
since := now.AddDate(0, 0, -14).UTC().Format(time.RFC3339)
rows, err := d.Query(`SELECT page FROM seo_changes WHERE site = ? AND status = 'live' AND live_at >= ?
UNION SELECT page FROM seo_briefs WHERE site = ? AND status = 'live' AND live_at >= ? AND page != ''`, site, since, site, since)
if err != nil {
return nil, err
}
// Read every row before looking anything else up: the database has one
// connection, which the open query holds.
var live []string
for rows.Next() {
var p string
if err := rows.Scan(&p); err != nil {
rows.Close()
return nil, err
}
live = append(live, p)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
var out []string
for _, p := range live {
if !pinged(d, site, p) {
out = append(out, p)
}
}
return out, nil
}
// --- Setting the site up for search engines ---
// Setup is the "set the site up" pull request's state.
type Setup struct {
At time.Time `json:"at"`
PRNumber int64 `json:"pr_number"`
PRURL string `json:"pr_url"`
Done []string `json:"done"`
Note string `json:"note"`
Error string `json:"error,omitempty"`
}
func setupKey(site string) string { return "seo:setup:" + site }
// LastSetup is a site's last setup pull request, or nil.
func LastSetup(d *db.DB, site string) *Setup {
var s Setup
if ok, _ := d.GetJSON(setupKey(site), &s); !ok {
return nil
}
return &s
}
// SetupSite opens one pull request that gets the site ready for search
// engines: the IndexNow key file, a robots.txt naming the sitemap (unless
// the site has its own), and the sitemap turned back on if the Hugo config
// turns it off. A build checks the sitemap, robots.txt and key file come
// out.
func (ap *Applier) SetupSite(ctx context.Context, d *db.DB, site, key string, now time.Time) (*Setup, error) {
st := &Setup{At: now}
err := ap.setupSite(ctx, site, key, st)
if err != nil {
st.Error = err.Error()
}
if perr := d.PutJSON(setupKey(site), st); perr != nil && err == nil {
err = perr
}
return st, err
}
func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) error {
wc, full, branch, err := ap.workingCopy(ctx)
if err != nil {
return err
}
canBuild, note := buildCheck(ctx, wc)
work := "supermarket/search-engines"
if err := wc.NewBranch(ctx, work); err != nil {
return err
}
keyFile := "static/" + key + ".txt"
if !wc.Exists(keyFile) {
if err := wc.WriteFile(keyFile, key+"\n"); err != nil {
return err
}
st.Done = append(st.Done, "Adds the IndexNow key file ("+key+".txt), so Supermarket can tell Bing and other engines when a page changes.")
}
if !wc.Exists("static/robots.txt") && !wc.Exists("layouts/robots.txt") {
robots := "User-agent: *\nAllow: /\n\nSitemap: " + strings.TrimRight(site, "/") + "/sitemap.xml\n"
if err := wc.WriteFile("static/robots.txt", robots); err != nil {
return err
}
st.Done = append(st.Done, "Adds a robots.txt that lets every crawler in and names the sitemap.")
}
if changed, err := wc.EnableSitemap(); err != nil {
return err
} else if changed {
st.Done = append(st.Done, "Turns the sitemap back on: the Hugo config listed it under disableKinds.")
}
if len(st.Done) == 0 {
return errors.New("the site already has the key file and its own robots.txt, and its config doesn't turn the sitemap off")
}
if canBuild {
out, err := wc.Build(ctx)
if err != nil {
return fmt.Errorf("after the change, %w", err)
}
var missing []string
for _, f := range []string{"sitemap.xml", "robots.txt", key + ".txt"} {
if _, err := hugorepo.BuiltFile(out, f); err != nil {
missing = append(missing, f)
}
}
os.RemoveAll(out)
if len(missing) > 0 {
note = "The build doesn't produce " + strings.Join(missing, ", ") + ": the theme or config may turn it off in a way Supermarket can't change; check before merging."
} else {
note = "Checked with a build: the site now produces sitemap.xml, robots.txt and the key file."
}
}
subject := "SEO: set the site up for search engines"
if err := wc.CommitAndPush(ctx, work, subject); err != nil {
return err
}
var body strings.Builder
body.WriteString("Proposed by Supermarket, from the audit.\n\n")
for _, d := range st.Done {
body.WriteString("- " + d + "\n")
}
body.WriteString("\n" + note + "\n\nAfter merging, submit " + strings.TrimRight(site, "/") + "/sitemap.xml in Google Search Console and Bing Webmaster Tools.")
pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, body.String())
if err != nil {
return err
}
st.PRNumber, st.PRURL, st.Note = pr.Number, pr.HTMLURL, note
return nil
}
+113
View File
@@ -0,0 +1,113 @@
package seo
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/hugorepo/hugotest"
)
func TestIndexNow(t *testing.T) {
d := openDB(t)
key, err := IndexNowKey(d)
if err != nil || len(key) != 32 {
t.Fatalf("key: %q %v", key, err)
}
if again, _ := IndexNowKey(d); again != key {
t.Error("the key changed")
}
var got map[string]any
in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&got)
w.WriteHeader(http.StatusAccepted)
}))
defer in.Close()
IndexNowURL = in.URL
defer func() { IndexNowURL = "https://api.indexnow.org/indexnow" }()
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/"+key+".txt" {
fmt.Fprintln(w, key)
return
}
http.NotFound(w, r)
}))
defer site.Close()
f := NewFetcher("test")
if !KeyLive(context.Background(), f, site.URL, key) || KeyLive(context.Background(), f, site.URL, "other") {
t.Error("key check")
}
// A change went live: it's waiting to be submitted, then it isn't.
now := time.Now()
c := &Change{Site: site.URL + "/", Page: site.URL + "/pricing/", NewTitle: "x", CreatedAt: now}
insertChange(d, c)
d.Exec(`UPDATE seo_changes SET status = 'live', live_at = ? WHERE id = ?`, now.UTC().Format(time.RFC3339), c.ID)
pages, _ := NewlyLive(d, site.URL+"/", now)
if len(pages) != 1 {
t.Fatalf("newly live: %v", pages)
}
p, err := SubmitIndexNow(context.Background(), d, site.URL+"/", key, pages, now)
if err != nil || p.Status != 202 {
t.Fatalf("submit: %+v %v", p, err)
}
if got["key"] != key || got["keyLocation"] != site.URL+"/"+key+".txt" || !strings.HasPrefix(site.URL, "http://"+got["host"].(string)) {
t.Errorf("request: %+v", got)
}
if pages, _ := NewlyLive(d, site.URL+"/", now); len(pages) != 0 {
t.Errorf("submitted twice: %v", pages)
}
if len(Pings(d, site.URL+"/")) != 1 {
t.Error("the ping isn't kept")
}
}
func TestSetupSite(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
d := openDB(t)
clone := hugotest.Site(t)
var body map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/o/site":
json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}})
case r.URL.Path == "/api/v1/repos/o/site/pulls":
json.NewDecoder(r.Body).Decode(&body)
json.NewEncoder(w).Encode(map[string]any{"number": 3, "html_url": "https://gitea.example/pr/3"})
}
}))
defer g.Close()
ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "P <p@example.com>"}
st, err := ap.SetupSite(context.Background(), d, "https://site.example", "abc123", time.Now())
if err != nil {
t.Fatal(err)
}
if st.PRNumber != 3 || len(st.Done) != 3 || !strings.HasPrefix(st.Note, "Checked with a build") {
t.Fatalf("setup: %+v", st)
}
if !strings.Contains(body["body"], "Turns the sitemap back on") || !strings.Contains(body["body"], "https://site.example/sitemap.xml") {
t.Errorf("pull request: %s", body["body"])
}
repo := strings.TrimPrefix(clone, "file://")
for file, want := range map[string]string{
"static/abc123.txt": "abc123", "static/robots.txt": "Sitemap: https://site.example/sitemap.xml", "hugo.toml": "disableKinds = ['taxonomy', 'term', 'RSS']",
} {
out, err := exec.Command("git", "-C", repo, "show", "supermarket/search-engines:"+file).CombinedOutput()
if err != nil || !strings.Contains(string(out), want) {
t.Errorf("%s: %s %v", file, out, err)
}
}
if LastSetup(d, "https://site.example") == nil {
t.Error("the setup isn't kept")
}
}
+196
View File
@@ -0,0 +1,196 @@
package web
import (
"context"
"net/http"
"slices"
"strconv"
"strings"
"time"
"supermarket/internal/api/bing"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
var bingKey = secretField{"bing", secrets.BingAPIKey, "Bing Webmaster API key (optional)",
"In Bing Webmaster Tools: Settings (the gear) → API access → API key. Your site must be verified there.", "https://www.bing.com/webmasters"}
// bingBase is the Bing API's address; tests point it elsewhere.
var bingBase = ""
func (s *Server) bing() *bing.Client {
key := s.Secrets.Get(secrets.BingAPIKey)
if key == "" {
return nil
}
c := bing.New(key)
if bingBase != "" {
c.WithBase(bingBase)
}
return c
}
// bingSite is how Bing names a website: the profile's Bing site, or its
// address with a trailing slash.
func (s *Server) bingSite(site seoSite) string {
if p, _ := profile.Load(s.DB); p != nil && site.Index < len(p.Websites) && p.Websites[site.Index].BingSite != "" {
return p.Websites[site.Index].BingSite
}
return strings.TrimRight(site.URL, "/") + "/"
}
type bingQuery struct {
Query string
Clicks, Impressions int
Position float64
}
func (s *Server) seoEnginesPage(w http.ResponseWriter, r *http.Request) {
s.renderEngines(w, r, "")
}
func (s *Server) renderEngines(w http.ResponseWriter, r *http.Request, errMsg string) {
sites, cur := s.auditSites(r)
data := map[string]any{"Sites": sites, "Current": cur}
if cur != nil {
ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second)
defer cancel()
if c := s.gsc(); c != nil && cur.Property != "" {
maps, err := c.Sitemaps(ctx, cur.Property)
data["Sitemaps"], data["SitemapsErr"] = maps, errText(err)
}
data["GoogleConnected"] = s.gsc() != nil && cur.Property != ""
if b := s.bing(); b != nil {
site := s.bingSite(*cur)
data["BingSite"] = site
if days, err := b.Traffic(ctx, site); err != nil {
data["BingErr"] = err.Error()
} else {
slices.SortFunc(days, func(a, b bing.Day) int { return b.Date.Compare(a.Date.Time) })
if len(days) > 8 {
days = days[:8]
}
data["BingDays"] = days
if qs, err := b.Queries(ctx, site); err == nil {
data["BingQueries"] = topBingQueries(qs, 28)
}
if issues, err := b.CrawlIssues(ctx, site); err == nil {
data["BingIssues"] = issues
}
}
}
key, err := seo.IndexNowKey(s.DB)
if err != nil {
s.serverError(w, err)
return
}
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)")
data["Key"], data["KeyURL"], data["KeyLive"] = key, seo.KeyFileURL(cur.URL, key), seo.KeyLive(ctx, f, cur.URL, key)
data["Pings"] = seo.Pings(s.DB, cur.URL)
data["Setup"] = seo.LastSetup(s.DB, cur.URL)
data["Gitea"] = s.gitea() != nil
}
s.render(w, r, "seo-engines", page{Title: "Search engines", Nav: "seo/engines", Error: errMsg, Data: data})
}
func errText(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// topBingQueries sums the last weeks' rows per search, most impressions
// first.
func topBingQueries(qs []bing.Query, days int) []bingQuery {
since := time.Now().AddDate(0, 0, -days)
sum := map[string]*bingQuery{}
var pos = map[string]float64{}
for _, q := range qs {
if q.Date.Before(since) {
continue
}
b := sum[q.Query]
if b == nil {
b = &bingQuery{Query: q.Query}
sum[q.Query] = b
}
b.Clicks += q.Clicks
b.Impressions += q.Impressions
pos[q.Query] += q.Position * float64(q.Impressions)
}
var out []bingQuery
for k, b := range sum {
if b.Impressions > 0 {
b.Position = pos[k] / float64(b.Impressions)
}
out = append(out, *b)
}
slices.SortFunc(out, func(a, b bingQuery) int { return b.Impressions - a.Impressions })
if len(out) > 15 {
out = out[:15]
}
return out
}
// seoEnginesSetup opens the "set the site up for search engines" pull
// request.
func (s *Server) seoEnginesSetup(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
key, err := seo.IndexNowKey(s.DB)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
_, err = s.applier(*cur).SetupSite(ctx, s.DB, cur.URL, key, time.Now())
}
if err != nil {
s.renderEngines(w, r, "Couldn't open the pull request: "+err.Error())
return
}
redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "setup-opened")
}
// seoEnginesPing submits the home page to IndexNow, to check it works.
func (s *Server) seoEnginesPing(w http.ResponseWriter, r *http.Request) {
_, cur := s.auditSites(r)
if cur == nil {
http.NotFound(w, r)
return
}
key, err := seo.IndexNowKey(s.DB)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
_, err = seo.SubmitIndexNow(ctx, s.DB, cur.URL, key, []string{strings.TrimRight(cur.URL, "/") + "/"}, time.Now())
}
if err != nil {
s.renderEngines(w, r, "IndexNow: "+err.Error())
return
}
redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "pinged")
}
// pingNewlyLive submits pages that went live to IndexNow, once the site
// serves its key file.
func (s *Server) pingNewlyLive(ctx context.Context) {
key, err := seo.IndexNowKey(s.DB)
if err != nil {
return
}
f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)")
for _, site := range s.seoSites() {
pages, err := seo.NewlyLive(s.DB, site.URL, time.Now())
if err != nil || len(pages) == 0 || !seo.KeyLive(ctx, f, site.URL, key) {
continue
}
if _, err := seo.SubmitIndexNow(ctx, s.DB, site.URL, key, pages, time.Now()); err != nil {
s.Log.Warn("seo: IndexNow", "site", site.URL, "err", err)
}
}
}
+60
View File
@@ -0,0 +1,60 @@
package web
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/seo"
)
func TestEnginesPage(t *testing.T) {
s, h := newTestServer(t, nil)
key, _ := seo.IndexNowKey(s.DB)
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/"+key+".txt" {
fmt.Fprint(w, key)
return
}
http.NotFound(w, r)
}))
defer site.Close()
b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/GetRankAndTrafficStats":
w.Write([]byte(`{"d":[{"Clicks":12,"Impressions":340,"Date":"/Date(1763337600000)/"}]}`))
case "/GetQueryStats":
w.Write([]byte(`{"d":[]}`))
case "/GetCrawlIssues":
w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404}]}`))
}
}))
defer b.Close()
bingBase = b.URL
defer func() { bingBase = "" }()
var pinged string
in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pinged = r.URL.Path; w.WriteHeader(200) }))
defer in.Close()
seo.IndexNowURL = in.URL
defer func() { seo.IndexNowURL = "https://api.indexnow.org/indexnow" }()
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: site.URL}}})
postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}})
body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String()
for _, want := range []string{key, "the site serves it", "340", "https://us.example/old (404)", "Connect Search Console", "Open the pull request"} {
if !strings.Contains(body, want) {
t.Errorf("page lacks %q", want)
}
}
if rec := postForm(h, "/seo/engines/ping?site=0", nil); rec.Code != http.StatusSeeOther || pinged == "" {
t.Errorf("ping: %d %q", rec.Code, pinged)
}
if body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String(); !strings.Contains(body, "accepted (200)") {
t.Error("the ping isn't listed")
}
}
+4 -1
View File
@@ -115,6 +115,8 @@ func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, er
"Fields": googleFields,
"Speed": pageSpeedKey,
"GiteaKey": giteaToken,
"BingKey": bingKey,
"BingSet": s.Secrets.Has(secrets.BingAPIKey),
"GiteaSet": s.Secrets.Has(secrets.GiteaToken),
"GiteaURL": s.giteaURL(),
"SpeedSet": s.Secrets.Has(secrets.PageSpeedAPIKey),
@@ -142,7 +144,7 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken)); err != nil {
if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken, bingKey)); err != nil {
s.serverError(w, err)
return
}
@@ -268,6 +270,7 @@ func (s *Server) RunSEO(ctx context.Context) {
}
s.refreshChanges(ctx)
s.refreshBriefs(ctx)
s.pingNewlyLive(ctx)
select {
case <-ctx.Done():
return
+5
View File
@@ -161,6 +161,9 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
mux.HandleFunc("GET /seo", s.seoPage)
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
mux.HandleFunc("POST /seo/engines/setup", s.seoEnginesSetup)
mux.HandleFunc("POST /seo/engines/ping", s.seoEnginesPing)
mux.HandleFunc("GET /seo/briefs", s.seoBriefsPage)
mux.HandleFunc("POST /seo/briefs", s.seoBriefNew)
mux.HandleFunc("GET /seo/briefs/{id}", s.seoBriefPage)
@@ -425,6 +428,8 @@ var flashes = map[string]string{
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"pinged": "Sent to IndexNow.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"keywords-found": "Looked for keywords: the candidates are below.",
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+1
View File
@@ -47,6 +47,7 @@
<a href="/seo/keywords" {{if eq $nav "seo/keywords"}}aria-current="page"{{end}}>Next keywords</a>
<a href="/seo/briefs" {{if eq $nav "seo/briefs"}}aria-current="page"{{end}}>Briefs and pages</a>
<a href="/seo/audit" {{if eq $nav "seo/audit"}}aria-current="page"{{end}}>Audit</a>
<a href="/seo/engines" {{if eq $nav "seo/engines"}}aria-current="page"{{end}}>Search engines</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
@@ -34,6 +34,12 @@
</section>
{{end}}
<section class="card" id="bing">
<h3>Bing Webmaster Tools</h3>
<p class="small">Bing's clicks, impressions, searches and crawl issues, on SEO → Search engines. DuckDuckGo and many AI assistants draw on Bing's index.</p>
{{template "key-field" (dict "F" .BingKey "Set" .BingSet)}}
</section>
<section class="card" id="gitea">
<h3>Gitea: your sites' repositories</h3>
<p class="small">For changes you approve: Supermarket pushes a branch to the website's Hugo repository (set in the <a href="/settings/profile">profile</a>) and opens a pull request. It never merges.</p>
+60
View File
@@ -0,0 +1,60 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Search engines</h1></div>
<p class="lede">What Google and Bing know about the site, and IndexNow, which tells Bing and other engines the moment a page changes, so they don't wait for their next crawl. Google doesn't use IndexNow; it reads the sitemap.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your websites to the <a href="/settings/profile">profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/seo/engines?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
<section class="card">
<h2>Set the site up for search engines</h2>
<p>One pull request that adds what's missing: the IndexNow key file, a <code>robots.txt</code> that names the sitemap (unless the site has its own), and the sitemap itself if the Hugo config turns it off. A Hugo build checks all three come out.</p>
{{with .Setup}}
{{if .Error}}<p class="error-text small">Last try, {{ago .At}}: {{.Error}}</p>
{{else}}<p class="small">Opened {{ago .At}}: <a href="{{.PRURL}}" target="_blank" rel="noopener noreferrer">pull request #{{.PRNumber}} ↗</a>. {{range .Done}}{{.}} {{end}}<br><span class="muted">{{.Note}}</span></p>{{end}}
{{end}}
<form method="post" action="/seo/engines/setup?site={{.Current.Index}}" data-busy="Opening…"><button type="submit" {{if not .Gitea}}disabled title="Save a Gitea token under Settings → Search engines"{{end}}>{{if .Setup}}Open it again{{else}}Open the pull request{{end}}</button></form>
</section>
<section class="card">
<h2>IndexNow</h2>
<p class="small">Key <code>{{.Key}}</code>, published at <a href="{{.KeyURL}}" target="_blank" rel="noopener noreferrer">{{.KeyURL}}</a>:
{{if .KeyLive}}<span class="ok">the site serves it.</span> Pages that go live through Changes or Briefs are submitted on their own.
{{else}}<span class="warn-text">not on the site yet.</span> Merge the setup pull request above; until then nothing is submitted.{{end}}</p>
{{if .KeyLive}}<form method="post" action="/seo/engines/ping?site={{.Current.Index}}" class="inline"><button type="submit" class="secondary small">Submit the home page now</button></form>{{end}}
{{if .Pings}}
<table class="list"><thead><tr><th>When</th><th>Pages</th><th>Result</th></tr></thead>
<tbody>{{range .Pings}}<tr><td>{{ago .At}}</td><td class="small">{{range .URLs}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">{{pagePath .}}</a> {{end}}</td>
<td class="small">{{if .Error}}<span class="error-text">{{.Error}}</span>{{else}}accepted ({{.Status}}){{end}}</td></tr>{{end}}</tbody></table>
{{end}}
</section>
<section class="card">
<h2>Google: sitemaps</h2>
{{if not .GoogleConnected}}<p class="help">Connect Search Console and choose this website's property under <a href="/settings/search">Settings → Search engines</a>.</p>
{{else if .SitemapsErr}}<p class="error-text">{{.SitemapsErr}}</p>
{{else if .Sitemaps}}
<table class="list"><thead><tr><th>Sitemap</th><th>Submitted</th><th>Last read</th><th>Pages</th><th>Problems</th></tr></thead>
<tbody>{{range .Sitemaps}}<tr><td class="small">{{.Path}}</td><td class="small">{{with .LastSubmitted}}{{ago .}}{{end}}</td><td class="small">{{with .LastDownloaded}}{{ago .}}{{else}}{{if .IsPending}}pending{{end}}{{end}}</td>
<td class="num">{{range .Contents}}{{if eq .Type "web"}}{{.Submitted}}{{end}}{{end}}</td><td class="small">{{if or (ne .Errors "0") (ne .Warnings "0")}}errors: {{.Errors}}, warnings: {{.Warnings}}{{else}}none{{end}}</td></tr>{{end}}</tbody></table>
{{else}}<p class="warn-text small">Google has no sitemap for this site. Once the site has one, submit it in Search Console (Indexing → Sitemaps): Supermarket's access is read-only.</p>{{end}}
</section>
<section class="card">
<h2>Bing</h2>
{{if not .BingSite}}<p class="help">Save a Bing Webmaster API key under <a href="/settings/search">Settings → Search engines</a> to see Bing's numbers.</p>
{{else if .BingErr}}<p class="error-text">{{.BingErr}} <span class="small muted">(site: {{.BingSite}})</span></p>
{{else}}
{{if .BingDays}}<table class="list"><thead><tr><th>Week of</th><th class="num">Clicks</th><th class="num">Impressions</th></tr></thead>
<tbody>{{range .BingDays}}<tr><td>{{.Date.Format "2 Jan 2006"}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{num .Impressions}}</td></tr>{{end}}</tbody></table>
{{else}}<p class="help">No traffic data from Bing yet.</p>{{end}}
{{if .BingQueries}}<h3>Searches, last 4 weeks</h3>
<table class="list"><thead><tr><th>Search</th><th class="num">Impressions</th><th class="num">Clicks</th><th class="num">Position</th></tr></thead>
<tbody>{{range .BingQueries}}<tr><td>{{.Query}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody></table>{{end}}
<h3>Crawl issues</h3>
{{if .BingIssues}}<ul class="small">{{range .BingIssues}}<li>{{.URL}}{{if .HTTPCode}} ({{.HTTPCode}}){{end}}</li>{{end}}</ul>{{else}}<p class="help">None.</p>{{end}}
{{end}}
</section>
{{end}}
{{end}}{{end}}