package sites
import (
"context"
"fmt"
"html"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"gopkg.in/yaml.v3"
"supermarket/internal/api/gitea"
"supermarket/internal/db"
"supermarket/internal/seo"
)
// GiveUpAfter is how long after merging a page that still isn't live is
// called a problem (the deploy hook, most likely).
const GiveUpAfter = 2 * time.Hour
// Address is the page's address on the live site.
func (p *SitePage) Address() string {
return strings.TrimRight(p.Site, "/") + p.Path
}
// Waiting says whether the live site hasn't caught up with the page yet:
// merged but not seen live, or removed but not seen gone.
func (p *SitePage) Waiting() bool {
return (p.Status == PageMerged && p.LiveAt.IsZero()) || (p.Status == PageRemoved && p.GoneAt.IsZero())
}
// Late says whether it's been waiting too long.
func (p *SitePage) Late(now time.Time) bool {
return p.Waiting() && !p.MergedAt.IsZero() && now.Sub(p.MergedAt) > GiveUpAfter && p.Status == PageMerged
}
// RefreshPR follows a page's open pull request (adding or removing it): a
// merge or a close changes its status. It says whether anything changed.
func RefreshPR(ctx context.Context, d *db.DB, g interface {
GetPull(context.Context, string, int64) (*gitea.Pull, error)
}, p *SitePage, now time.Time) (bool, error) {
_, full, err := gitea.ParseRepo(p.Repo)
if err != nil {
return false, nil
}
switch p.Status {
case PageRemoving:
pull, err := g.GetPull(ctx, full, p.RemovalPRNumber)
if err != nil {
return false, err
}
switch {
case pull.Merged:
p.Status, p.GoneAt, p.LiveNote = PageRemoved, time.Time{}, ""
p.MergedAt = now
if pull.MergedAt != nil {
p.MergedAt = *pull.MergedAt
}
case pull.State == "closed":
p.Status, p.RemovalPRNumber, p.RemovalPRURL = PageMerged, 0, ""
default:
return false, nil
}
case PagePR:
pull, err := g.GetPull(ctx, full, p.PRNumber)
if err != nil {
return false, err
}
switch {
case pull.Merged:
p.Status, p.MergedAt, p.LiveAt, p.LiveNote = PageMerged, now, time.Time{}, ""
if pull.MergedAt != nil {
p.MergedAt = *pull.MergedAt
}
case pull.State == "closed":
p.Status = PageClosed
default:
return false, nil
}
default:
return false, nil
}
return true, SavePage(d, p)
}
// CheckLive looks at the live site for a page that's waiting: a merged
// one must answer, with its title and its own words; a removed one must
// be gone (404 or 410, or sent elsewhere). It notes what it found.
func CheckLive(ctx context.Context, f *seo.Fetcher, p *SitePage, now time.Time) {
p.CheckedAt = now
lp, err := f.Page(ctx, p.Address())
if err != nil {
p.LiveNote = "Couldn't reach the site: " + err.Error()
return
}
if p.Status == PageRemoved {
moved := false
if u, err := url.Parse(lp.Final); err == nil && strings.TrimRight(u.Path, "/") != strings.TrimRight(p.Path, "/") {
moved = true
}
switch {
case lp.Status == http.StatusNotFound || lp.Status == http.StatusGone:
p.GoneAt, p.LiveNote = now, fmt.Sprintf("Gone from the site (it answers %d).", lp.Status)
case moved:
p.GoneAt, p.LiveNote = now, "Gone from the site: its address now leads to "+lp.Final+"."
default:
p.LiveNote = fmt.Sprintf("Still on the site (it answers %d).", lp.Status)
}
return
}
if lp.Status != http.StatusOK {
p.LiveNote = fmt.Sprintf("Not on the site yet (it answers %d).", lp.Status)
return
}
titleOK := p.Title == "" || strings.Contains(norm(lp.Title), norm(p.Title))
phrase := Phrase(p.Sections)
textOK := phrase == "" || strings.Contains(norm(lp.Text), norm(phrase))
switch {
case titleOK && textOK:
p.LiveAt, p.LiveNote = now, "Live: the title and the words match."
case textOK:
p.LiveAt, p.LiveNote = now, fmt.Sprintf("Live, but its title shows as %q.", lp.Title)
case titleOK:
p.LiveNote = fmt.Sprintf("The page is there with its title, but not this version's words yet (looking for %q).", phrase)
default:
p.LiveNote = fmt.Sprintf("Something else is at this address (its title is %q).", lp.Title)
}
}
var (
mdLinkText = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
mdMarks = regexp.MustCompile("[*_`#>]+")
spaces = regexp.MustCompile(`\s+`)
)
// Phrase is words from the page that should show on the live site: the
// first heading of its first section that has one, without Markdown.
func Phrase(sectionsYAML string) string {
var doc yaml.Node
if yaml.Unmarshal([]byte(sectionsYAML), &doc) != nil || len(doc.Content) == 0 || doc.Content[0].Kind != yaml.SequenceNode {
return ""
}
for _, sec := range doc.Content[0].Content {
for _, key := range []string{"title", "headline", "text", "body"} {
if v := mapValue(sec, key); v != nil && v.Kind == yaml.ScalarNode && strings.TrimSpace(v.Value) != "" {
s := mdLinkText.ReplaceAllString(v.Value, "$1")
s = strings.TrimSpace(spaces.ReplaceAllString(mdMarks.ReplaceAllString(s, ""), " "))
if r := []rune(s); len(r) > 80 {
s = string(r[:80])
if i := strings.LastIndex(s, " "); i > 20 {
s = s[:i]
}
}
return s
}
}
}
return ""
}
func norm(s string) string {
s = html.UnescapeString(s)
s = strings.NewReplacer("’", "'", "‘", "'", "“", `"`, "”", `"`, "–", "-", "—", "-", " ", " ").Replace(s)
return strings.ToLower(strings.TrimSpace(spaces.ReplaceAllString(s, " ")))
}
// Refresh follows every page's pull request and checks the live site for
// pages waiting on it. Pages are checked at most every few minutes.
func Refresh(ctx context.Context, d *db.DB, g interface {
GetPull(context.Context, string, int64) (*gitea.Pull, error)
}, f *seo.Fetcher, now time.Time) error {
ps, err := PagesIn(d, PagePR, PageRemoving, PageMerged, PageRemoved)
if err != nil {
return err
}
for i := range ps {
p := &ps[i]
if g != nil {
if _, err := RefreshPR(ctx, d, g, p, now); err != nil {
continue
}
}
if !p.Waiting() || now.Sub(p.CheckedAt) < 4*time.Minute {
continue
}
CheckLive(ctx, f, p, now)
if err := SavePage(d, p); err != nil {
return err
}
}
return nil
}
// LiveAddresses are pages that went live, or went away, since a time: for
// telling search engines (IndexNow takes both).
func LiveAddresses(d *db.DB, site string, since time.Time) ([]string, error) {
ps, err := Pages(d, site)
if err != nil {
return nil, err
}
var out []string
for _, p := range ps {
if (!p.LiveAt.IsZero() && p.LiveAt.After(since)) || (!p.GoneAt.IsZero() && p.GoneAt.After(since)) {
out = append(out, p.Address())
}
}
return out, nil
}