config.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package util
  2. import (
  3. "encoding/json"
  4. "os"
  5. "github.com/rivo/tview"
  6. )
  7. // Config consists of fields, such as theme, mouse, so on, that may be
  8. // customized by the user.
  9. type Config struct {
  10. Token string `json:"token"`
  11. Mouse bool `json:"mouse"`
  12. Notifications bool `json:"notifications"`
  13. UserAgent string `json:"userAgent"`
  14. GetMessagesLimit int `json:"getMessagesLimit"`
  15. Theme tview.Theme `json:"theme"`
  16. }
  17. // LoadConfig creates (if the configuration file does not exist) and reads the configuration file and returns a new config.
  18. func LoadConfig() *Config {
  19. u, err := os.UserHomeDir()
  20. if err != nil {
  21. panic(err)
  22. }
  23. configPath := u + "/.config/discordo/config.json"
  24. if _, err := os.Stat(configPath); os.IsNotExist(err) {
  25. f, err := os.Create(configPath)
  26. if err != nil {
  27. panic(err)
  28. }
  29. c := Config{
  30. Mouse: true,
  31. Notifications: true,
  32. UserAgent: "" +
  33. "Mozilla/5.0 (X11; Linux x86_64) " +
  34. "AppleWebKit/537.36 (KHTML, like Gecko) " +
  35. "Chrome/92.0.4515.131 Safari/537.36",
  36. GetMessagesLimit: 50,
  37. Theme: tview.Styles,
  38. }
  39. d, err := json.MarshalIndent(c, "", "\t")
  40. if err != nil {
  41. panic(err)
  42. }
  43. _, err = f.Write(d)
  44. if err != nil {
  45. panic(err)
  46. }
  47. f.Sync()
  48. }
  49. d, err := os.ReadFile(configPath)
  50. if err != nil {
  51. panic(err)
  52. }
  53. var c Config
  54. if err = json.Unmarshal(d, &c); err != nil {
  55. panic(err)
  56. }
  57. return &c
  58. }