config.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package config
  2. import (
  3. "log/slog"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "github.com/BurntSushi/toml"
  8. "github.com/ayn2op/discordo/internal/consts"
  9. "github.com/diamondburned/arikawa/v3/discord"
  10. )
  11. const fileName = "config.toml"
  12. type (
  13. Identify struct {
  14. Status discord.Status `toml:"status"`
  15. Browser string `toml:"browser"`
  16. BrowserVersion string `toml:"browser_version"`
  17. UserAgent string `toml:"user_agent"`
  18. }
  19. Notifications struct {
  20. Enabled bool `toml:"enabled"`
  21. Duration int `toml:"duration"`
  22. Sound Sound `toml:"sound"`
  23. }
  24. Sound struct {
  25. Enabled bool `toml:"enabled"`
  26. OnlyOnPing bool `toml:"only_on_ping"`
  27. }
  28. Config struct {
  29. Mouse bool `toml:"mouse"`
  30. Editor string `toml:"editor"`
  31. HideBlockedUsers bool `toml:"hide_blocked_users"`
  32. ShowAttachmentLinks bool `toml:"show_attachment_links"`
  33. MessagesLimit uint8 `toml:"messages_limit"`
  34. Timestamps bool `toml:"timestamps"`
  35. TimestampsFormat string `toml:"timestamps_format"`
  36. Identify Identify `toml:"identify"`
  37. Notifications Notifications `toml:"notifications"`
  38. Keys Keys `toml:"keys"`
  39. Theme Theme `toml:"theme"`
  40. }
  41. )
  42. func defaultConfig() *Config {
  43. return &Config{
  44. Mouse: true,
  45. Editor: "default",
  46. HideBlockedUsers: true,
  47. ShowAttachmentLinks: true,
  48. MessagesLimit: 50,
  49. Timestamps: false,
  50. TimestampsFormat: time.Kitchen,
  51. Identify: Identify{
  52. Status: discord.OnlineStatus,
  53. Browser: consts.Browser,
  54. BrowserVersion: consts.BrowserVersion,
  55. UserAgent: consts.UserAgent,
  56. },
  57. Notifications: Notifications{
  58. Enabled: true,
  59. Duration: 500,
  60. Sound: Sound{
  61. Enabled: true,
  62. OnlyOnPing: true,
  63. },
  64. },
  65. Keys: defaultKeys(),
  66. Theme: defaultTheme(),
  67. }
  68. }
  69. // Reads the configuration file and parses it.
  70. func Load() (*Config, error) {
  71. path, err := os.UserConfigDir()
  72. if err != nil {
  73. slog.Info("user configuration directory path cannot be determined; falling back to the current directory path")
  74. path = "."
  75. }
  76. path = filepath.Join(path, consts.Name, fileName)
  77. f, err := os.Open(path)
  78. cfg := defaultConfig()
  79. if os.IsNotExist(err) {
  80. slog.Info("the configuration file does not exist, falling back to the default configuration", "path", path, "err", err)
  81. return cfg, nil
  82. }
  83. if err != nil {
  84. return nil, err
  85. }
  86. defer f.Close()
  87. if _, err := toml.NewDecoder(f).Decode(&cfg); err != nil {
  88. return nil, err
  89. }
  90. return cfg, nil
  91. }