-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.go
96 lines (90 loc) 路 2.14 KB
/
register.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package client
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
"github.com/fatih/color"
"github.com/lcian/cf-tool/util"
)
// Register for a contest
func (c *Client) Register(contestID string) error {
URL := fmt.Sprintf("%v/contestRegistration/%v", c.host, contestID)
resp, err := c.client.Get(URL)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if _, err = findHandle(body); err != nil {
return err
}
if msg := findCodeforcesMessage(body); msg != "" {
return errors.New(msg)
}
doc, err := goquery.NewDocumentFromReader(ioutil.NopCloser(bytes.NewReader(body)))
if err != nil {
return err
}
color.HiCyan(findTitle(doc))
if !agreesToTerms(doc) {
return errors.New("You cannot participate without agreeing to the terms")
}
formData, err := getFormData(doc, c)
if err != nil {
return err
}
resp, err = c.client.PostForm(URL, formData)
if err != nil {
return err
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Println(findCodeforcesMessage(body))
return nil
}
func findTitle(doc *goquery.Document) string {
title := doc.Find("h2").Text()
return cleanText(title)
}
func agreesToTerms(doc *goquery.Document) bool {
label := cleanText(doc.Find("label[for=registrationTerms]").Text())
terms := cleanText(doc.Find("#registrationTerms").Text())
terms = strings.ReplaceAll(terms, "\n*", "\n *")
color.Green(label)
fmt.Println(terms)
return util.YesOrNo("Do you argree to the terms? (y/n)")
}
func getFormData(doc *goquery.Document, c *Client) (url.Values, error) {
form := doc.Find(".contestRegistration").First()
data := url.Values{}
var err error
form.Find("input").Each(func(i int, input *goquery.Selection) {
key, k := input.Attr("name")
value, v := input.Attr("value")
if key != "" {
if !k || !v {
err = errors.New("Unable to get form data")
return
}
data.Set(key, value)
}
})
if data.Get("_tta") == "" {
tta, err := getTta(c)
if err != nil {
return data, nil
}
data.Set("_tta", tta)
}
return data, err
}