// Package statement fetches a problem's statement from its judge, as // markdown, for problem.md. Only the judges this repo mostly uses are known: // LeetCode (its public GraphQL API) and USACO (the problem page's HTML). // Anything else is pasted by hand. package statement import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "time" htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2" "golang.org/x/net/html" ) // ErrUnsupported is a link to a judge this package cannot read. var ErrUnsupported = errors.New("statements can't be fetched from this site; paste it instead") // maxBody caps a judge's response. A statement page is tens of kilobytes. const maxBody = 1 << 20 // Fetcher reads statements. The zero value talks to the real judges; tests // point the bases at an httptest server. type Fetcher struct { Client *http.Client LeetCodeAPI string // default https://leetcode.com/graphql USACOBase string // default https://usaco.org } func (f *Fetcher) client() *http.Client { if f.Client != nil { return f.Client } return &http.Client{Timeout: 15 * time.Second} } // Fetch returns the statement behind a problem link as markdown, headed by // the problem's title. func (f *Fetcher) Fetch(ctx context.Context, link string) (string, error) { u, err := url.Parse(strings.TrimSpace(link)) if err != nil || u.Host == "" { return "", ErrUnsupported } switch strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") { case "leetcode.com": return f.leetcode(ctx, u) case "usaco.org": return f.usaco(ctx, u) } return "", ErrUnsupported } // leetcode asks the GraphQL API the problem page itself uses. Free problems // answer without a login; a premium one comes back with null content. func (f *Fetcher) leetcode(ctx context.Context, u *url.URL) (string, error) { // /problems// and /problems//description/ both name it. parts := strings.Split(strings.Trim(u.Path, "/"), "/") if len(parts) < 2 || parts[0] != "problems" || parts[1] == "" { return "", fmt.Errorf("not a LeetCode problem link") } body, _ := json.Marshal(map[string]any{ "query": "query($s:String!){question(titleSlug:$s){title content}}", "variables": map[string]string{"s": parts[1]}, }) api := f.LeetCodeAPI if api == "" { api = "https://leetcode.com/graphql" } req, err := http.NewRequestWithContext(ctx, http.MethodPost, api, bytes.NewReader(body)) if err != nil { return "", err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Referer", "https://leetcode.com") b, err := f.do(req) if err != nil { return "", err } var resp struct { Data struct { Question *struct { Title string `json:"title"` Content *string `json:"content"` } `json:"question"` } `json:"data"` } if err := json.Unmarshal(b, &resp); err != nil { return "", fmt.Errorf("LeetCode answered with something other than JSON") } q := resp.Data.Question if q == nil { return "", fmt.Errorf("LeetCode has no problem %q", parts[1]) } if q.Content == nil || strings.TrimSpace(*q.Content) == "" { return "", fmt.Errorf("LeetCode returned no statement (a premium problem?)") } return toMarkdown(q.Title, *q.Content) } // usaco reads the problem page: the title is its second

(the first is // the contest) and the statement is div.problem-text. func (f *Fetcher) usaco(ctx context.Context, u *url.URL) (string, error) { base := f.USACOBase if base == "" { base = "https://usaco.org" } req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(base, "/")+u.RequestURI(), nil) if err != nil { return "", err } b, err := f.do(req) if err != nil { return "", err } doc, err := html.Parse(bytes.NewReader(b)) if err != nil { return "", err } var h2s []string var text *html.Node for n := range doc.Descendants() { if n.Type != html.ElementNode { continue } switch { case n.Data == "h2": h2s = append(h2s, strings.TrimSpace(textOf(n))) case text == nil && n.Data == "div" && hasClass(n, "problem-text"): text = n } } if text == nil { return "", fmt.Errorf("no statement on that USACO page") } title := "" if len(h2s) > 0 { title = h2s[len(h2s)-1] } var buf bytes.Buffer if err := html.Render(&buf, text); err != nil { return "", err } return toMarkdown(title, buf.String()) } func (f *Fetcher) do(req *http.Request) ([]byte, error) { resp, err := f.client().Do(req) if err != nil { return nil, fmt.Errorf("could not reach %s", req.URL.Host) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("%s answered %d", req.URL.Host, resp.StatusCode) } return io.ReadAll(io.LimitReader(resp.Body, maxBody)) } func toMarkdown(title, body string) (string, error) { md, err := htmltomarkdown.ConvertString(body) if err != nil { return "", err } md = strings.TrimSpace(md) if title != "" { md = "# " + title + "\n\n" + md } return md, nil } func hasClass(n *html.Node, class string) bool { for _, a := range n.Attr { if a.Key == "class" && strings.Contains(" "+a.Val+" ", " "+class+" ") { return true } } return false } func textOf(n *html.Node) string { var sb strings.Builder for d := range n.Descendants() { if d.Type == html.TextNode { sb.WriteString(d.Data) } } return sb.String() }