On the entry form, "Fill in the empty boxes" reads their website. Links, social accounts and feeds come straight from the pages (no guessing); the AI drafts the name if missing, a description, keywords, hashtags, and talking points set against the company profile for the relationship chosen. Typed values stay, nothing is saved until Save, and the form says which boxes were filled. Website reading moves from the profile draft into internal/site, shared by both, and now also collects links and declared RSS/Atom feeds (comment feeds skipped; Fill takes up to three). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
269 lines
8.6 KiB
Go
269 lines
8.6 KiB
Go
// Package site reads a company's website for the AI to draft from: the home
|
|
// page and a few pages it links to, reduced to text, plus the links found on
|
|
// them (social accounts, feeds), which are read directly rather than guessed
|
|
// by the model.
|
|
package site
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"html"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Page is one page read.
|
|
type Page struct {
|
|
URL string
|
|
Text string // title, meta description and visible text
|
|
}
|
|
|
|
// Site is what Read found.
|
|
type Site struct {
|
|
Pages []Page
|
|
Links []string // every link on the pages, absolute, de-duplicated, in page order
|
|
Feeds []string // RSS and Atom feeds the pages declare
|
|
}
|
|
|
|
const (
|
|
maxPageBytes = 2 << 20
|
|
maxPageText = 12000 // characters of text kept per page
|
|
maxPages = 4
|
|
)
|
|
|
|
// Pages beyond the home page worth reading, by the words in their paths.
|
|
var usefulLink = regexp.MustCompile(`(?i)about|product|pricing|features|solutions|customers|services|platform|integrations|partners`)
|
|
|
|
var (
|
|
hrefRe = regexp.MustCompile(`(?i)<a\s[^>]*href\s*=\s*["']([^"']+)["']`)
|
|
linkRe = regexp.MustCompile(`(?i)<link\s[^>]*>`)
|
|
attrRe = regexp.MustCompile(`(?i)([a-z-]+)\s*=\s*["']([^"']*)["']`)
|
|
dropRe = regexp.MustCompile(`(?is)<(script|style|noscript|svg|template)\b.*?</(script|style|noscript|svg|template)>`)
|
|
tagRe = regexp.MustCompile(`(?s)<[^>]+>`)
|
|
metaRe = regexp.MustCompile(`(?is)<meta\s[^>]*name\s*=\s*["']description["'][^>]*content\s*=\s*["']([^"']*)["']`)
|
|
titlRe = regexp.MustCompile(`(?is)<title[^>]*>(.*?)</title>`)
|
|
blockRe = regexp.MustCompile(`(?i)<(br|/p|/div|/h[1-6]|/li|/tr|/section|/header|/footer)\b[^>]*>`)
|
|
wsRe = regexp.MustCompile(`[ \t\f\r]+`)
|
|
nlRe = regexp.MustCompile(`\n\s*\n+`)
|
|
)
|
|
|
|
// Normalize makes a typed address into a URL, adding https:// if missing.
|
|
func Normalize(siteURL string) (*url.URL, error) {
|
|
siteURL = strings.TrimSpace(siteURL)
|
|
if !strings.Contains(siteURL, "://") {
|
|
siteURL = "https://" + siteURL
|
|
}
|
|
u, err := url.Parse(siteURL)
|
|
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
return nil, fmt.Errorf("%q isn't a website address", siteURL)
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
// Read reads the home page at siteURL and up to a few pages it links to on
|
|
// the same host. userAgent says who's reading.
|
|
func Read(ctx context.Context, siteURL, userAgent string) (*Site, error) {
|
|
base, err := Normalize(siteURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
client := &http.Client{Timeout: 20 * time.Second}
|
|
|
|
home, homeHTML, err := fetchPage(ctx, client, base.String(), userAgent)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s := &Site{Pages: []Page{home}}
|
|
links, feeds := &ordered{}, &ordered{}
|
|
finalBase, _ := url.Parse(home.URL)
|
|
collect(finalBase, homeHTML, links, feeds)
|
|
|
|
seen := map[string]bool{home.URL: true, base.String(): true}
|
|
for _, m := range hrefRe.FindAllStringSubmatch(homeHTML, -1) {
|
|
if len(s.Pages) >= maxPages {
|
|
break
|
|
}
|
|
u := resolve(finalBase, m[1])
|
|
if u == nil {
|
|
continue
|
|
}
|
|
u.Fragment, u.RawQuery = "", ""
|
|
if u.Host != finalBase.Host || seen[u.String()] || !usefulLink.MatchString(u.Path) {
|
|
continue
|
|
}
|
|
seen[u.String()] = true
|
|
if pg, src, err := fetchPage(ctx, client, u.String(), userAgent); err == nil {
|
|
s.Pages = append(s.Pages, pg)
|
|
collect(u, src, links, feeds)
|
|
}
|
|
}
|
|
s.Links, s.Feeds = links.list, feeds.list
|
|
return s, nil
|
|
}
|
|
|
|
func resolve(base *url.URL, href string) *url.URL {
|
|
ref, err := url.Parse(strings.TrimSpace(html.UnescapeString(href)))
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
u := base.ResolveReference(ref)
|
|
if u.Scheme != "http" && u.Scheme != "https" {
|
|
return nil
|
|
}
|
|
return u
|
|
}
|
|
|
|
// collect adds a page's links and declared feeds.
|
|
func collect(base *url.URL, src string, links, feeds *ordered) {
|
|
for _, m := range hrefRe.FindAllStringSubmatch(src, -1) {
|
|
if u := resolve(base, m[1]); u != nil {
|
|
u.Fragment = ""
|
|
links.add(u.String())
|
|
}
|
|
}
|
|
for _, tag := range linkRe.FindAllString(src, -1) {
|
|
attrs := map[string]string{}
|
|
for _, a := range attrRe.FindAllStringSubmatch(tag, -1) {
|
|
attrs[strings.ToLower(a[1])] = a[2]
|
|
}
|
|
typ := strings.ToLower(attrs["type"])
|
|
if !strings.Contains(strings.ToLower(attrs["rel"]), "alternate") ||
|
|
(typ != "application/rss+xml" && typ != "application/atom+xml") {
|
|
continue
|
|
}
|
|
// Comment feeds are talk about the posts, not news.
|
|
title := strings.ToLower(attrs["title"])
|
|
if u := resolve(base, attrs["href"]); u != nil && !strings.Contains(strings.ToLower(u.Path), "comments") &&
|
|
!strings.Contains(title, "comments") {
|
|
feeds.add(u.String())
|
|
}
|
|
}
|
|
}
|
|
|
|
// ordered is a list without repeats, in the order first added.
|
|
type ordered struct {
|
|
list []string
|
|
seen map[string]bool
|
|
}
|
|
|
|
func (o *ordered) add(s string) {
|
|
if o.seen == nil {
|
|
o.seen = map[string]bool{}
|
|
}
|
|
if !o.seen[s] {
|
|
o.seen[s] = true
|
|
o.list = append(o.list, s)
|
|
}
|
|
}
|
|
|
|
func fetchPage(ctx context.Context, client *http.Client, u, userAgent string) (Page, string, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
|
if err != nil {
|
|
return Page{}, "", err
|
|
}
|
|
req.Header.Set("User-Agent", userAgent)
|
|
req.Header.Set("Accept", "text/html")
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return Page{}, "", fmt.Errorf("can't read %s: %w", u, err)
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != http.StatusOK {
|
|
return Page{}, "", fmt.Errorf("%s answered %s", u, res.Status)
|
|
}
|
|
if ct := res.Header.Get("Content-Type"); ct != "" && !strings.Contains(ct, "html") {
|
|
return Page{}, "", errors.New(u + " isn't a web page")
|
|
}
|
|
raw, err := io.ReadAll(io.LimitReader(res.Body, maxPageBytes))
|
|
if err != nil {
|
|
return Page{}, "", err
|
|
}
|
|
src := string(raw)
|
|
return Page{URL: res.Request.URL.String(), Text: pageText(src)}, src, nil
|
|
}
|
|
|
|
// pageText reduces HTML to its title, meta description and visible text.
|
|
func pageText(src string) string {
|
|
var parts []string
|
|
if m := titlRe.FindStringSubmatch(src); m != nil {
|
|
parts = append(parts, "Title: "+clean(m[1]))
|
|
}
|
|
if m := metaRe.FindStringSubmatch(src); m != nil {
|
|
parts = append(parts, "Description: "+clean(m[1]))
|
|
}
|
|
body := dropRe.ReplaceAllString(src, " ")
|
|
body = blockRe.ReplaceAllString(body, "\n")
|
|
body = tagRe.ReplaceAllString(body, " ")
|
|
body = html.UnescapeString(body)
|
|
body = wsRe.ReplaceAllString(body, " ")
|
|
body = nlRe.ReplaceAllString(body, "\n")
|
|
parts = append(parts, strings.TrimSpace(body))
|
|
text := strings.Join(parts, "\n")
|
|
if r := []rune(text); len(r) > maxPageText {
|
|
text = string(r[:maxPageText])
|
|
}
|
|
return text
|
|
}
|
|
|
|
func clean(s string) string {
|
|
return strings.TrimSpace(wsRe.ReplaceAllString(html.UnescapeString(tagRe.ReplaceAllString(s, " ")), " "))
|
|
}
|
|
|
|
// PromptText is the pages as the prompts quote them, each marked as data.
|
|
func (s *Site) PromptText() string {
|
|
var b strings.Builder
|
|
for _, pg := range s.Pages {
|
|
fmt.Fprintf(&b, "<page url=%q>\n%s\n</page>\n\n", pg.URL, pg.Text)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// Accounts are the social accounts a site links to.
|
|
type Accounts struct {
|
|
X, LinkedIn, YouTubeChannel, Instagram string
|
|
Subreddits []string
|
|
}
|
|
|
|
var (
|
|
xRe = regexp.MustCompile(`(?i)^https?://(?:www\.|mobile\.)?(?:twitter|x)\.com/([A-Za-z0-9_]{1,15})/?$`)
|
|
linkedinRe = regexp.MustCompile(`(?i)^https?://(?:[a-z]{2,3}\.)?linkedin\.com/(company|school|showcase)/([^/?#]+)/?`)
|
|
youtubeRe = regexp.MustCompile(`(?i)^https?://(?:www\.)?youtube\.com/channel/(UC[A-Za-z0-9_-]{22})`)
|
|
instaRe = regexp.MustCompile(`(?i)^https?://(?:www\.)?instagram\.com/([A-Za-z0-9_.]{1,30})/?$`)
|
|
redditRe = regexp.MustCompile(`(?i)^https?://(?:www\.|old\.)?reddit\.com/r/([A-Za-z0-9_]{2,21})/?$`)
|
|
)
|
|
|
|
// Not accounts, though they look like them.
|
|
var notHandles = map[string]bool{"share": true, "intent": true, "home": true, "search": true, "hashtag": true,
|
|
"i": true, "explore": true, "p": true, "reel": true, "accounts": true}
|
|
|
|
// FindAccounts picks social accounts out of the links. The first link of each
|
|
// kind wins, as a site's own account is usually linked before others.
|
|
func FindAccounts(links []string) Accounts {
|
|
var a Accounts
|
|
seenSub := map[string]bool{}
|
|
for _, l := range links {
|
|
if m := xRe.FindStringSubmatch(l); m != nil && a.X == "" && !notHandles[strings.ToLower(m[1])] {
|
|
a.X = m[1]
|
|
}
|
|
if m := linkedinRe.FindStringSubmatch(l); m != nil && a.LinkedIn == "" {
|
|
a.LinkedIn = "https://www.linkedin.com/" + strings.ToLower(m[1]) + "/" + m[2]
|
|
}
|
|
if m := youtubeRe.FindStringSubmatch(l); m != nil && a.YouTubeChannel == "" {
|
|
a.YouTubeChannel = m[1]
|
|
}
|
|
if m := instaRe.FindStringSubmatch(l); m != nil && a.Instagram == "" && !notHandles[strings.ToLower(m[1])] {
|
|
a.Instagram = m[1]
|
|
}
|
|
if m := redditRe.FindStringSubmatch(l); m != nil && !seenSub[strings.ToLower(m[1])] {
|
|
seenSub[strings.ToLower(m[1])] = true
|
|
a.Subreddits = append(a.Subreddits, m[1])
|
|
}
|
|
}
|
|
return a
|
|
}
|