sonar/config.go

98 lines
2.5 KiB
Go

package sonar
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/kirsle/configdir"
)
// Config file at ~/.config/sonar.json
var configFile = configdir.LocalConfig("sonar.json")
// Config for the Sonar app.
type Config struct {
CookieName string `json:"cookieName"`
MediaPath string `json:"mediaPath"` // where the playlist media is stored
MediaCommand []string `json:"mediaCommand"` // how to play the media
// Volume commands.
VolumeUpCommand []string `json:"volUpCommand"`
VolumeDownCommand []string `json:"volDnCommand"`
VolumeMuteCommand []string `json:"volMuteCommand"`
VolumeStatusCommand []string `json:"volStatusCommand"`
// Scheduled cron tab.
Hour int `json:"hour"`
Minute int `json:"minute"`
Days []string `json:"days"`
}
// DefaultConfig returns the default config.
func DefaultConfig() *Config {
return &Config{
CookieName: "session",
MediaPath: "./media",
MediaCommand: []string{"mplayer", "%s"},
// Default schedule.
Hour: 6,
Minute: 30,
Days: []string{"1", "2", "3", "4", "5"}, // M-F
// PulseAudio pactl commands.
// pactl set-sink-volume <SINK> -<INT>%
// Find the sink number from: pactl list
VolumeUpCommand: strings.Fields("pactl set-sink-volume 0 +5%"),
VolumeDownCommand: strings.Fields("pactl set-sink-volume 0 -5%"),
VolumeMuteCommand: strings.Fields("pactl set-sink-mute 0 toggle"),
// Get the current volume. TODO: PulseAudio specific. The command
// output is run thru a regexp for `(\d+)%`
VolumeStatusCommand: []string{
"bash", "-c",
`pacmd dump-volumes | grep "Sink 0" | egrep -o '([0-9]+)%' | head -1`,
},
}
}
// LoadConfig loads the config or uses the default.
func LoadConfig() *Config {
filepath := configFile
if _, err := os.Stat(filepath); os.IsNotExist(err) {
log.Warn("No stored config file found (%s); loading default settings", filepath)
cfg := DefaultConfig()
SaveConfig(cfg)
return cfg
}
fh, err := os.Open(filepath)
if err != nil {
log.Error("Error reading config from %s: %s", filepath, err)
return DefaultConfig()
}
defer fh.Close()
log.Info("Reading config from %s", filepath)
var c *Config
decoder := json.NewDecoder(fh)
decoder.Decode(&c)
return c
}
// SaveConfig writes the config file to disk.
func SaveConfig(c *Config) error {
filepath := configFile
fh, err := os.Create(filepath)
if err != nil {
return fmt.Errorf("SaveConfig: %s", err)
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.SetIndent("", "\t")
return encoder.Encode(c)
}