From 39923074f26e1e887e11c90c86e5ec27412ed720 Mon Sep 17 00:00:00 2001 From: ayntgl Date: Sun, 22 May 2022 21:31:32 +0400 Subject: [PATCH] refactor!(config): use os.OpenFile() instead --- config/config.go | 126 +++++++++++++++++++++++++++++++++++++--------- config/general.go | 49 ------------------ config/keys.go | 33 ------------ config/theme.go | 15 ------ main.go | 8 ++- ui/app.go | 8 +-- ui/builder.go | 2 +- ui/channels.go | 2 +- ui/messages.go | 2 +- 9 files changed, 115 insertions(+), 130 deletions(-) delete mode 100644 config/general.go delete mode 100644 config/keys.go delete mode 100644 config/theme.go diff --git a/config/config.go b/config/config.go index 5857048..f43abc4 100644 --- a/config/config.go +++ b/config/config.go @@ -1,56 +1,134 @@ package config import ( + "log" "os" "path/filepath" + "runtime" "github.com/BurntSushi/toml" ) +type IdentifyConfig struct { + UserAgent string `toml:"user_agent"` + Os string `toml:"os"` + Browser string `toml:"browser"` +} + +type KeysConfig struct { + ToggleGuildsList string `toml:"toggle_guilds_list"` + ToggleChannelsTreeView string `toml:"toggle_channels_tree_view"` + ToggleMessagesTextView string `toml:"toggle_messages_text_view"` + ToggleMessageInputField string `toml:"toggle_message_input_field"` + + OpenMessageActionsList string `toml:"open_message_actions_list"` + OpenExternalEditor string `toml:"open_external_editor"` + + SelectPreviousMessage string `toml:"select_previous_message"` + SelectNextMessage string `toml:"select_next_message"` + SelectFirstMessage string `toml:"select_first_message"` + SelectLastMessage string `toml:"select_last_message"` +} + +type ThemeConfig struct { + Background string `toml:"background"` + Border string `toml:"border"` + Title string `toml:"title"` +} + type Config struct { - General GeneralConfig `toml:"general"` - Theme ThemeConfig `toml:"theme"` - Keys KeysConfig `toml:"keys"` + Mouse bool `toml:"mouse"` + Timestamps bool `toml:"timestamps"` + MessagesLimit int `toml:"messages_limit"` + AttachmentDownloadsDir string `toml:"attachment_downloads_dir"` + Identify IdentifyConfig `toml:"identify"` + Theme ThemeConfig `toml:"theme"` + Keys KeysConfig `toml:"keys"` } func New() *Config { return &Config{ - General: newGeneralConfig(), - Theme: newThemeConfig(), - Keys: newKeysConfig(), + Mouse: true, + Timestamps: false, + MessagesLimit: 50, + AttachmentDownloadsDir: UserDownloadsDir(), + Identify: IdentifyConfig{ + UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36", + Os: "Linux", + Browser: "Chrome", + }, + Theme: ThemeConfig{ + Background: "black", + Border: "white", + Title: "white", + }, + Keys: KeysConfig{ + ToggleGuildsList: "Rune[g]", + ToggleChannelsTreeView: "Rune[c]", + ToggleMessagesTextView: "Rune[m]", + ToggleMessageInputField: "Rune[i]", + + OpenMessageActionsList: "Rune[a]", + OpenExternalEditor: "Ctrl+E", + + SelectPreviousMessage: "Up", + SelectNextMessage: "Down", + SelectFirstMessage: "Home", + SelectLastMessage: "End", + }, } } -func (c *Config) Load(path string) { +func (c *Config) Load(path string) error { + // Create directories that do not exist and are mentioned in the path recursively. err := os.MkdirAll(filepath.Dir(path), os.ModePerm) if err != nil { - panic(err) + return err } - if _, err = os.Stat(path); os.IsNotExist(err) { - f, err := os.Create(path) - if err != nil { - panic(err) - } - - err = toml.NewEncoder(f).Encode(c) - if err != nil { - panic(err) - } - } else { - _, err = toml.DecodeFile(path, &c) - if err != nil { - panic(err) - } + // If the configuration file does not exist already, create a new file; otherwwise, open the existing file with read-write flag. + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModePerm) + if err != nil { + return err } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return err + } + + // If the file is empty (the size of the file is zero), write the dedfault configuration to the file. + if fi.Size() == 0 { + return toml.NewEncoder(f).Encode(c) + } + + _, err = toml.NewDecoder(f).Decode(&c) + return err } func DefaultPath() string { path, err := os.UserConfigDir() if err != nil { - panic(err) + log.Fatal(err) } path += "/discordo/config.toml" return path } + +func UserDownloadsDir() string { + // We try to set the download folder location to the default Downloads folder + var dlloc string + if runtime.GOOS == "windows" { + h, _ := os.UserHomeDir() + dlloc = h + "\\Downloads" + } else if runtime.GOOS == "linux" || runtime.GOOS == "darwin" { + h, _ := os.UserHomeDir() + dlloc = h + "/Downloads" + } else { + dlloc = os.TempDir() // Very lame fallback, I know + } + + return dlloc +} diff --git a/config/general.go b/config/general.go deleted file mode 100644 index 2d0dc44..0000000 --- a/config/general.go +++ /dev/null @@ -1,49 +0,0 @@ -package config - -import ( - "os" - "runtime" -) - -type IdentifyConfig struct { - Os string `toml:"os"` - Browser string `toml:"browser"` -} - -type GeneralConfig struct { - UserAgent string `toml:"user_agent"` - FetchMessagesLimit int `toml:"fetch_messages_limit"` - Mouse bool `toml:"mouse"` - Timestamps bool `toml:"timestamps"` - Identify IdentifyConfig `toml:"identify"` - AttachmentDownloadsDir string `toml:"attachment_downloads_dir"` -} - -func newGeneralConfig() GeneralConfig { - return GeneralConfig{ - UserAgent: "Mozilla/5.0 (X11; Linux x86_64; rv:97.0) Gecko/20100101 Firefox/97.0", - FetchMessagesLimit: 50, - Mouse: true, - Timestamps: false, - AttachmentDownloadsDir: UserDownloadsDir(), - Identify: IdentifyConfig{ - Os: "Linux", - Browser: "Firefox", - }, - } -} - -func UserDownloadsDir() string { - // We try to set the download folder location to the default Downloads folder - var dlloc string - if runtime.GOOS == "windows" { - h, _ := os.UserHomeDir() - dlloc = h + "\\Downloads" - } else if runtime.GOOS == "linux" || runtime.GOOS == "darwin" { - h, _ := os.UserHomeDir() - dlloc = h + "/Downloads" - } else { - dlloc = os.TempDir() // Very lame fallback, I know - } - return dlloc -} diff --git a/config/keys.go b/config/keys.go deleted file mode 100644 index 62dfa98..0000000 --- a/config/keys.go +++ /dev/null @@ -1,33 +0,0 @@ -package config - -type KeysConfig struct { - ToggleGuildsList string `toml:"toggle_guilds_list"` - ToggleChannelsTreeView string `toml:"toggle_channels_tree_view"` - ToggleMessagesTextView string `toml:"toggle_messages_text_view"` - ToggleMessageInputField string `toml:"toggle_message_input_field"` - - OpenMessageActionsList string `toml:"open_message_actions_list"` - OpenExternalEditor string `toml:"open_external_editor"` - - SelectPreviousMessage string `toml:"select_previous_message"` - SelectNextMessage string `toml:"select_next_message"` - SelectFirstMessage string `toml:"select_first_message"` - SelectLastMessage string `toml:"select_last_message"` -} - -func newKeysConfig() KeysConfig { - return KeysConfig{ - ToggleGuildsList: "Rune[g]", - ToggleChannelsTreeView: "Rune[c]", - ToggleMessagesTextView: "Rune[m]", - ToggleMessageInputField: "Rune[i]", - - OpenMessageActionsList: "Rune[a]", - OpenExternalEditor: "Ctrl+E", - - SelectPreviousMessage: "Up", - SelectNextMessage: "Down", - SelectFirstMessage: "Home", - SelectLastMessage: "End", - } -} diff --git a/config/theme.go b/config/theme.go deleted file mode 100644 index 4139122..0000000 --- a/config/theme.go +++ /dev/null @@ -1,15 +0,0 @@ -package config - -type ThemeConfig struct { - Background string `toml:"background"` - Border string `toml:"border"` - Title string `toml:"title"` -} - -func newThemeConfig() ThemeConfig { - return ThemeConfig{ - Background: "black", - Border: "white", - Title: "white", - } -} diff --git a/main.go b/main.go index 3b0b220..3e99d67 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "log" "os" "github.com/ayntgl/discordo/config" @@ -42,7 +43,10 @@ func main() { cliApp.Action = func(ctx *cli.Context) error { c := config.New() - c.Load(ctx.String("config")) + err := c.Load(ctx.String("config")) + if err != nil { + log.Fatal(err) + } token := ctx.String("token") app := ui.NewApp(token, c) @@ -128,7 +132,7 @@ func main() { tview.Styles.BorderColor = tcell.GetColor(app.Config.Theme.Border) tview.Styles.TitleColor = tcell.GetColor(app.Config.Theme.Title) - err := app.Run() + err = app.Run() if err != nil { panic(err) } diff --git a/ui/app.go b/ui/app.go index e6e762a..832b189 100644 --- a/ui/app.go +++ b/ui/app.go @@ -37,7 +37,7 @@ func NewApp(token string, c *config.Config) *App { app.MessageInputField = NewMessageInputField(app) app.Application = tview.NewApplication() - app.EnableMouse(app.Config.General.Mouse) + app.EnableMouse(app.Config.Mouse) app.SetInputCapture(app.onInputCapture) return app @@ -47,13 +47,13 @@ func (app *App) Connect() error { // For user accounts, all of the guilds, the user is in, are dispatched in the READY gateway event. // Whereas, for bot accounts, the guilds are dispatched discretely in the GUILD_CREATE gateway events. if !strings.HasPrefix(app.Session.Identify.Token, "Bot") { - app.Session.UserAgent = app.Config.General.UserAgent + app.Session.UserAgent = app.Config.Identify.UserAgent app.Session.Identify.Compress = false app.Session.Identify.LargeThreshold = 0 app.Session.Identify.Intents = 0 app.Session.Identify.Properties = astatine.IdentifyProperties{ - OS: app.Config.General.Identify.Os, - Browser: app.Config.General.Identify.Browser, + OS: app.Config.Identify.Os, + Browser: app.Config.Identify.Browser, } app.Session.AddHandlerOnce(app.onSessionReady) } diff --git a/ui/builder.go b/ui/builder.go index 7a6c203..98a7c8c 100644 --- a/ui/builder.go +++ b/ui/builder.go @@ -23,7 +23,7 @@ func buildMessage(app *App, m *astatine.Message) []byte { // Build the message associated with crosspost, channel follow add, pin, or a reply. buildReferencedMessage(&b, m.ReferencedMessage, app.Session.State.User.ID) - if app.Config.General.Timestamps { + if app.Config.Timestamps { b.WriteString("[::d]") b.WriteString(m.Timestamp.Format(time.Stamp)) b.WriteString("[::-]") diff --git a/ui/channels.go b/ui/channels.go index b45efd4..827a089 100644 --- a/ui/channels.go +++ b/ui/channels.go @@ -55,7 +55,7 @@ func (ctv *ChannelsTreeView) onSelected(n *tview.TreeNode) { ctv.app.MessagesTextView.SetTitle(title) go func() { - ms, err := ctv.app.Session.ChannelMessages(c.ID, ctv.app.Config.General.FetchMessagesLimit, "", "", "") + ms, err := ctv.app.Session.ChannelMessages(c.ID, ctv.app.Config.MessagesLimit, "", "", "") if err != nil { return } diff --git a/ui/messages.go b/ui/messages.go index 7b32467..6ce9a4e 100644 --- a/ui/messages.go +++ b/ui/messages.go @@ -203,7 +203,7 @@ func (mtv *MessagesTextView) onInputCapture(e *tcell.EventKey) *tcell.EventKey { func (mtv *MessagesTextView) downloadAttachment(as []*astatine.MessageAttachment) error { for _, a := range as { - f, err := os.Create(filepath.Join(mtv.app.Config.General.AttachmentDownloadsDir, a.Filename)) + f, err := os.Create(filepath.Join(mtv.app.Config.AttachmentDownloadsDir, a.Filename)) if err != nil { return err }