Import LeetCode problems from a pasted link on the site
The problem list's admin row gains a link box beside "Today's LeetCode":
POST /leetcode/import takes {url} and does what `usaco new
<leetcode-link>` does, through the same lib/leetcode.py run and "Start
<slug>" commit as the daily question, then opens the solve page. A
problem already in the repo is only opened.
leetcode.Slug reads the link as slug_of in lib/leetcode.py does: full
links with /description/ and query strings, www., no scheme, or a bare
slug. Anything else is a 400.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+2
-1
@@ -56,7 +56,7 @@ internal/transcribe/ OpenAI-compatible speech-to-text client, and pace/pause/fil
|
||||
internal/review/ the review prompt and schema, reviews/<id>.md rendering
|
||||
internal/evaluate/ the solve page's evaluation: prompt, schema and the run's verdicts for Claude
|
||||
internal/audiostore/ optional S3 bucket (Garage) that keeps review recordings for playback
|
||||
internal/leetcode/ today's daily question, imported by running the clone's lib/leetcode.py
|
||||
internal/leetcode/ today's daily question or a pasted link, imported by running the clone's lib/leetcode.py
|
||||
internal/statement/ fetches statements from LeetCode (GraphQL) and USACO (the problem page)
|
||||
web/ Vue 3 + Vite SPA, built for base /usaco/
|
||||
```
|
||||
@@ -87,6 +87,7 @@ Everything is served under `BASE_PATH` (`/usaco`). nginx proxies the prefix thro
|
||||
| `GET /usaco/api/problems/<name>/evaluate` | admin | the latest evaluation job, shaped like the explain one, with the evaluation as `result` once it is done |
|
||||
| `PUT /usaco/api/problems/<name>/code` | admin | `{lang, source}`: commits `main.cpp`, or `main.py` (`sol.py` where that is the existing file), as "Edit <name>" |
|
||||
| `POST /usaco/api/leetcode/daily` | admin | imports today's LeetCode daily question into `solving/` with the CLI's `lib/leetcode.py` and commits it as "Start <slug>", or finds it if it is already a problem; answers `{name, created}`. 502 if LeetCode or the import fails |
|
||||
| `POST /usaco/api/leetcode/import` | admin | `{url}`: the same for the problem a LeetCode link names (`usaco new <leetcode-link>`); a bare slug works too. 400 if it is not a LeetCode problem link, 502 if LeetCode or the import fails |
|
||||
| `GET /usaco/api/concepts` | open | the concept library, newest first, without content or snippets |
|
||||
| `GET /usaco/api/concepts/<slug>` | open | one concept: `{slug, title, summary, tags, content, snippet, updated}` |
|
||||
| `POST /usaco/api/concepts` | admin | `{topic, code?}`: starts explaining a new concept and answers 202 `{id, status}`. 503 without `CLAUDE_API_KEY` |
|
||||
|
||||
@@ -27,8 +27,6 @@ func (s *Server) leetcode() LeetCode {
|
||||
|
||||
// startDaily is `usaco daily`: it imports today's LeetCode daily question
|
||||
// into solving/ and commits it, and answers its name for the page to open.
|
||||
// A daily question already in the repo (started yesterday from the CLI, or
|
||||
// solved months ago) is only named, never imported again.
|
||||
func (s *Server) startDaily(ctx *gin.Context) {
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
@@ -44,6 +42,33 @@ func (s *Server) startDaily(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "LeetCode named the daily question " + slug + ", which is not a usable name"})
|
||||
return
|
||||
}
|
||||
s.startLeetCode(ctx, c, lc, slug)
|
||||
}
|
||||
|
||||
// startImport is `usaco new <leetcode-link>`: the same import, for the
|
||||
// problem a pasted link names.
|
||||
func (s *Server) startImport(ctx *gin.Context) {
|
||||
var body struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
|
||||
return
|
||||
}
|
||||
slug, err := leetcode.Slug(body.URL)
|
||||
if err != nil || !validName.MatchString(slug) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "not a LeetCode problem link"})
|
||||
return
|
||||
}
|
||||
c, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
s.startLeetCode(ctx, c, s.leetcode(), slug)
|
||||
}
|
||||
|
||||
// startLeetCode imports slug into solving/, commits it as "Start <slug>" and
|
||||
// answers {name, created}. A problem already in the repo (started yesterday
|
||||
// from the CLI, or solved months ago) is only named, never imported again.
|
||||
func (s *Server) startLeetCode(ctx *gin.Context, c context.Context, lc LeetCode, slug string) {
|
||||
if idx := s.Index(); idx != nil {
|
||||
if _, ok := idx.Problems[slug]; ok {
|
||||
ctx.JSON(http.StatusOK, gin.H{"name": slug, "created": false})
|
||||
@@ -51,7 +76,7 @@ func (s *Server) startDaily(ctx *gin.Context) {
|
||||
}
|
||||
}
|
||||
created := false
|
||||
err = s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
|
||||
err := s.Repo.Mutate(c, "Start "+slug, func(dir string) error {
|
||||
if _, err := findOnDisk(dir, slug); err == nil {
|
||||
created = false
|
||||
return nil
|
||||
|
||||
@@ -84,3 +84,66 @@ func TestDailyImportFails(t *testing.T) {
|
||||
t.Fatalf("daily = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportLink(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
lc := &fakeLeetCode{}
|
||||
repo.srv.LeetCode = lc
|
||||
body := `{"url":"https://leetcode.com/problems/two-sum/description/?envType=problem-list-v2"}`
|
||||
|
||||
if rec := do(r, "POST", "/usaco/api/leetcode/import", body, false); rec.Code != 401 {
|
||||
t.Fatalf("non-admin = %d, want 401", rec.Code)
|
||||
}
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/import", body, true)
|
||||
var got dailyReply
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if rec.Code != 200 || got != (dailyReply{"two-sum", true}) {
|
||||
t.Fatalf("import = %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if len(repo.msg) != 1 || repo.msg[0] != "Start two-sum" {
|
||||
t.Fatalf("commits = %v", repo.msg)
|
||||
}
|
||||
if _, ok := repo.srv.Index().Problems["two-sum"]; !ok {
|
||||
t.Fatal("two-sum is not in the index after the import")
|
||||
}
|
||||
|
||||
rec = do(r, "POST", "/usaco/api/leetcode/import", body, true)
|
||||
got = dailyReply{}
|
||||
json.Unmarshal(rec.Body.Bytes(), &got)
|
||||
if rec.Code != 200 || got != (dailyReply{"two-sum", false}) || lc.imports != 1 {
|
||||
t.Fatalf("second import = %d %s after %d imports", rec.Code, rec.Body, lc.imports)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportExisting(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
lc := &fakeLeetCode{}
|
||||
repo.srv.LeetCode = lc
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/import", `{"url":"https://leetcode.com/problems/moocast/"}`, true)
|
||||
if rec.Code != 200 || lc.imports != 0 || len(repo.msg) != 0 {
|
||||
t.Fatalf("import = %d %s, %d imports, commits %v", rec.Code, rec.Body, lc.imports, repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportBadLink(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
lc := &fakeLeetCode{}
|
||||
repo.srv.LeetCode = lc
|
||||
for _, body := range []string{`{"url":"https://codeforces.com/problemset/problem/1/A"}`, `{"url":""}`, `not json`} {
|
||||
if rec := do(r, "POST", "/usaco/api/leetcode/import", body, true); rec.Code != 400 {
|
||||
t.Fatalf("import %s = %d %s, want 400", body, rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
if lc.imports != 0 || len(repo.msg) != 0 {
|
||||
t.Fatalf("%d imports, commits %v", lc.imports, repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportFails(t *testing.T) {
|
||||
r, repo, _ := setup(t)
|
||||
repo.srv.LeetCode = &fakeLeetCode{err: errors.New("LeetCode has no problem 'nope'")}
|
||||
rec := do(r, "POST", "/usaco/api/leetcode/import", `{"url":"https://leetcode.com/problems/nope/"}`, true)
|
||||
if rec.Code != 502 || len(repo.msg) != 0 {
|
||||
t.Fatalf("import = %d %s, commits %v", rec.Code, rec.Body, repo.msg)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ type Server struct {
|
||||
// Statements reads a statement from the problem's judge; nil means the
|
||||
// real judges.
|
||||
Statements Fetcher
|
||||
// LeetCode starts the daily question; nil means the real API and the
|
||||
// clone's lib/leetcode.py.
|
||||
// LeetCode starts the daily question and pasted links; nil means the
|
||||
// real API and the clone's lib/leetcode.py.
|
||||
LeetCode LeetCode
|
||||
// Transcriber turns review recordings into text; nil when
|
||||
// TRANSCRIBE_API_KEY is not set, which turns reviews off.
|
||||
@@ -118,6 +118,7 @@ func (s *Server) Routes(api *gin.RouterGroup) {
|
||||
admin.POST("/problems/:name/evaluate", s.startEvaluate)
|
||||
admin.GET("/problems/:name/evaluate", s.evaluateStatus)
|
||||
admin.POST("/leetcode/daily", s.startDaily)
|
||||
admin.POST("/leetcode/import", s.startImport)
|
||||
api.GET("/concepts", s.listConcepts)
|
||||
api.GET("/concepts/:slug", s.getConcept)
|
||||
admin.POST("/concepts", s.startConcept)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package leetcode starts LeetCode problems from the site the way `usaco
|
||||
// daily` does from the CLI. The import itself is the CLI's: lib/leetcode.py
|
||||
// daily` and `usaco new <leetcode-link>` 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.
|
||||
@@ -13,8 +13,10 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -73,6 +75,31 @@ func (i *Importer) Daily(ctx context.Context) (string, error) {
|
||||
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/<slug>/ 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/<slug>. The script reports a failure as "Error: ..." on
|
||||
// stderr, which is what the admin is shown.
|
||||
|
||||
@@ -32,6 +32,32 @@ func TestDailyMissing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlug(t *testing.T) {
|
||||
for _, link := range []string{
|
||||
"https://leetcode.com/problems/two-sum/",
|
||||
"https://leetcode.com/problems/two-sum/description/?envType=daily-question",
|
||||
" https://www.leetcode.com/problems/two-sum ",
|
||||
"leetcode.com/problems/two-sum/",
|
||||
"two-sum",
|
||||
} {
|
||||
if got, err := Slug(link); err != nil || got != "two-sum" {
|
||||
t.Errorf("Slug(%q) = %q, %v; want two-sum", link, got, err)
|
||||
}
|
||||
}
|
||||
for _, link := range []string{
|
||||
"",
|
||||
"https://codeforces.com/problems/two-sum/",
|
||||
"https://leetcode.com/contest/weekly-contest-400/",
|
||||
"https://leetcode.com/problems/",
|
||||
"https://leetcode.com/problems/../x/",
|
||||
"https://evil.com/leetcode.com/problems/two-sum/",
|
||||
} {
|
||||
if got, err := Slug(link); err == nil {
|
||||
t.Errorf("Slug(%q) = %q, want an error", link, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The script's own "Error: ..." line is the message, not the exit status.
|
||||
func TestImportError(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
|
||||
@@ -68,6 +68,8 @@ export const evaluateStatus = (name) => request("GET", `/problems/${encodeURICom
|
||||
// Imports today's LeetCode daily question (or finds it, if it is already a
|
||||
// problem) and answers { name, created }. It takes a few seconds.
|
||||
export const startDaily = () => request("POST", "/leetcode/daily");
|
||||
// The same for the problem a LeetCode link names.
|
||||
export const importLeetCode = (url) => request("POST", "/leetcode/import", { url });
|
||||
|
||||
// Concepts: techniques Claude explained, with a C++ snippet. Anyone can read
|
||||
// them; starting one answers 202 { id, status } and the job's status, at
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { RouterLink, useRoute, useRouter } from "vue-router";
|
||||
import { listProblems, startDaily } from "@/api";
|
||||
import { importLeetCode, listProblems, startDaily } from "@/api";
|
||||
import { LANG_LABELS, STATUS_LABELS, formatDate, title } from "@/format";
|
||||
|
||||
const route = useRoute();
|
||||
@@ -18,21 +18,26 @@ const admin = ref(false);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
|
||||
// "Today's LeetCode" imports the daily question as `usaco daily` would and
|
||||
// opens it on the solve page; one already in the repo is just opened.
|
||||
const starting = ref(false);
|
||||
const dailyError = ref("");
|
||||
async function openDaily() {
|
||||
starting.value = true;
|
||||
dailyError.value = "";
|
||||
// "Today's LeetCode" imports the daily question as `usaco daily` would, and
|
||||
// a pasted link the problem it names as `usaco new <link>` would; either
|
||||
// opens on the solve page, and one already in the repo is just opened. One
|
||||
// import at a time: they share the busy flag and the error line.
|
||||
const importing = ref("");
|
||||
const importError = ref("");
|
||||
const link = ref("");
|
||||
async function startImport(kind, start) {
|
||||
importing.value = kind;
|
||||
importError.value = "";
|
||||
try {
|
||||
const { name } = await startDaily();
|
||||
const { name } = await start();
|
||||
router.push({ name: "solve", params: { name } });
|
||||
} catch (e) {
|
||||
dailyError.value = e.message;
|
||||
starting.value = false;
|
||||
importError.value = e.message;
|
||||
importing.value = "";
|
||||
}
|
||||
}
|
||||
const openDaily = () => startImport("daily", startDaily);
|
||||
const openLink = () => link.value.trim() && startImport("link", () => importLeetCode(link.value.trim()));
|
||||
|
||||
const status = computed({
|
||||
get: () => route.query.status || "all",
|
||||
@@ -126,11 +131,17 @@ const groups = computed(() => {
|
||||
<option value="recent">Most recent</option>
|
||||
<option value="name">Name</option>
|
||||
</select>
|
||||
<button v-if="admin" class="btn primary" :disabled="starting" @click="openDaily">
|
||||
{{ starting ? "Fetching today's problem…" : "Today's LeetCode" }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="dailyError" class="error daily-error">{{ dailyError }}</p>
|
||||
<form v-if="admin" class="controls" @submit.prevent="openLink">
|
||||
<input v-model="link" type="url" placeholder="Paste a LeetCode link" aria-label="LeetCode problem link" />
|
||||
<button class="btn" type="submit" :disabled="!!importing || !link.trim()">
|
||||
{{ importing === "link" ? "Importing…" : "Import" }}
|
||||
</button>
|
||||
<button class="btn primary" type="button" :disabled="!!importing" @click="openDaily">
|
||||
{{ importing === "daily" ? "Fetching today's problem…" : "Today's LeetCode" }}
|
||||
</button>
|
||||
</form>
|
||||
<p v-if="importError" class="error import-error">{{ importError }}</p>
|
||||
|
||||
<p v-if="loading" class="muted">Loading…</p>
|
||||
<p v-else-if="error" class="error">{{ error }}</p>
|
||||
@@ -171,7 +182,7 @@ const groups = computed(() => {
|
||||
.intro {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.daily-error {
|
||||
.import-error {
|
||||
margin: -8px 0 16px;
|
||||
}
|
||||
.controls {
|
||||
|
||||
Reference in New Issue
Block a user