package seo import ( "bytes" "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "strings" "time" "supermarket/internal/api/gitea" "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 } defer wc.Release() 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 } // PublishPage opens a pull request that adds a page to the site, or // updates it if it's there: used for the open metrics page. The build // checks the page comes out. func (ap *Applier) PublishPage(ctx context.Context, pagePath, title, description, body, why string) (*gitea.Pull, string, error) { wc, full, branch, err := ap.WorkingCopy(ctx) if err != nil { return nil, "", err } defer wc.Release() canBuild, note := buildCheck(ctx, wc) pagePath = "/" + strings.Trim(pagePath, "/") + "/" work := "supermarket/page" + strings.TrimSuffix(strings.ReplaceAll(pagePath, "/", "-"), "-") if err := wc.NewBranch(ctx, work); err != nil { return nil, "", err } file, err := wc.FindContent(pagePath) if err != nil { file = "content" + strings.TrimSuffix(pagePath, "/") + ".md" } fields := []hugorepo.Field{{Key: "title", Value: title}, {Key: "description", Value: description}, {Key: "date", Value: time.Now().Format("2006-01-02")}} if err := wc.UpsertPage(file, fields, body); err != nil { return nil, "", err } if canBuild { out, err := wc.Build(ctx) if err != nil { return nil, "", fmt.Errorf("after the change, %w", err) } _, _, err = hugorepo.BuiltHead(out, pagePath) os.RemoveAll(out) if err != nil { return nil, "", fmt.Errorf("the site builds, but %w", err) } note = "Checked with a build: the page is at " + pagePath + "." } subject := "Update " + pagePath + ": " + title if err := wc.CommitAndPush(ctx, work, subject); err != nil { return nil, "", err } pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, why+"\n\n"+note+"\n\nMerging publishes it.") if err != nil { return nil, "", err } return pr, file, nil }