package backlinks import ( "context" "errors" "fmt" "net/http" "net/url" "strings" "time" "supermarket/internal/db" "supermarket/internal/seo" ) // Whether a link is still there, as the last check found. const ( StatusUnchecked = "unchecked" StatusKept = "kept" // the page still links to the site StatusGone = "gone" // the page is there, without the link StatusPageGone = "page-gone" // the page answers 404 or 410, or moved elsewhere StatusTarget404 = "target-404" // it links to a page of ours that's gone ) // Checking politely: each link at most once a week, at most MaxPerDay // pages a day in all. const ( CheckEvery = 7 * 24 * time.Hour MaxPerDay = 100 ) // Lost says whether a link was lost (or points nowhere). func (l Link) Lost() bool { return l.Status == StatusGone || l.Status == StatusPageGone || l.Status == StatusTarget404 } // Fetcher reads a page of another site. type Fetcher interface { Page(ctx context.Context, u string) (*seo.LivePage, error) } func checkedKey(day string) string { return "backlinks:checked:" + day } // CheckDue checks a website's links that are due (never checked, or not // for a week), oldest first, within what's left of today's MaxPerDay; at // most limit of them (0: no limit but the day's). It returns how many it // checked. func CheckDue(ctx context.Context, d *db.DB, f Fetcher, siteURL string, limit int, now time.Time) (int, error) { day := now.Format(dayFormat) var done int _, _ = d.GetJSON(checkedKey(day), &done) left := MaxPerDay - done if limit > 0 && limit < left { left = limit } if left <= 0 { return 0, nil } rows, err := d.Query(`SELECT id FROM backlinks WHERE site = ? AND (checked_at IS NULL OR checked_at < ?) ORDER BY coalesce(checked_at, ''), id LIMIT ?`, siteURL, now.Add(-CheckEvery).UTC().Format(time.RFC3339), left) if err != nil { return 0, err } var ids []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { rows.Close() return 0, err } ids = append(ids, id) } rows.Close() ours := map[string]int{} // our pages' answers, once per run n := 0 for _, id := range ids { if ctx.Err() != nil { break } l, err := Get(d, id) if err != nil { return n, err } Check(ctx, f, siteURL, l, ours, now) if err := save(d, l); err != nil { return n, err } n++ } return n, d.PutJSON(checkedKey(day), done+n) } // Check opens the linking page and says whether it still links to the // site, and whether the page of ours it links to still answers. func Check(ctx context.Context, f Fetcher, siteURL string, l *Link, ours map[string]int, now time.Time) { l.CheckedAt = now own := hostOf(siteURL) lp, err := f.Page(ctx, l.Source) if err != nil { // Unreachable this time: not a verdict. Keep the last one. l.Note = "Couldn't reach the page: " + err.Error() if l.Status == "" { l.Status = StatusUnchecked } return } switch { case lp.Status == http.StatusNotFound || lp.Status == http.StatusGone: l.Status, l.Note = StatusPageGone, fmt.Sprintf("The page answers %d.", lp.Status) return case lp.Status != http.StatusOK: l.Note = fmt.Sprintf("The page answered %d; trying again next week.", lp.Status) if l.Status == "" { l.Status = StatusUnchecked } return } if moved(l.Source, lp.Final) { l.Status, l.Note = StatusPageGone, "The page now leads to "+lp.Final+"." return } found := "" for _, link := range lp.Links { if hostOf(link) == own { found = link if l.Target == "" || pathOf(link) == l.Target { break } } } if found == "" { l.Status, l.Note = StatusGone, "The page is there, but no longer links to the site." return } if l.Target == "" { l.Target = pathOf(found) } l.LastSeen = now.Format(dayFormat) // The page of ours it links to: still there? target := strings.TrimRight(siteURL, "/") + pathOf(found) status, ok := ours[target] if !ok { if tp, err := f.Page(ctx, target); err == nil { status = tp.Status } ours[target] = status } if status == http.StatusNotFound || status == http.StatusGone { l.Status, l.Note = StatusTarget404, fmt.Sprintf("It links to %s, which answers %d: a redirect to where that page went keeps the link working.", pathOf(found), status) return } l.Status, l.Note = StatusKept, "Still links to "+pathOf(found)+"." } // moved says whether a page's final address is a different page: another // site, or another path (not just http to https, www or a slash). func moved(from, to string) bool { if to == "" { return false } a, err1 := url.Parse(from) b, err2 := url.Parse(to) if err1 != nil || err2 != nil { return false } return hostOf(from) != hostOf(to) || strings.TrimRight(a.Path, "/") != strings.TrimRight(b.Path, "/") } // Get reads one link. func Get(d *db.DB, id int64) (*Link, error) { var l Link var checked string err := d.QueryRow(`SELECT id, source_url, target, anchor, origin, first_seen, last_seen, status, coalesce(checked_at, ''), note FROM backlinks WHERE id = ?`, id).Scan(&l.ID, &l.Source, &l.Target, &l.Anchor, &l.Origin, &l.FirstSeen, &l.LastSeen, &l.Status, &checked, &l.Note) if err != nil { return nil, err } l.CheckedAt, _ = time.Parse(time.RFC3339, checked) return &l, nil } func save(d *db.DB, l *Link) error { var checked any if !l.CheckedAt.IsZero() { checked = l.CheckedAt.UTC().Format(time.RFC3339) } _, err := d.Exec(`UPDATE backlinks SET target = ?, status = ?, note = ?, checked_at = ?, last_seen = max(last_seen, ?) WHERE id = ?`, l.Target, l.Status, l.Note, checked, l.LastSeen, l.ID) return err } // Add keeps a linking page the user knows of; it's checked like the rest. func Add(d *db.DB, siteURL, source, target string, now time.Time) (*Link, error) { source = strings.TrimSpace(source) u, err := url.Parse(source) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { return nil, errors.New("give the linking page's full address (https://…)") } if hostOf(source) == hostOf(siteURL) { return nil, errors.New("that's a page of your own site: give the other site's page that links to it") } if target = strings.TrimSpace(target); target != "" { target = pathOf(target) } day := now.Format(dayFormat) if err := upsert(d, siteURL, source, target, "", OriginManual, day); err != nil { return nil, err } var id int64 if err := d.QueryRow(`SELECT id FROM backlinks WHERE site = ? AND source_url = ? AND target = ?`, siteURL, strings.SplitN(source, "#", 2)[0], target).Scan(&id); err != nil { return nil, err } return Get(d, id) } // CheckOne checks one link now (after it's added by hand), whatever the // day's count. func CheckOne(ctx context.Context, d *db.DB, f Fetcher, siteURL string, l *Link, now time.Time) error { Check(ctx, f, siteURL, l, map[string]int{}, now) return save(d, l) } // Remove forgets a link. func Remove(d *db.DB, siteURL string, id int64) error { _, err := d.Exec(`DELETE FROM backlinks WHERE id = ? AND site = ?`, id, siteURL) return err }