config.go 2.0 KB

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