Adrià Vilanova MartÃnez | 32758f0 | 2022-01-20 16:03:00 +0100 | [diff] [blame^] | 1 | package hguclient |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/cookiejar" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | |
| 11 | "golang.org/x/net/publicsuffix" |
| 12 | ) |
| 13 | |
| 14 | const URL_INDEX = "/" |
| 15 | const URL_LOGIN = "/te_acceso_router.cgi" |
| 16 | const URL_SIPBASIC = "/voicesip_basic.html" |
| 17 | const URL_SIPSTOP = "/voicesipstop.cmd" |
| 18 | const URL_SIPSTART = "/voicesipstart.cmd" |
| 19 | |
| 20 | const LOGGED_OUT_SCRIPT = "<script language='javascript'>\nwindow.top.location = \"/\";\n</script>" |
| 21 | const LOGGED_OUT_SCRIPT_HOME = "src='te_acceso_router.html'" |
| 22 | |
| 23 | type Client struct { |
| 24 | httpClient http.Client |
| 25 | endpoint string |
| 26 | password string |
| 27 | } |
| 28 | |
| 29 | func New(endpoint string, password string) (*Client, error) { |
| 30 | jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) |
| 31 | if err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | |
| 35 | client := &Client{ |
| 36 | httpClient: http.Client{ |
| 37 | Jar: jar, |
| 38 | }, |
| 39 | endpoint: endpoint, |
| 40 | password: password, |
| 41 | } |
| 42 | return client, nil |
| 43 | } |
| 44 | |
| 45 | func (c *Client) LogIn() error { |
| 46 | // Visit the homepage to generate the current sessionId cookie |
| 47 | c.httpClient.Get(c.endpoint) |
| 48 | |
| 49 | // Log in |
| 50 | resp, err := c.httpClient.PostForm(c.endpoint+URL_LOGIN, url.Values{ |
| 51 | "loginPassword": []string{c.password}, |
| 52 | }) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | defer resp.Body.Close() |
| 57 | if resp.StatusCode != 200 { |
| 58 | return errors.New("Status code is not 200.") |
| 59 | } |
| 60 | |
| 61 | return nil |
| 62 | } |
| 63 | |
| 64 | func (c *Client) Get(path string, autoLogIn bool) (string, error) { |
| 65 | resp, err := c.httpClient.Get(c.endpoint + path) |
| 66 | if err != nil { |
| 67 | return "", err |
| 68 | } |
| 69 | defer resp.Body.Close() |
| 70 | if resp.StatusCode != 200 { |
| 71 | return "", errors.New("Status code is not 200.") |
| 72 | } |
| 73 | bodyb, err := io.ReadAll(resp.Body) |
| 74 | if err != nil { |
| 75 | return "", err |
| 76 | } |
| 77 | body := string(bodyb) |
| 78 | |
| 79 | if !strings.Contains(body, LOGGED_OUT_SCRIPT) { |
| 80 | return body, nil |
| 81 | } |
| 82 | if !autoLogIn { |
| 83 | return "", errors.New("User needs to log in") |
| 84 | } |
| 85 | c.LogIn() |
| 86 | return c.Get(path, false) |
| 87 | } |
| 88 | |
| 89 | func (c *Client) IsLoggedIn() (bool, error) { |
| 90 | body, err := c.Get("", false) |
| 91 | if err != nil { |
| 92 | return false, err |
| 93 | } |
| 94 | return !strings.Contains(body, LOGGED_OUT_SCRIPT_HOME), nil |
| 95 | } |