summaryrefslogtreecommitdiff
path: root/config.go
blob: 44d6892e7d911c7899ef42b36afacb9438fe7891 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main

import (
	"encoding/json"
	"io"
	"net"
	"os"
	"path/filepath"
)

const configPathRelative = `.config/soundbox/config.json`

type Config struct {
	Soundboxes []struct {
		Name    string
		Mac     net.HardwareAddr
		Enabled bool
	}
	URLs []struct {
		Name string
		Url  string
	}
}

func (config *Config) UnmarshalJSON(data []byte) error {
	var buffer struct {
		Soundboxes []struct {
			Name    string
			Mac     string
			Enabled bool
		}
		URLs []struct {
			Name string
			Url  string
		}
	}

	err := json.Unmarshal(data, &buffer)
	if err != nil {
		return err
	}

	parsed := Config{}

	for _, soundbox := range buffer.Soundboxes {
		hwAddr, err := net.ParseMAC(soundbox.Mac)
		if err != nil {
			return err
		}
		parsed.Soundboxes = append(parsed.Soundboxes, struct {
			Name    string
			Mac     net.HardwareAddr
			Enabled bool
		}{soundbox.Name, hwAddr, soundbox.Enabled})
	}

	for _, url := range buffer.URLs {
		parsed.URLs = append(parsed.URLs, struct {
			Name string
			Url  string
		}{url.Name, url.Url})
	}

	*config = parsed
	return nil
}

func loadConfig() (Config, error) {
	home, err := os.UserHomeDir()
	if err != nil {
		return Config{}, err
	}

	path := filepath.Join(home, configPathRelative)

	file, err := os.Open(path)
	if err != nil {
		return Config{}, err
	}
	defer file.Close()

	bytes, err := io.ReadAll(file)
	if err != nil {
		return Config{}, err
	}

	var config Config
	err = json.Unmarshal(bytes, &config)
	if err != nil {
		return Config{}, err
	}

	return config, nil
}