config.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package util
  2. import (
  3. "encoding/json"
  4. "os"
  5. "github.com/rivo/tview"
  6. )
  7. type keybindings struct {
  8. GuildsTreeViewFocus string
  9. MessagesTextViewFocus string
  10. MessagesTextViewSelectPrevious string
  11. MessagesTextViewSelectNext string
  12. MessagesTextViewSelectFirst string
  13. MessagesTextViewSelectLast string
  14. MessagesTextViewReplySelected string
  15. MessagesTextViewMentionReplySelected string
  16. MessageInputFieldFocus string
  17. }
  18. // Config consists of fields that can be customized by the user using the configuration file.
  19. type Config struct {
  20. Token string
  21. Mouse bool
  22. Notifications bool
  23. UserAgent string
  24. GetMessagesLimit int
  25. Theme tview.Theme
  26. Keybindings keybindings
  27. }
  28. // LoadConfig createsa new configuration file (if does not exist) and returns the default configuration or reads the existing configuration file from the default path.
  29. func LoadConfig() *Config {
  30. u, err := os.UserHomeDir()
  31. if err != nil {
  32. panic(err)
  33. }
  34. configPath := u + "/.config/discordo/config.json"
  35. if _, err = os.Stat(configPath); os.IsNotExist(err) {
  36. err = os.MkdirAll(u+"/.config/discordo", 0700)
  37. if err != nil {
  38. panic(err)
  39. }
  40. f, err := os.Create(configPath)
  41. if err != nil {
  42. panic(err)
  43. }
  44. defer f.Close()
  45. c := Config{
  46. Mouse: true,
  47. Notifications: true,
  48. UserAgent: "" +
  49. "Mozilla/5.0 (X11; Linux x86_64) " +
  50. "AppleWebKit/537.36 (KHTML, like Gecko) " +
  51. "Chrome/92.0.4515.131 Safari/537.36",
  52. GetMessagesLimit: 50,
  53. Theme: tview.Styles,
  54. Keybindings: keybindings{
  55. GuildsTreeViewFocus: "Alt+Rune[1]",
  56. MessagesTextViewFocus: "Alt+Rune[2]",
  57. MessagesTextViewSelectPrevious: "Up",
  58. MessagesTextViewSelectNext: "Down",
  59. MessagesTextViewSelectFirst: "Home",
  60. MessagesTextViewSelectLast: "End",
  61. MessagesTextViewReplySelected: "r",
  62. MessagesTextViewMentionReplySelected: "R",
  63. MessageInputFieldFocus: "Alt+Rune[3]",
  64. },
  65. }
  66. d, err := json.MarshalIndent(c, "", "\t")
  67. if err != nil {
  68. panic(err)
  69. }
  70. _, err = f.Write(d)
  71. if err != nil {
  72. panic(err)
  73. }
  74. f.Sync()
  75. return &c
  76. }
  77. d, err := os.ReadFile(configPath)
  78. if err != nil {
  79. panic(err)
  80. }
  81. var c Config
  82. if err = json.Unmarshal(d, &c); err != nil {
  83. panic(err)
  84. }
  85. return &c
  86. }