app.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "strings"
  10. "time"
  11. )
  12. // Application stores main information needed to run the app
  13. type Application struct {
  14. Name, AccessToken, Sid, BaseURL, AuthString string
  15. Languages map[string]string
  16. Delay time.Duration
  17. }
  18. func (app *Application) setBaseURL(url string) {
  19. if !strings.HasSuffix(url, "/") {
  20. url += "/"
  21. }
  22. app.BaseURL = url
  23. }
  24. func jsonDecoder(data io.ReadCloser, target interface{}) error {
  25. decoder := json.NewDecoder(data)
  26. return decoder.Decode(target)
  27. }
  28. func (app *Application) loadLanguages() bool {
  29. data, err := os.Open("./html/languages.json")
  30. if err != nil {
  31. log.Printf("Error reading languages: %s", err)
  32. return false
  33. }
  34. defer data.Close()
  35. app.Languages = make(map[string]string)
  36. err = jsonDecoder(data, &app.Languages)
  37. if err != nil {
  38. log.Printf("Error decoding languages: %s", err)
  39. return false
  40. }
  41. return true
  42. }
  43. func (app Application) checkLanguage(language string) bool {
  44. _, ok := app.Languages[language]
  45. return ok
  46. }
  47. func (app *Application) login() (bool, error) {
  48. credentials, err := ioutil.ReadFile("./secrets.json")
  49. if err != nil {
  50. return false, fmt.Errorf("Error reading credentials: %s", err)
  51. }
  52. loginURL := app.BaseURL + "auth/login"
  53. resp, err := postQuery(loginURL, credentials)
  54. if err != nil {
  55. return false, fmt.Errorf("Error logging in: %s", err)
  56. }
  57. defer resp.Body.Close()
  58. if resp.StatusCode != 200 {
  59. return false, fmt.Errorf("Error logging in: %s", resp.Status)
  60. }
  61. err = jsonDecoder(resp.Body, &app)
  62. if err != nil {
  63. return false, fmt.Errorf("Error decoding login details: %s", err)
  64. }
  65. app.AuthString = "?authToken=" + app.AccessToken
  66. log.Println(app.AuthString, resp.Status)
  67. return true, nil
  68. }