-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
settings.go
89 lines (74 loc) · 2.48 KB
/
settings.go
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
package globals
import (
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
)
const (
UsrDir = "usr"
CredFileName = "cred"
ConfigFileName = "usr_config.json"
)
// The following are defaults for user configuration.
var (
DownloadDir = "downloads"
Languages = []string{"en"}
DownloadQuality = "data"
)
// UserConfig : This struct contains information for user configurable settings.
type UserConfig struct {
DownloadDir string `json:"downloadDir"`
Languages []string `json:"languages"`
DownloadQuality string `json:"downloadQuality"`
ForcePort443 bool `json:"forcePort443"`
}
// LoadUserConfiguration : Reads any user configuration settings and will create a default one if it does not exist.
func LoadUserConfiguration() error {
// Path to user configuration file.
confPath := filepath.Join(UsrDir, ConfigFileName)
// Attempt to read user configuration file.
if confBytes, err := ioutil.ReadFile(confPath); err != nil { // If error, assume file does not exist.
// Set defaults and save new configuration.
SetDefaultConfigurations()
return SaveConfiguration(confPath)
} else if err = json.Unmarshal(confBytes, &Conf); err != nil { // If no error reading, then unmarshal.
return err
}
// Check for defaults
SetDefaultConfigurations()
// Expand any environment variables in the user provided string
Conf.DownloadDir = os.ExpandEnv(Conf.DownloadDir)
// Save the config file.
return SaveConfiguration(confPath)
}
// SaveConfiguration : Save user configuration.
func SaveConfiguration(path string) error {
// Format JSON properly for user.
confBytes, err := json.MarshalIndent(&Conf, "", "\t")
if err != nil {
return err
}
// Make sure `usr` directory exists. If it already exists, then nothing is done.
if err = os.MkdirAll(UsrDir, os.ModePerm); err != nil {
return err
}
return ioutil.WriteFile(path, confBytes, os.ModePerm)
}
// SetDefaultConfigurations : Sets default configurations.
func SetDefaultConfigurations() {
// Set default download directory if not set.
if Conf.DownloadDir == "" {
Conf.DownloadDir = DownloadDir
}
// Set default language if not set.
if len(Conf.Languages) == 0 {
Conf.Languages = Languages
}
// ForcePort443 is false by default.
// Set default download quality.
// Will automatically set to `data` if invalid or no download quality specified.
if Conf.DownloadQuality == "" || (Conf.DownloadQuality != "data" && Conf.DownloadQuality != "data-saver") {
Conf.DownloadQuality = DownloadQuality
}
}