Phase 3 part 1: Search Console and what already ranks
PLAN: Phase 3 rewritten around a weekly seven-job SEO loop (what ranks, next keywords, brief, page, approval, morning check, Monday report), with chatseo.app's ideas borrowed and rankings from Search Console only. Google OAuth (PKCE, offline, read-only webmasters scope) from Settings → Search engines, with each website's property. Search Console is synced into SQLite by day (site, page, and page+query; 16 months, then twice a day). SEO → What ranks shows the last 90 days: totals, the share of clicks from hidden queries, best pages, queries shown but not clicked, and the pages to protect and to push, each with its numbers. Schema 12. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/gsc"
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
)
|
||||
|
||||
var googleFields = []secretField{
|
||||
{"google", secrets.GoogleClientID, "OAuth client ID",
|
||||
"In Google Cloud: create a project, enable the Google Search Console API, set up the OAuth consent screen (add yourself as a test user, or publish it so the sign-in doesn't expire after 7 days), then Credentials → Create credentials → OAuth client ID → Web application, with the redirect URI below.", googleCreds},
|
||||
{"google", secrets.GoogleClientSecret, "OAuth client secret", "Shown next to the client ID.", googleCreds},
|
||||
}
|
||||
|
||||
// gscBase is the Search Console API's address; tests point it elsewhere.
|
||||
var gscBase = ""
|
||||
|
||||
// googleAuth caches the access token, which lasts an hour.
|
||||
type googleAuth struct {
|
||||
mu sync.Mutex
|
||||
token string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
var gauth googleAuth
|
||||
|
||||
func (s *Server) setGoogleToken(res *oauth.Result) {
|
||||
gauth.mu.Lock()
|
||||
defer gauth.mu.Unlock()
|
||||
gauth.token = res.AccessToken
|
||||
life := res.ExpiresIn
|
||||
if life <= 0 {
|
||||
life = time.Hour
|
||||
}
|
||||
gauth.expires = time.Now().Add(life - time.Minute)
|
||||
}
|
||||
|
||||
// googleToken returns an access token, refreshing it when it's run out.
|
||||
func (s *Server) googleToken(ctx context.Context) (string, error) {
|
||||
gauth.mu.Lock()
|
||||
tok, exp := gauth.token, gauth.expires
|
||||
gauth.mu.Unlock()
|
||||
if tok != "" && time.Now().Before(exp) {
|
||||
return tok, nil
|
||||
}
|
||||
refresh := s.Secrets.Get(secrets.GoogleRefreshToken)
|
||||
if refresh == "" {
|
||||
return "", errors.New("connect Search Console first, under Settings → Search engines")
|
||||
}
|
||||
res, err := oauth.RefreshGoogle(ctx, s.Secrets.Get(secrets.GoogleClientID), s.Secrets.Get(secrets.GoogleClientSecret), refresh)
|
||||
if err != nil {
|
||||
return "", errors.New("Google refused to renew the sign-in; connect Search Console again (" + err.Error() + ")")
|
||||
}
|
||||
s.setGoogleToken(res)
|
||||
return res.AccessToken, nil
|
||||
}
|
||||
|
||||
// gsc is a Search Console client, or nil when it isn't connected.
|
||||
func (s *Server) gsc() *gsc.Client {
|
||||
if !s.Secrets.Has(secrets.GoogleRefreshToken) {
|
||||
return nil
|
||||
}
|
||||
c := gsc.New(s.googleToken)
|
||||
if gscBase != "" {
|
||||
c.WithBase(gscBase)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// seoSite is a website and its Search Console property.
|
||||
type seoSite struct {
|
||||
Index int
|
||||
URL string
|
||||
Property string
|
||||
Last *seo.SyncResult
|
||||
}
|
||||
|
||||
func (s *Server) seoSites() []seoSite {
|
||||
p, _ := profile.Load(s.DB)
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
var out []seoSite
|
||||
for i, w := range p.Websites {
|
||||
site := seoSite{Index: i, URL: w.URL, Property: w.SearchConsoleProperty}
|
||||
if site.Property != "" {
|
||||
site.Last, _ = seo.LastSync(s.DB, site.Property)
|
||||
}
|
||||
out = append(out, site)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- Settings → Search engines ---
|
||||
|
||||
func (s *Server) searchSettingsPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderSearchSettings(w, r, "")
|
||||
}
|
||||
|
||||
func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, errMsg string) {
|
||||
data := map[string]any{
|
||||
"Fields": googleFields,
|
||||
"Set": s.secretState(secrets.GoogleClientID, secrets.GoogleClientSecret, secrets.GoogleRefreshToken),
|
||||
"Redirect": s.callbackURL("google"),
|
||||
"Sites": s.seoSites(),
|
||||
"Connected": s.Secrets.Has(secrets.GoogleRefreshToken),
|
||||
"Account": s.connections()["google"].Account,
|
||||
}
|
||||
if c := s.gsc(); c != nil {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||
props, err := c.Sites(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
data["PropsError"] = err.Error()
|
||||
}
|
||||
data["Properties"] = props
|
||||
}
|
||||
s.render(w, r, "search-engines", page{Title: "Search engines", Nav: "settings/search", Error: errMsg, Data: data})
|
||||
}
|
||||
|
||||
func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.saveSecrets(r, googleFields); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if r.PostForm.Get("remove:"+secrets.GoogleRefreshToken) == "on" {
|
||||
if err := s.Secrets.Set(map[string]string{secrets.GoogleRefreshToken: ""}); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
gauth.mu.Lock()
|
||||
gauth.token = ""
|
||||
gauth.mu.Unlock()
|
||||
}
|
||||
if props, has := r.PostForm["property"]; has {
|
||||
p, err := profile.Load(s.DB)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
for i := range p.Websites {
|
||||
if i < len(props) {
|
||||
p.Websites[i].SearchConsoleProperty = strings.TrimSpace(props[i])
|
||||
}
|
||||
}
|
||||
if err := profile.Save(s.DB, p); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
redirect(w, r, "/settings/search", "saved")
|
||||
}
|
||||
|
||||
// seoSync syncs every website's property now.
|
||||
func (s *Server) seoSync(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
|
||||
defer cancel()
|
||||
if err := s.syncSearchConsole(ctx); err != nil {
|
||||
s.renderSearchSettings(w, r, "Syncing: "+err.Error())
|
||||
return
|
||||
}
|
||||
back := r.PostFormValue("back")
|
||||
if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") {
|
||||
back = "/settings/search"
|
||||
}
|
||||
redirect(w, r, back, "synced")
|
||||
}
|
||||
|
||||
func (s *Server) syncSearchConsole(ctx context.Context) error {
|
||||
c := s.gsc()
|
||||
if c == nil {
|
||||
return errors.New("connect Search Console first")
|
||||
}
|
||||
var errs []string
|
||||
n := 0
|
||||
for _, site := range s.seoSites() {
|
||||
if site.Property == "" {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if _, err := seo.Sync(ctx, s.DB, c, site.Property, time.Now()); err != nil {
|
||||
errs = append(errs, site.Property+": "+err.Error())
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
return errors.New("choose a Search Console property for a website first")
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
return errors.New(strings.Join(errs, "; "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunSEO syncs Search Console twice a day.
|
||||
func (s *Server) RunSEO(ctx context.Context) {
|
||||
tick := time.NewTicker(30 * time.Minute)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if s.gsc() != nil {
|
||||
due := false
|
||||
for _, site := range s.seoSites() {
|
||||
if site.Property != "" && (site.Last == nil || time.Since(site.Last.At) > 12*time.Hour) {
|
||||
due = true
|
||||
}
|
||||
}
|
||||
if due {
|
||||
sctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
|
||||
if err := s.syncSearchConsole(sctx); err != nil {
|
||||
s.Log.Warn("seo: Search Console sync", "err", err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- The SEO page ---
|
||||
|
||||
func (s *Server) seoPage(w http.ResponseWriter, r *http.Request) {
|
||||
sites := s.seoSites()
|
||||
var mapped []seoSite
|
||||
for _, st := range sites {
|
||||
if st.Property != "" {
|
||||
mapped = append(mapped, st)
|
||||
}
|
||||
}
|
||||
var cur *seoSite
|
||||
if i, err := strconv.Atoi(r.URL.Query().Get("site")); err == nil {
|
||||
for j := range mapped {
|
||||
if mapped[j].Index == i {
|
||||
cur = &mapped[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
if cur == nil && len(mapped) > 0 {
|
||||
cur = &mapped[0]
|
||||
}
|
||||
data := map[string]any{
|
||||
"Connected": s.Secrets.Has(secrets.GoogleRefreshToken),
|
||||
"Sites": mapped,
|
||||
"Current": cur,
|
||||
"Days": seo.RanksDays,
|
||||
}
|
||||
if cur != nil {
|
||||
ranks, err := seo.WhatRanks(s.DB, cur.Property)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
data["Ranks"] = ranks
|
||||
}
|
||||
s.render(w, r, "seo", page{Title: "SEO", Nav: "seo/ranks", Data: data})
|
||||
}
|
||||
|
||||
// pagePath shows a page's address without the site, for tables.
|
||||
func pagePath(u string) string {
|
||||
p, err := url.Parse(u)
|
||||
if err != nil || p.Path == "" {
|
||||
return u
|
||||
}
|
||||
if p.RawQuery != "" {
|
||||
return p.Path + "?" + p.RawQuery
|
||||
}
|
||||
return p.Path
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/profile"
|
||||
"supermarket/internal/secrets"
|
||||
)
|
||||
|
||||
func TestSearchConsole(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/token":
|
||||
r.ParseForm()
|
||||
if r.PostForm.Get("client_secret") != "sec" || (r.PostForm.Get("code") != "c0de" && r.PostForm.Get("grant_type") != "refresh_token") {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"access_token": "tok", "refresh_token": "ref", "expires_in": 3600})
|
||||
case r.URL.Path == "/userinfo":
|
||||
json.NewEncoder(w).Encode(map[string]any{"email": "me@example.com"})
|
||||
case r.URL.Path == "/sites":
|
||||
json.NewEncoder(w).Encode(map[string]any{"siteEntry": []any{map[string]any{"siteUrl": "sc-domain:us.example", "permissionLevel": "siteOwner"}}})
|
||||
case strings.HasSuffix(r.URL.Path, "/searchAnalytics/query"):
|
||||
var q struct {
|
||||
StartDate string `json:"startDate"`
|
||||
Dimensions []string `json:"dimensions"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&q)
|
||||
var rows []any
|
||||
if q.StartDate <= "2026-11-10" && q.StartDate >= "2026-10-20" {
|
||||
day := "2026-11-10"
|
||||
switch strings.Join(q.Dimensions, ",") {
|
||||
case "date":
|
||||
rows = append(rows, map[string]any{"keys": []string{day}, "clicks": 63, "impressions": 4200, "position": 9})
|
||||
case "date,page":
|
||||
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/"}, "clicks": 0, "impressions": 4000, "position": 6.5},
|
||||
map[string]any{"keys": []string{day, "https://us.example/"}, "clicks": 63, "impressions": 200, "position": 1.2})
|
||||
case "date,page,query":
|
||||
rows = append(rows, map[string]any{"keys": []string{day, "https://us.example/pricing/", "nextcloud hosting price"}, "clicks": 0, "impressions": 3000, "position": 6})
|
||||
}
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"rows": rows})
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
oauth.SetGoogleURLs(srv.URL+"/auth", srv.URL+"/token", srv.URL+"/userinfo")
|
||||
gscBase = srv.URL
|
||||
defer func() {
|
||||
oauth.SetGoogleURLs("https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://openidconnect.googleapis.com/v1/userinfo")
|
||||
gscBase = ""
|
||||
gauth.token = ""
|
||||
}()
|
||||
|
||||
s, h := newTestServer(t, nil)
|
||||
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example"}}})
|
||||
if body := do(h, http.MethodGet, "/seo", nil, nil).Body.String(); !strings.Contains(body, "Connect Google Search Console") {
|
||||
t.Error("the SEO page doesn't say to connect")
|
||||
}
|
||||
postForm(h, "/settings/search", url.Values{secrets.GoogleClientID: {"cid"}, secrets.GoogleClientSecret: {"sec"}})
|
||||
body := do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "/auth/google/callback") || !strings.Contains(body, "Connect Search Console") {
|
||||
t.Fatal("no redirect URI or Connect button")
|
||||
}
|
||||
|
||||
rec := postForm(h, "/auth/google/start", nil)
|
||||
loc, _ := url.Parse(rec.Header().Get("Location"))
|
||||
q := loc.Query()
|
||||
if !strings.HasPrefix(loc.String(), srv.URL+"/auth") || q.Get("access_type") != "offline" || !strings.Contains(q.Get("scope"), "webmasters.readonly") || q.Get("code_challenge") == "" {
|
||||
t.Fatalf("start: %s", loc)
|
||||
}
|
||||
rec = do(h, http.MethodGet, "/auth/google/callback?state="+url.QueryEscape(q.Get("state"))+"&code=c0de", nil, nil)
|
||||
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/settings/search?msg=google-connected") {
|
||||
t.Fatalf("callback: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body)
|
||||
}
|
||||
if s.Secrets.Get(secrets.GoogleRefreshToken) != "ref" {
|
||||
t.Error("the refresh token wasn't saved")
|
||||
}
|
||||
body = do(h, http.MethodGet, "/settings/search", nil, nil).Body.String()
|
||||
if !strings.Contains(body, "Connected as me@example.com") || !strings.Contains(body, `<option value="sc-domain:us.example"`) {
|
||||
t.Fatalf("connected page: %s", body)
|
||||
}
|
||||
postForm(h, "/settings/search", url.Values{"property": {"sc-domain:us.example"}})
|
||||
if p, _ := profile.Load(s.DB); p.Websites[0].SearchConsoleProperty != "sc-domain:us.example" {
|
||||
t.Errorf("property: %+v", p.Websites)
|
||||
}
|
||||
if rec := postForm(h, "/settings/search/sync", url.Values{"back": {"/seo?site=0"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("sync: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
body = do(h, http.MethodGet, "/seo", nil, nil).Body.String()
|
||||
for _, want := range []string{"4,200", "/pricing/", "Shown 4,000 times at position 6.5, 0 clicks. 75% of its impressions come from “nextcloud hosting price”",
|
||||
"nextcloud hosting price", "100.0% of the clicks come from searches Google doesn't name"} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("SEO page lacks %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-4
@@ -23,6 +23,7 @@ import (
|
||||
"supermarket/internal/oauth"
|
||||
"supermarket/internal/prospects"
|
||||
"supermarket/internal/secrets"
|
||||
"supermarket/internal/seo"
|
||||
"supermarket/internal/signals"
|
||||
)
|
||||
|
||||
@@ -158,6 +159,10 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("POST /settings/email", s.emailSave)
|
||||
mux.HandleFunc("POST /settings/email/test", s.emailTest)
|
||||
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
|
||||
mux.HandleFunc("GET /seo", s.seoPage)
|
||||
mux.HandleFunc("GET /settings/search", s.searchSettingsPage)
|
||||
mux.HandleFunc("POST /settings/search", s.searchSettingsSave)
|
||||
mux.HandleFunc("POST /settings/search/sync", s.seoSync)
|
||||
mux.HandleFunc("GET /settings/tracking", s.trackingPage)
|
||||
mux.HandleFunc("POST /settings/tracking", s.trackingSave)
|
||||
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
|
||||
@@ -276,9 +281,12 @@ func (s *Server) loadTemplates() error {
|
||||
},
|
||||
"xreserve": twitter.URLReserve,
|
||||
// money shows cents as dollars: $1,234 or $12.50.
|
||||
"money": money,
|
||||
"stage": signals.StageLabel,
|
||||
"channel": signals.ChannelLabel,
|
||||
"money": money,
|
||||
"num": seo.Thousands,
|
||||
"dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) },
|
||||
"pagePath": pagePath,
|
||||
"stage": signals.StageLabel,
|
||||
"channel": signals.ChannelLabel,
|
||||
"truncate": func(n int, s string) string {
|
||||
r := []rune(s)
|
||||
if len(r) <= n {
|
||||
@@ -347,7 +355,7 @@ type module struct {
|
||||
var modules = []module{
|
||||
{"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/content"},
|
||||
{"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"},
|
||||
{"seo", "SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories.", ""},
|
||||
{"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo"},
|
||||
{"metrics", "Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible.", ""},
|
||||
{"sites", "Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea.", ""},
|
||||
}
|
||||
@@ -395,6 +403,8 @@ var flashes = map[string]string{
|
||||
"deleted": "Deleted.",
|
||||
"x-connected": "X is connected.",
|
||||
"li-connected": "LinkedIn is connected.",
|
||||
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
|
||||
"synced": "Synced from Search Console.",
|
||||
"reddit-connected": "Reddit is connected.",
|
||||
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
|
||||
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
|
||||
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
|
||||
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
|
||||
"/content/scheduled", "/content/published",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking",
|
||||
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo",
|
||||
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
|
||||
rec := do(h, http.MethodGet, path, nil, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
@@ -358,6 +358,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
authURL, p, err = oauth.RedditStart(id, s.callbackURL("reddit"))
|
||||
case "google":
|
||||
id := s.Secrets.Get(secrets.GoogleClientID)
|
||||
if id == "" || !s.Secrets.Has(secrets.GoogleClientSecret) {
|
||||
http.Error(w, "Save Google's client ID and secret first.", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
authURL, p, err = oauth.GoogleStart(id, s.callbackURL("google"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
@@ -386,15 +393,19 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
p := s.pending[q.Get("state")]
|
||||
delete(s.pending, q.Get("state")) // a state is good for one callback
|
||||
s.mu.Unlock()
|
||||
back, nav := "/settings/accounts", "settings/accounts"
|
||||
if provider == "google" {
|
||||
back, nav = "/settings/search", "settings/search"
|
||||
}
|
||||
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
|
||||
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
|
||||
redirect(w, r, "/settings/accounts", "oauth-expired")
|
||||
redirect(w, r, back, "oauth-expired")
|
||||
return
|
||||
}
|
||||
fail := func(msg string) {
|
||||
s.Log.Warn("oauth: sign-in failed", "provider", provider, "reason", msg)
|
||||
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: "settings/accounts", Error: msg,
|
||||
Data: map[string]string{"Back": "/settings/accounts"}})
|
||||
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: nav, Error: msg,
|
||||
Data: map[string]string{"Back": back}})
|
||||
}
|
||||
if e := q.Get("error"); e != "" {
|
||||
// Some providers (LinkedIn) send the description HTML-escaped;
|
||||
@@ -411,6 +422,29 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
switch provider {
|
||||
case "google":
|
||||
res, err := oauth.GoogleExchange(ctx, s.Secrets.Get(secrets.GoogleClientID), s.Secrets.Get(secrets.GoogleClientSecret), code, p)
|
||||
if err != nil {
|
||||
fail(err.Error())
|
||||
return
|
||||
}
|
||||
if res.RefreshToken == "" {
|
||||
fail("Google sent no refresh token, so Supermarket couldn't read Search Console on its own. Remove Supermarket's access in your Google account's security settings, then connect again.")
|
||||
return
|
||||
}
|
||||
email, err := oauth.GoogleEmail(ctx, res.AccessToken)
|
||||
if err != nil {
|
||||
s.Log.Warn("google: couldn't read the account's email", "err", err)
|
||||
}
|
||||
if err := s.Secrets.Set(map[string]string{secrets.GoogleRefreshToken: res.RefreshToken}); err != nil {
|
||||
fail("Signed in, but couldn't save the token: " + err.Error())
|
||||
return
|
||||
}
|
||||
s.setGoogleToken(res)
|
||||
if err := s.saveConnection("google", Connection{Account: email, At: time.Now()}); err != nil {
|
||||
s.Log.Error("saving connection", "err", err)
|
||||
}
|
||||
redirect(w, r, "/settings/search", "google-connected")
|
||||
case "x":
|
||||
res, err := oauth.XExchange(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), code, p)
|
||||
if err != nil {
|
||||
|
||||
@@ -38,6 +38,11 @@
|
||||
<a href="/content/published" {{if eq $nav "content/published"}}aria-current="page"{{end}}>Published</a>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq .ID "seo"}}
|
||||
<div class="subnav">
|
||||
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
|
||||
</div>
|
||||
{{end}}
|
||||
{{if eq .ID "prospects"}}
|
||||
<div class="subnav">
|
||||
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
|
||||
@@ -95,6 +100,7 @@
|
||||
<a href="/settings/sources" {{if eq .Nav "settings/sources"}}aria-current="page"{{end}}>{{template "icon" "prospects"}}Lead sources</a>
|
||||
<a href="/settings/email" {{if eq .Nav "settings/email"}}aria-current="page"{{end}}>{{template "icon" "email"}}Email</a>
|
||||
<a href="/settings/tracking" {{if eq .Nav "settings/tracking"}}aria-current="page"{{end}}>{{template "icon" "metrics"}}Website & sales</a>
|
||||
<a href="/settings/search" {{if eq .Nav "settings/search"}}aria-current="page"{{end}}>{{template "icon" "seo"}}Search engines</a>
|
||||
<div class="nav-label">AI</div>
|
||||
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
|
||||
<h2>Search engines</h2>
|
||||
<p class="lede">Google Search Console is where Google says what it really shows for your sites: every number in SEO comes from it. Supermarket reads it (read-only) twice a day and keeps 16 months of it.</p>
|
||||
|
||||
<form method="post" action="/settings/search" autocomplete="off">
|
||||
<section class="card" id="google">
|
||||
<h3>Google Search Console</h3>
|
||||
{{range .Fields}}{{template "key-field" (dict "F" . "Set" (index $d.Set .Name))}}{{end}}
|
||||
<p class="help">Redirect URI to register on the OAuth client: <code id="google-redirect">{{.Redirect}}</code> <button type="button" class="link small" data-copy="google-redirect">Copy</button></p>
|
||||
{{if .Connected}}
|
||||
<p class="ok">Connected{{with .Account}} as {{.}}{{end}}.</p>
|
||||
<label class="check small"><input type="checkbox" name="remove:google.refresh_token"> disconnect</label>
|
||||
{{end}}
|
||||
</section>
|
||||
|
||||
{{if .Connected}}
|
||||
<section class="card">
|
||||
<h3>Your websites' properties</h3>
|
||||
{{with .PropsError}}<p class="error">Couldn't list your properties: {{.}}</p>{{end}}
|
||||
{{if .Sites}}
|
||||
{{range .Sites}}
|
||||
<label>{{.URL}}
|
||||
<select name="property">
|
||||
<option value="">none</option>
|
||||
{{$cur := .Property}}{{range $d.Properties}}<option value="{{.URL}}" {{if eq .URL $cur}}selected{{end}}>{{.URL}}</option>{{end}}
|
||||
{{if and $cur (not $d.Properties)}}<option value="{{$cur}}" selected>{{$cur}}</option>{{end}}
|
||||
</select>
|
||||
{{with .Last}}<span class="help {{if .Error}}error-text{{end}}">Synced {{ago .At}}{{if .Error}}: {{.Error}}{{else}}; data through {{.Through}}{{end}}.</span>{{end}}
|
||||
</label>
|
||||
{{end}}
|
||||
{{else}}<p class="help">Add your websites to the <a href="/settings/profile">profile</a> first.</p>{{end}}
|
||||
{{if not .Properties}}<p class="help">This account sees no verified properties. Add your site in Search Console, or sign in with the account that owns it.</p>{{end}}
|
||||
</section>
|
||||
{{end}}
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit">Save</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="actions">
|
||||
{{if and (index .Set "google.client_id") (index .Set "google.client_secret")}}
|
||||
<form method="post" action="/auth/google/start"><button type="submit" class="{{if .Connected}}secondary{{end}}">{{if .Connected}}Connect again{{else}}Connect Search Console{{end}}</button></form>
|
||||
{{end}}
|
||||
{{if .Connected}}<form method="post" action="/settings/search/sync" data-busy="Syncing…"><button type="submit" class="secondary">Sync now</button></form>{{end}}
|
||||
</div>
|
||||
{{end}}{{template "settings-end"}}{{end}}
|
||||
@@ -0,0 +1,62 @@
|
||||
{{define "content"}}{{with .Data}}{{$d := .}}
|
||||
<div class="heading">
|
||||
<h1>What already ranks</h1>
|
||||
{{if .Current}}<div class="buttons">
|
||||
<form method="post" action="/settings/search/sync" data-busy="Syncing…"><input type="hidden" name="back" value="/seo?site={{.Current.Index}}"><button type="submit" class="secondary">Sync now</button></form>
|
||||
</div>{{end}}
|
||||
</div>
|
||||
<p class="lede">The cheapest traffic is on pages that already rank. From Search Console, the last {{.Days}} days: the pages that carry your clicks, which to protect, and which to push because Google already shows them and nobody clicks.</p>
|
||||
|
||||
{{if not .Connected}}
|
||||
<section class="card empty"><p>Connect Google Search Console under <a href="/settings/search">Settings → Search engines</a> first.</p></section>
|
||||
{{else if not .Sites}}
|
||||
<section class="card empty"><p>Choose the Search Console property for your website under <a href="/settings/search">Settings → Search engines</a>.</p></section>
|
||||
{{else}}
|
||||
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/seo?site={{.Index}}" {{if eq .Index $d.Current.Index}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
|
||||
|
||||
{{with .Ranks}}
|
||||
<section class="card">
|
||||
<p class="small muted">{{.Site}} · {{.From}} to {{.To}} (Search Console's final data is 2 to 3 days behind).</p>
|
||||
<div class="funnel">
|
||||
<div class="step"><span class="label">Clicks</span><strong>{{num .Total.Clicks}}</strong></div>
|
||||
<div class="step"><span class="label">Impressions</span><strong>{{num .Total.Impressions}}</strong></div>
|
||||
<div class="step"><span class="label">Click rate</span><strong>{{dec1 .Total.CTR}}%</strong></div>
|
||||
<div class="step"><span class="label">Average position</span><strong>{{dec1 .Total.Position}}</strong></div>
|
||||
</div>
|
||||
{{if ge .Anonymous 0.0}}<p class="small">{{dec1 .Anonymous}}% of the clicks come from searches Google doesn't name, so the query tables below read low; the page tables don't.</p>{{end}}
|
||||
</section>
|
||||
|
||||
<div class="grid">
|
||||
<section class="card">
|
||||
<h2>Protect</h2>
|
||||
<p class="help">They carry the clicks: don't rewrite them for fun, don't change their address, look at them first.</p>
|
||||
{{range .Protect}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>{{else}}<p class="help">No page has clicks yet.</p>{{end}}
|
||||
</section>
|
||||
<section class="card">
|
||||
<h2>Push</h2>
|
||||
<p class="help">On page one, shown a lot, hardly clicked: Google did the hard part, and the page loses at the click. Compare its main query with its title first.</p>
|
||||
{{range .Push}}<p><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a><br><span class="small">{{.Why}}</span></p>{{else}}<p class="help">No page sits on page one with few clicks. Good, or too little data.</p>{{end}}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<h2>Best pages</h2>
|
||||
{{if .Pages}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Page</th><th class="num">Clicks</th><th class="num">Impressions</th><th class="num">Click rate</th><th class="num">Position</th></tr></thead>
|
||||
<tbody>{{range .Pages}}<tr><td><a href="{{.Page}}" target="_blank" rel="noopener noreferrer">{{pagePath .Page}}</a></td><td class="num">{{num .Clicks}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{dec1 .CTR}}%</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{else}}<p class="help">No pages with data yet.</p>{{end}}
|
||||
|
||||
<h2>Shown a lot, hardly clicked</h2>
|
||||
<p class="help">The searches Google shows you for most, with a click rate under 1%.</p>
|
||||
{{if .Unclicked}}
|
||||
<table class="list">
|
||||
<thead><tr><th>Query</th><th class="num">Impressions</th><th class="num">Clicks</th><th class="num">Position</th></tr></thead>
|
||||
<tbody>{{range .Unclicked}}<tr><td>{{.Query}}</td><td class="num">{{num .Impressions}}</td><td class="num">{{num .Clicks}}</td><td class="num">{{dec1 .Position}}</td></tr>{{end}}</tbody>
|
||||
</table>
|
||||
{{else}}<p class="help">None.</p>{{end}}
|
||||
{{else}}
|
||||
<section class="card empty"><p>No data yet for {{.Current.Property}}. {{with .Current.Last}}{{if .Error}}The last sync failed: {{.Error}}{{else}}Synced {{ago .At}}, with nothing back.{{end}}{{else}}Sync now to read it.{{end}}</p></section>
|
||||
{{end}}
|
||||
{{end}}
|
||||
{{end}}{{end}}
|
||||
Reference in New Issue
Block a user