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