internal/config.go
230 lines · 6554 bytes
1package internal
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7 "path/filepath"
8 "reflect"
9 "strconv"
10 "strings"
11)
12
13// CurdConfig struct with field names that match the config keys
14type CurdConfig struct {
15 Player string `config:"Player"`
16 SubsLanguage string `config:"SubsLanguage"`
17 SubOrDub string `config:"SubOrDub"`
18 StoragePath string `config:"StoragePath"`
19 PercentageToMarkComplete int `config:"PercentageToMarkComplete"`
20 NextEpisodePrompt bool `config:"NextEpisodePrompt"`
21 SkipOp bool `config:"SkipOp"`
22 SkipEd bool `config:"SkipEd"`
23 SkipFiller bool `config:"SkipFiller"`
24 ImagePreview bool `config:"ImagePreview"`
25 SkipRecap bool `config:"SkipRecap"`
26 RofiSelection bool `config:"RofiSelection"`
27 CurrentCategory bool `config:"CurrentCategory"`
28 ScoreOnCompletion bool `config:"ScoreOnCompletion"`
29 SaveMpvSpeed bool `config:"SaveMpvSpeed"`
30 DiscordPresence bool `config:"DiscordPresence"`
31}
32
33// Default configuration values as a map
34func defaultConfigMap() map[string]string {
35 return map[string]string{
36 "Player": "mpv",
37 "StoragePath": "$HOME/.local/share/curd",
38 "SubsLanguage": "english",
39 "SubOrDub": "sub",
40 "PercentageToMarkComplete": "85",
41 "NextEpisodePrompt": "false",
42 "SkipOp": "true",
43 "SkipEd": "true",
44 "SkipFiller": "true",
45 "SkipRecap": "true",
46 "RofiSelection": "false",
47 "ImagePreview": "false",
48 "ScoreOnCompletion": "true",
49 "SaveMpvSpeed": "true",
50 "DiscordPresence": "true",
51 }
52}
53
54var globalConfig *CurdConfig
55
56func SetGlobalConfig(config *CurdConfig) {
57 globalConfig = config
58}
59
60func GetGlobalConfig() *CurdConfig {
61 return globalConfig
62}
63
64
65// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
66func LoadConfig(configPath string) (CurdConfig, error) {
67 configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
68
69 // Check if config file exists
70 if _, err := os.Stat(configPath); os.IsNotExist(err) {
71 // Create the config file with default values if it doesn't exist
72 CurdOut("Config file not found. Creating default config...")
73 if err := createDefaultConfig(configPath); err != nil {
74 return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
75 }
76 }
77
78 // Load the config from file
79 configMap, err := loadConfigFromFile(configPath)
80 if err != nil {
81 return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
82 }
83
84 // Add missing fields to the config map
85 updated := false
86 defaultConfigMap := defaultConfigMap()
87 for key, defaultValue := range defaultConfigMap {
88 if _, exists := configMap[key]; !exists {
89 configMap[key] = defaultValue
90 updated = true
91 }
92 }
93
94 // Write updated config back to file if there were any missing fields
95 if updated {
96 if err := saveConfigToFile(configPath, configMap); err != nil {
97 return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
98 }
99 }
100
101 // Populate the CurdConfig struct from the config map
102 config := populateConfig(configMap)
103
104 return config, nil
105}
106
107// Create a config file with default values in key=value format
108// Ensure the directory exists before creating the file
109func createDefaultConfig(path string) error {
110 defaultConfig := defaultConfigMap()
111
112 // Ensure the directory exists
113 dir := filepath.Dir(path)
114 if err := os.MkdirAll(dir, 0755); err != nil {
115 return fmt.Errorf("error creating directory: %v", err)
116 }
117
118 file, err := os.Create(path)
119 if err != nil {
120 return fmt.Errorf("error creating file: %v", err)
121 }
122 defer file.Close()
123
124 writer := bufio.NewWriter(file)
125 for key, value := range defaultConfig {
126 line := fmt.Sprintf("%s=%s\n", key, value)
127 if _, err := writer.WriteString(line); err != nil {
128 return fmt.Errorf("error writing to file: %v", err)
129 }
130 }
131 if err := writer.Flush(); err != nil {
132 return fmt.Errorf("error flushing writer: %v", err)
133 }
134 return nil
135}
136
137func ChangeToken(config *CurdConfig, user *User) {
138 var err error
139 if config.RofiSelection {
140 user.Token, err = GetTokenFromRofi()
141 } else {
142 fmt.Println("Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token")
143 fmt.Scanln(&user.Token)
144 }
145 if err != nil {
146 Log("Error getting user input: "+err.Error(), logFile)
147 ExitCurd(err)
148 }
149 WriteTokenToFile(user.Token, filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
150}
151
152// Load config file from disk into a map (key=value format)
153func loadConfigFromFile(path string) (map[string]string, error) {
154 file, err := os.Open(path)
155 if err != nil {
156 return nil, err
157 }
158 defer file.Close()
159
160 configMap := make(map[string]string)
161 scanner := bufio.NewScanner(file)
162
163 for scanner.Scan() {
164 line := strings.TrimSpace(scanner.Text())
165 if line == "" || strings.HasPrefix(line, "#") {
166 continue // Skip empty lines and comments
167 }
168
169 parts := strings.SplitN(line, "=", 2)
170 if len(parts) == 2 {
171 key := strings.TrimSpace(parts[0])
172 value := strings.TrimSpace(parts[1])
173 configMap[key] = value
174 }
175 }
176
177 if err := scanner.Err(); err != nil {
178 return nil, err
179 }
180
181 return configMap, nil
182}
183
184// Save updated config map to file in key=value format
185func saveConfigToFile(path string, configMap map[string]string) error {
186 file, err := os.Create(path)
187 if err != nil {
188 return err
189 }
190 defer file.Close()
191
192 writer := bufio.NewWriter(file)
193 for key, value := range configMap {
194 line := fmt.Sprintf("%s=%s\n", key, value)
195 if _, err := writer.WriteString(line); err != nil {
196 return err
197 }
198 }
199 return writer.Flush()
200}
201
202// Populate the CurdConfig struct from a map
203func populateConfig(configMap map[string]string) CurdConfig {
204 config := CurdConfig{}
205 configValue := reflect.ValueOf(&config).Elem()
206
207 for i := 0; i < configValue.NumField(); i++ {
208 field := configValue.Type().Field(i)
209 tag := field.Tag.Get("config")
210
211 if value, exists := configMap[tag]; exists {
212 fieldValue := configValue.FieldByName(field.Name)
213
214 if fieldValue.CanSet() {
215 switch fieldValue.Kind() {
216 case reflect.String:
217 fieldValue.SetString(value)
218 case reflect.Int:
219 intVal, _ := strconv.Atoi(value)
220 fieldValue.SetInt(int64(intVal))
221 case reflect.Bool:
222 boolVal, _ := strconv.ParseBool(value)
223 fieldValue.SetBool(boolVal)
224 }
225 }
226 }
227 }
228
229 return config
230}