subsonic-tui/internal/config/config.go
Sagi Dayan bae2c74815
initial commit
Signed-off-by: Sagi Dayan <sagidayan@gmail.com>
2024-12-14 23:23:29 +02:00

123 lines
2.7 KiB
Go

package config
import (
"encoding/base64"
"fmt"
"os"
"path"
"strings"
"github.com/creasty/defaults"
"gopkg.in/yaml.v3"
)
var configPath string
type _config struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
URL string `yaml:"url"`
EnableScrobble bool `yaml:"enable_scrobble" default:"false"`
MaxRadioSongs int `yaml:"max_radio_songs" default:"50"`
ExperimentalRadioAlgo bool `yaml:"experimental_radio_algo" default:"false"`
}
var configStruct *_config
func init() {
userConfigDir, err := os.UserConfigDir()
configDir := path.Join(userConfigDir, "subsonictui")
configPath = path.Join(configDir, "config.yaml")
if err != nil {
fmt.Printf("[ERROR] Failed to fetch user config directory. %e\n", err)
os.Exit(1)
}
if _, err := os.Stat(configDir); os.IsNotExist(err) {
err := os.MkdirAll(configDir, 0700)
if err != nil {
panic(err)
}
}
var configFile *os.File
if _, err := os.Stat(configPath); os.IsNotExist(err) {
configFile, err = os.Create(configPath)
defer func() {
err := configFile.Close()
if err != nil {
panic(err)
}
}()
if err != nil {
fmt.Printf("[ERROR] Failed to create config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
}
configStruct, err = loadConfig()
if err != nil {
fmt.Printf("[ERROR] Failed to load config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
fmt.Printf("Init Config %s\n", configPath)
}
func URL() string {
return configStruct.URL
}
func Username() string {
return configStruct.Username
}
func Password() string {
p, _ := base64.StdEncoding.DecodeString(configStruct.Password)
return strings.TrimSpace(string(p))
}
func ScrobbleEnabled() bool {
return configStruct.EnableScrobble
}
func MaxRadioSongs() int {
return configStruct.MaxRadioSongs
}
func ExperimentalRadioAlgo() bool {
return configStruct.ExperimentalRadioAlgo
}
func SetPassword(p string) {
configStruct.Password = base64.StdEncoding.EncodeToString([]byte(p))
}
func SetUsername(u string) {
configStruct.Username = u
}
func SetURL(u string) {
configStruct.URL = u
}
func loadConfig() (*_config, error) {
c := &_config{}
err := defaults.Set(c)
if err != nil {
panic(err)
}
file, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(file, c); err != nil {
return nil, err
}
return c, nil
}
func SaveConfig() {
yml, err := yaml.Marshal(configStruct)
if err != nil {
fmt.Printf("[ERROR] Failed to convert config to yaml. %e\n", err)
os.Exit(1)
}
err = os.WriteFile(configPath, yml, 0600)
if err != nil {
fmt.Printf("[ERROR] Failed to save config file @ %s. %e\n", configPath, err)
os.Exit(1)
}
}