app.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 func() {
  35. if err := data.Close(); err != nil {
  36. log.Printf("Error closing file: %s", err)
  37. }
  38. }()
  39. app.Languages = make(map[string]string)
  40. err = jsonDecoder(data, &app.Languages)
  41. if err != nil {
  42. log.Printf("Error decoding languages: %s", err)
  43. return false
  44. }
  45. return true
  46. }
  47. func (app Application) checkLanguage(language string) bool {
  48. _, ok := app.Languages[language]
  49. return ok
  50. }
  51. func (app *Application) login() (bool, error) {
  52. credentials, err := ioutil.ReadFile("./secrets.json")
  53. if err != nil {
  54. return false, fmt.Errorf("Error reading credentials: %s", err)
  55. }
  56. loginURL := app.BaseURL + "auth/login"
  57. resp, err := postQuery(loginURL, credentials)
  58. if err != nil {
  59. return false, fmt.Errorf("Error logging in: %s", err)
  60. }
  61. defer resp.Body.Close()
  62. if resp.StatusCode != 200 {
  63. return false, fmt.Errorf("Error logging in: %s", resp.Status)
  64. }
  65. err = jsonDecoder(resp.Body, &app)
  66. if err != nil {
  67. return false, fmt.Errorf("Error decoding login details: %s", err)
  68. }
  69. app.AuthString = "?authToken=" + app.AccessToken
  70. log.Println(app.AuthString, resp.Status)
  71. return true, nil
  72. }