This repository has been archived by the owner on Nov 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathuser_settings.go
91 lines (82 loc) · 2 KB
/
user_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
90
91
package main
import (
"errors"
"log"
"os"
"path/filepath"
"riftshare/transport"
"runtime"
"gopkg.in/yaml.v2"
)
type UserSettings struct {
Notifications bool `yaml:"notifications"`
Overwrite bool `yaml:"overwrite"`
DownloadsDirectory string `yaml:"downloads_directory"`
}
func SaveUserSettings(settings UserSettings) error {
prefs, err := openPrefFile()
if err != nil {
log.Println(err)
return errors.New("error opening settings file")
}
defer prefs.Close()
encoder := yaml.NewEncoder(prefs)
err = encoder.Encode(settings)
if err != nil {
log.Println(err)
return errors.New("error encoding settings file")
}
return nil
}
func GetUserSettings() (UserSettings, error) {
prefs, err := openPrefFile()
if err != nil {
log.Println(err)
}
defer prefs.Close()
var settings UserSettings
decoder := yaml.NewDecoder(prefs)
err = decoder.Decode(&settings)
if err != nil {
log.Println(err)
}
// Check if file is empty
if settings == (UserSettings{}) {
// Initialize empty settings file
settings = UserSettings{Notifications: false, Overwrite: true, DownloadsDirectory: transport.UserDownloadsFolder()}
}
return settings, nil
}
func getSettingsDirectory() (string, error) {
var err error
homeDir, err := os.UserHomeDir()
prefDir := ""
switch runtime.GOOS {
case "windows":
prefDir = filepath.Join(homeDir, "/AppData/Local/RiftShare")
case "darwin":
prefDir = filepath.Join(homeDir, "/Library/Application Support/RiftShare")
default:
err = errors.New("unsupported platform")
}
return prefDir, err
}
func openPrefFile() (*os.File, error) {
dir, err := getSettingsDirectory()
if err != nil {
log.Println(err)
}
if _, err := os.Stat(dir); os.IsNotExist(err) {
log.Println("No Pref Directory Found, creating..")
err = os.Mkdir(dir, 0777)
if err != nil {
log.Println(err)
}
}
settingsPath := filepath.Join(dir, "riftshare_config.yaml")
prefs, err := os.OpenFile(settingsPath, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
log.Println(err)
}
return prefs, nil
}