95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
package config
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
)
|
|
|
|
type Config struct {
|
|
ClientID string `json:"client_id"`
|
|
MusicFolders []string `json:"music_folders"`
|
|
}
|
|
|
|
func getConfigPath() string {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return filepath.Join(home, ".config", "mpv-discord-rpc", "config.json")
|
|
}
|
|
|
|
func loadConfig() (*Config, error) {
|
|
configPath := getConfigPath()
|
|
|
|
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("config file not found at %s\nExample config was created, fill in the values\n", configPath)
|
|
}
|
|
|
|
file, err := os.Open(configPath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open config file: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
var config Config
|
|
decoder := json.NewDecoder(file)
|
|
if err := decoder.Decode(&config); err != nil {
|
|
return nil, fmt.Errorf("failed to parse config file: %w", err)
|
|
}
|
|
|
|
if config.ClientID == "" {
|
|
return nil, fmt.Errorf("client_id is empty in config file")
|
|
}
|
|
|
|
return &config, nil
|
|
}
|
|
|
|
func createExampleConfig() error {
|
|
configPath := getConfigPath()
|
|
configDir := filepath.Dir(configPath)
|
|
|
|
// Create directory if it doesn't exist
|
|
if err := os.MkdirAll(configDir, 0755); err != nil {
|
|
return fmt.Errorf("failed to create config directory: %w", err)
|
|
}
|
|
|
|
// Create example config
|
|
exampleConfig := Config{
|
|
ClientID: "your_discord_application_id_here",
|
|
MusicFolders: []string{
|
|
"folder1",
|
|
"folder2",
|
|
},
|
|
}
|
|
|
|
file, err := os.Create(configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create config file: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
encoder := json.NewEncoder(file)
|
|
encoder.SetIndent("", " ")
|
|
if err := encoder.Encode(exampleConfig); err != nil {
|
|
return fmt.Errorf("failed to write config file: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func GetConfig() (*Config, error) {
|
|
config, err := loadConfig()
|
|
if err != nil {
|
|
fmt.Printf("Error: %v\n", err)
|
|
fmt.Printf("\nConfig file location: %s\n", getConfigPath())
|
|
createExampleConfig()
|
|
os.Exit(1)
|
|
}
|
|
fmt.Println("✓ Config loaded")
|
|
fmt.Printf("Client ID: %s\n", config.ClientID)
|
|
|
|
return config, err
|
|
}
|