config.go 2.2 KB

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