/
app.go
88 lines (73 loc) · 1.91 KB
/
app.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
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
// Application stores main information needed to run the app
type Application struct {
Name, AccessToken, Sid, BaseURL, AuthString string
Languages map[string]string
Delay time.Duration
}
func (app *Application) setBaseURL(baseURL string) {
if !strings.HasSuffix(baseURL, "/") {
baseURL += "/"
}
app.BaseURL = baseURL
}
func jsonDecoder(data io.ReadCloser, target interface{}) error {
decoder := json.NewDecoder(data)
return decoder.Decode(target)
}
func (app *Application) loadLanguages() bool {
data, err := os.Open("./html/languages.json")
if err != nil {
log.Printf("Error reading languages: %s", err)
return false
}
defer func() {
if err := data.Close(); err != nil {
log.Printf("Error closing file: %s", err)
}
}()
app.Languages = make(map[string]string)
err = jsonDecoder(data, &app.Languages)
if err != nil {
log.Printf("Error decoding languages: %s", err)
return false
}
return true
}
func (app *Application) checkLanguage(language *string) bool {
_, ok := app.Languages[*language]
return ok
}
func (app *Application) login() (bool, error) {
credentials, err := ioutil.ReadFile("./secrets.json")
if err != nil {
return false, fmt.Errorf("Error reading credentials: %s", err)
}
loginURL := app.BaseURL + "auth/login"
resp, err := postQuery(loginURL, credentials)
if err != nil {
return false, fmt.Errorf("Error logging in: %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false, fmt.Errorf("Error logging in: %s", resp.Status)
}
err = jsonDecoder(resp.Body, &app)
if err != nil {
return false, fmt.Errorf("Error decoding login details: %s", err)
}
app.AuthString = "?authToken=" + app.AccessToken
log.Println(app.AuthString, resp.Status)
return true, nil
}