blob: 9ba79f66b7e0273890324df669f3b7e137a87784 [file] [log] [blame]
package hguclient
import (
"errors"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"golang.org/x/net/publicsuffix"
)
const URL_INDEX = "/"
const URL_LOGIN = "/te_acceso_router.cgi"
const URL_SIPBASIC = "/voicesip_basic.html"
const URL_SIPSTOP = "/voicesipstop.cmd"
const URL_SIPSTART = "/voicesipstart.cmd"
const LOGGED_OUT_SCRIPT = "<script language='javascript'>\nwindow.top.location = \"/\";\n</script>"
const LOGGED_OUT_SCRIPT_HOME = "src='te_acceso_router.html'"
type Client struct {
httpClient http.Client
endpoint string
password string
}
func New(endpoint string, password string) (*Client, error) {
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
return nil, err
}
client := &Client{
httpClient: http.Client{
Jar: jar,
},
endpoint: endpoint,
password: password,
}
return client, nil
}
func (c *Client) LogIn() error {
// Visit the homepage to generate the current sessionId cookie
c.httpClient.Get(c.endpoint)
// Log in
resp, err := c.httpClient.PostForm(c.endpoint+URL_LOGIN, url.Values{
"loginPassword": []string{c.password},
})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New("Status code is not 200.")
}
return nil
}
func (c *Client) Get(path string, autoLogIn bool) (string, error) {
resp, err := c.httpClient.Get(c.endpoint + path)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", errors.New("Status code is not 200.")
}
bodyb, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
body := string(bodyb)
if !strings.Contains(body, LOGGED_OUT_SCRIPT) {
return body, nil
}
if !autoLogIn {
return "", errors.New("User needs to log in")
}
c.LogIn()
return c.Get(path, false)
}
func (c *Client) IsLoggedIn() (bool, error) {
body, err := c.Get("", false)
if err != nil {
return false, err
}
return !strings.Contains(body, LOGGED_OUT_SCRIPT_HOME), nil
}