// Package leetcode starts LeetCode problems from the site the way `usaco // daily` and `usaco new ` do from the CLI. The import itself is the CLI's: lib/leetcode.py // in the clone writes problem.md, main.cpp, the generated driver.h and the // examples as tests. Rewriting its driver generator in Go would leave two // copies to drift apart, so the site image carries python3 to run it. package leetcode import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "os/exec" "path/filepath" "regexp" "strings" "time" ) // Importer asks LeetCode for the daily question and runs the CLI's importer. // The zero value talks to the real API with python3 from PATH; tests point // API at an httptest server. type Importer struct { Client *http.Client API string // default https://leetcode.com/graphql Python string // default python3 } // Daily is the slug of today's daily question. func (i *Importer) Daily(ctx context.Context) (string, error) { body, _ := json.Marshal(map[string]string{ "query": "query { activeDailyCodingChallengeQuestion { question { titleSlug } } }", }) api := i.API 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") client := i.Client if client == nil { client = &http.Client{Timeout: 15 * time.Second} } resp, err := client.Do(req) if err != nil { return "", fmt.Errorf("could not reach LeetCode") } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("LeetCode answered %s", resp.Status) } var out struct { Data struct { Daily *struct { Question struct { Slug string `json:"titleSlug"` } `json:"question"` } `json:"activeDailyCodingChallengeQuestion"` } `json:"data"` } if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&out); err != nil { return "", fmt.Errorf("LeetCode answered with something other than JSON") } if out.Data.Daily == nil || out.Data.Daily.Question.Slug == "" { return "", fmt.Errorf("LeetCode named no daily question") } return out.Data.Daily.Question.Slug, nil } var slugRe = regexp.MustCompile(`^[a-z0-9-]+$`) // Slug is the problem a LeetCode link names, as slug_of in lib/leetcode.py // reads it: https://leetcode.com/problems// with anything after (the // /description/ and ?envType=... a copied link carries), with or without the // scheme, or a bare slug. func Slug(link string) (string, error) { link = strings.TrimSpace(link) if slugRe.MatchString(link) { return link, nil } if !strings.Contains(link, "://") { link = "https://" + link } u, err := url.Parse(link) if err != nil || strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") != "leetcode.com" { return "", errors.New("not a LeetCode problem link") } parts := strings.Split(strings.Trim(u.Path, "/"), "/") if len(parts) < 2 || parts[0] != "problems" || !slugRe.MatchString(parts[1]) { return "", errors.New("not a LeetCode problem link") } return parts[1], nil } // Import runs `lib/leetcode.py root slug` in the clone at root, which // creates solving/. The script reports a failure as "Error: ..." on // stderr, which is what the admin is shown. func (i *Importer) Import(ctx context.Context, root, slug string) error { python := i.Python if python == "" { python = "python3" } var stderr bytes.Buffer cmd := exec.CommandContext(ctx, python, "-I", filepath.Join(root, "lib", "leetcode.py"), root, slug) cmd.Env = scriptEnv() cmd.Stderr = &stderr if err := cmd.Run(); err != nil { for _, line := range strings.Split(stderr.String(), "\n") { if msg, ok := strings.CutPrefix(line, "Error: "); ok { return errors.New(msg) } } return fmt.Errorf("the LeetCode import failed: %v", err) } return nil } // scriptEnv is the environment the importer runs with: what python3 needs // to reach LeetCode over HTTPS, and nothing else. The script comes from the // clone, so whoever can push to the repo writes it, while this process holds // the Claude, Gitea and S3 secrets in its environment. Those must not be // inherited. func scriptEnv() []string { env := []string{"HOME=" + os.TempDir(), "LANG=C.UTF-8"} if _, ok := os.LookupEnv("PATH"); !ok { env = append(env, "PATH=/usr/local/bin:/usr/bin:/bin") } for _, k := range []string{"PATH", "TMPDIR", "SSL_CERT_FILE", "SSL_CERT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"} { if v, ok := os.LookupEnv(k); ok { env = append(env, k+"="+v) } } return env }