package seo import ( "net/url" "strings" ) // Scope is one website's share of a Search Console property. A domain // property (sc-domain:example.com) covers every subdomain — a shop, a Gitea, // a forum — so its rows are narrowed to the website's own host, with or // without www. With no hosts it's the whole property. type Scope struct { Property string Hosts []string // lower case, without www. } // NewScope is the scope of the website at siteURL within property. Only a // domain property is narrowed, and only to a host within its domain: a // URL-prefix property is one site already. func NewScope(property, siteURL string) Scope { s := Scope{Property: property} domain, ok := strings.CutPrefix(strings.ToLower(property), "sc-domain:") u, err := url.Parse(siteURL) if !ok || err != nil { return s } host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") if host == domain || strings.HasSuffix(host, "."+domain) { s.Hosts = []string{host} } return s } // Has says whether a page's address is on the website. func (s Scope) Has(page string) bool { if len(s.Hosts) == 0 { return true } u, err := url.Parse(page) if err != nil { return false } h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") for _, want := range s.Hosts { if h == want { return true } } return false } // where is the SQL condition for the scope's rows of a gsc_ table, which // has site and page columns, and its arguments. func (s Scope) where() (string, []any) { cond := "site = ?" args := []any{s.Property} if len(s.Hosts) == 0 { return cond, args } var ors []string for _, h := range s.Hosts { h = likeEscape(h) for _, prefix := range []string{"https://", "http://", "https://www.", "http://www."} { ors = append(ors, `page LIKE ? ESCAPE '\'`, `page = ?`) args = append(args, prefix+h+"/%", prefix+h) } } return cond + " AND (" + strings.Join(ors, " OR ") + ")", args } func likeEscape(s string) string { return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s) }