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>
157 lines
4.1 KiB
Go
157 lines
4.1 KiB
Go
// Package gsc reads Google Search Console (the Search Console API v3,
|
|
// https://developers.google.com/webmaster-tools/v1/api_reference_index):
|
|
// the properties the signed-in account can see, and their search
|
|
// analytics. It only reads.
|
|
package gsc
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const apiBase = "https://www.googleapis.com/webmasters/v3"
|
|
|
|
// ErrUnauthorized means Google refused the token: sign in again.
|
|
var ErrUnauthorized = errors.New("Google refused the sign-in: connect Search Console again")
|
|
|
|
// TokenFunc returns a current access token.
|
|
type TokenFunc func(ctx context.Context) (string, error)
|
|
|
|
// Client calls the API with tokens from a TokenFunc.
|
|
type Client struct {
|
|
token TokenFunc
|
|
base string
|
|
http *http.Client
|
|
}
|
|
|
|
func New(token TokenFunc) *Client {
|
|
return &Client{token: token, base: apiBase, http: &http.Client{Timeout: 2 * time.Minute}}
|
|
}
|
|
|
|
// WithBase points the client at another server (for tests).
|
|
func (c *Client) WithBase(u string) *Client {
|
|
c.base = strings.TrimRight(u, "/")
|
|
return c
|
|
}
|
|
|
|
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
|
|
tok, err := c.token(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var rd io.Reader
|
|
if body != nil {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
rd = bytes.NewReader(raw)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, c.base+path, rd)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
res, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(res.Body, 64<<20))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if res.StatusCode == http.StatusUnauthorized {
|
|
return ErrUnauthorized
|
|
}
|
|
if res.StatusCode != http.StatusOK {
|
|
var e struct {
|
|
Error struct {
|
|
Message string `json:"message"`
|
|
} `json:"error"`
|
|
}
|
|
if json.Unmarshal(raw, &e) == nil && e.Error.Message != "" {
|
|
return fmt.Errorf("Search Console: %s", e.Error.Message)
|
|
}
|
|
return fmt.Errorf("Search Console: HTTP %d", res.StatusCode)
|
|
}
|
|
return json.Unmarshal(raw, out)
|
|
}
|
|
|
|
// Site is a property the account can read.
|
|
type Site struct {
|
|
URL string `json:"siteUrl"` // "sc-domain:example.com" or "https://example.com/"
|
|
Permission string `json:"permissionLevel"`
|
|
}
|
|
|
|
// Sites lists the properties the account can see.
|
|
func (c *Client) Sites(ctx context.Context) ([]Site, error) {
|
|
var out struct {
|
|
Entries []Site `json:"siteEntry"`
|
|
}
|
|
if err := c.do(ctx, http.MethodGet, "/sites", nil, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
var usable []Site
|
|
for _, s := range out.Entries {
|
|
if s.Permission != "siteUnverifiedUser" {
|
|
usable = append(usable, s)
|
|
}
|
|
}
|
|
return usable, nil
|
|
}
|
|
|
|
// Query is a Search Analytics query.
|
|
type Query struct {
|
|
StartDate string `json:"startDate"` // YYYY-MM-DD
|
|
EndDate string `json:"endDate"`
|
|
Dimensions []string `json:"dimensions,omitempty"` // date, page, query, country, device
|
|
Type string `json:"type,omitempty"` // web (default)
|
|
RowLimit int `json:"rowLimit,omitempty"` // up to 25000
|
|
StartRow int `json:"startRow,omitempty"`
|
|
DataState string `json:"dataState,omitempty"` // final (default) or all
|
|
}
|
|
|
|
// Row is one result: the dimensions' values in order, and the numbers.
|
|
type Row struct {
|
|
Keys []string `json:"keys"`
|
|
Clicks float64 `json:"clicks"`
|
|
Impressions float64 `json:"impressions"`
|
|
CTR float64 `json:"ctr"`
|
|
Position float64 `json:"position"`
|
|
}
|
|
|
|
// maxRows is Google's page size.
|
|
const maxRows = 25000
|
|
|
|
// Analytics runs a query, reading every page of rows.
|
|
func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, error) {
|
|
path := "/sites/" + url.PathEscape(site) + "/searchAnalytics/query"
|
|
q.RowLimit = maxRows
|
|
var all []Row
|
|
for {
|
|
var out struct {
|
|
Rows []Row `json:"rows"`
|
|
}
|
|
if err := c.do(ctx, http.MethodPost, path, q, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
all = append(all, out.Rows...)
|
|
if len(out.Rows) < maxRows {
|
|
return all, nil
|
|
}
|
|
q.StartRow += maxRows
|
|
}
|
|
}
|