config.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 Config struct {
  13. Mouse bool `toml:"mouse"`
  14. Editor string `toml:"editor"`
  15. HideBlockedUsers bool `toml:"hide_blocked_users"`
  16. ShowAttachmentLinks bool `toml:"show_attachment_links"`
  17. MessagesLimit uint8 `toml:"messages_limit"`
  18. Timestamps bool `toml:"timestamps"`
  19. TimestampsFormat string `toml:"timestamps_format"`
  20. Status discord.Status `toml:"status"`
  21. Browser string `toml:"browser"`
  22. BrowserVersion string `toml:"browser_version"`
  23. UserAgent string `toml:"user_agent"`
  24. Keys Keys `toml:"keys"`
  25. Theme Theme `toml:"theme"`
  26. }
  27. func defaultConfig() *Config {
  28. return &Config{
  29. Mouse: true,
  30. Editor: "default",
  31. HideBlockedUsers: true,
  32. ShowAttachmentLinks: true,
  33. MessagesLimit: 50,
  34. Timestamps: false,
  35. TimestampsFormat: time.Kitchen,
  36. Status: discord.OnlineStatus,
  37. Browser: consts.Browser,
  38. BrowserVersion: consts.BrowserVersion,
  39. UserAgent: consts.UserAgent,
  40. Keys: defaultKeys(),
  41. Theme: defaultTheme(),
  42. }
  43. }
  44. // Reads the configuration file and parses it.
  45. func Load() (*Config, error) {
  46. path, err := os.UserConfigDir()
  47. if err != nil {
  48. slog.Info("user configuration directory path cannot be determined; falling back to the current directory path")
  49. path = "."
  50. }
  51. path = filepath.Join(path, consts.Name, fileName)
  52. f, err := os.Open(path)
  53. cfg := defaultConfig()
  54. if os.IsNotExist(err) {
  55. slog.Info("the configuration file does not exist, falling back to the default configuration", "path", path, "err", err)
  56. return cfg, nil
  57. }
  58. if err != nil {
  59. return nil, err
  60. }
  61. defer f.Close()
  62. if _, err := toml.NewDecoder(f).Decode(&cfg); err != nil {
  63. return nil, err
  64. }
  65. return cfg, nil
  66. }