Skip to content

Commit

Permalink
✨ exec: submit code
Browse files Browse the repository at this point in the history
  • Loading branch information
budougumi0617 committed Sep 25, 2020
1 parent 17fe449 commit 2a991c6
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
38 changes: 38 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"log"
"net/http"
"strconv"
"time"
)

Expand Down Expand Up @@ -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]
Expand Down
44 changes: 43 additions & 1 deletion exec.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 2a991c6

Please sign in to comment.