From 2a991c6f07ce29eea5d71a72265c2485665f2978 Mon Sep 17 00:00:00 2001 From: budougumi0617 Date: Sat, 26 Sep 2020 01:21:42 +0900 Subject: [PATCH] :sparkles: exec: submit code --- client.go | 38 ++++++++++++++++++++++++++++++++++++++ exec.go | 44 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 1 deletion(-) diff --git a/client.go b/client.go index 0ece245..913a5c6 100644 --- a/client.go +++ b/client.go @@ -7,6 +7,7 @@ import ( "fmt" "log" "net/http" + "strconv" "time" ) @@ -241,6 +242,43 @@ func (lc *LeetCode) Check(ctx context.Context, q *Question, id string) (*CheckRe return &res, nil } +func (lc *LeetCode) Submit(ctx context.Context, q *Question, ans string) (string, error) { + sr := &SubmitRequest{ + Lang: "golang", + QuestionID: q.QuestionID, + TestMode: "false", + Name: q.Slug, + TypedCode: ans, + } + b, err := json.Marshal(sr) + if err != nil { + log.Printf("failed Marshal %+v\n", err) + return "", err + } + surl := lc.BaseURL + fmt.Sprintf("/problems/%s/submit/", q.Slug) + log.Printf("send to %q", surl) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, surl, bytes.NewBuffer(b)) + if err != nil { + return "", err + } + lc.fill(req, q) + req.Header.Set("Referer", surl) + cli := http.Client{ + Timeout: 3 * time.Second, + } + resp, err := cli.Do(req) + if err != nil { + log.Printf("failed Do %+v\n", err) + return "", err + } + var res SubmitResult + if err := json.NewDecoder(resp.Body).Decode(&res); err != nil { + return "", err + } + log.Printf("result %+v\n", res) + return strconv.Itoa(res.SubmissionID), nil +} + //SUBCOMMANDS: //data Manage Cache [aliases: d] //edit Edit question by id [aliases: e] diff --git a/exec.go b/exec.go index 8f0cdbb..001f02b 100644 --- a/exec.go +++ b/exec.go @@ -1,7 +1,49 @@ package leetgode -import "context" +import ( + "context" + "fmt" + "io/ioutil" + "os" +) func ExecCmd(ctx context.Context, id int) error { + session := os.Getenv("LEETCODE_SESSION") + token := os.Getenv("LEETCODE_TOKEN") + + cli, err := NewLeetCode(fillAuth(session, token)) + if err != nil { + return err + } + q, err := cli.GetQuestionByID(ctx, id) + if err != nil { + return err + } + fp := buildPath(q.QuestionID, q.Slug) + code, err := ioutil.ReadFile(fp) + if err != nil { + return err + } + tr, err := cli.Submit(ctx, q, string(code)) + if err != nil { + return err + } + for { + fmt.Print("now sending") + res, err := cli.Check(ctx, q, tr) + if err != nil { + return err + } + if res.State == "SUCCESS" { + fmt.Printf(` +test id: %s +test name: %s +result: %s +`, q.QuestionID, q.Slug, res.StatusMsg) + break + } else { + fmt.Print(".") + } + } return nil }