internal/config.go
232 lines · 6647 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 if config.RofiSelection {
142 user.Token, err = GetTokenFromRofi()
143 } else {
144 fmt.Println("Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token")
145 fmt.Scanln(&user.Token)
146 }
147 if err != nil {
148 Log("Error getting user input: "+err.Error(), logFile)
149 ExitCurd(err)
150 }
151 WriteTokenToFile(user.Token, filepath.Join(os.ExpandEnv(config.StoragePath), "token"))
152}
153
154// Load config file from disk into a map (key=value format)
155func loadConfigFromFile(path string) (map[string]string, error) {
156 file, err := os.Open(path)
157 if err != nil {
158 return nil, err
159 }
160 defer file.Close()
161
162 configMap := make(map[string]string)
163 scanner := bufio.NewScanner(file)
164
165 for scanner.Scan() {
166 line := strings.TrimSpace(scanner.Text())
167 if line == "" || strings.HasPrefix(line, "#") {
168 continue // Skip empty lines and comments
169 }
170
171 parts := strings.SplitN(line, "=", 2)
172 if len(parts) == 2 {
173 key := strings.TrimSpace(parts[0])
174 value := strings.TrimSpace(parts[1])
175 configMap[key] = value
176 }
177 }
178
179 if err := scanner.Err(); err != nil {
180 return nil, err
181 }
182
183 return configMap, nil
184}
185
186// Save updated config map to file in key=value format
187func saveConfigToFile(path string, configMap map[string]string) error {
188 file, err := os.Create(path)
189 if err != nil {
190 return err
191 }
192 defer file.Close()
193
194 writer := bufio.NewWriter(file)
195 for key, value := range configMap {
196 line := fmt.Sprintf("%s=%s\n", key, value)
197 if _, err := writer.WriteString(line); err != nil {
198 return err
199 }
200 }
201 return writer.Flush()
202}
203
204// Populate the CurdConfig struct from a map
205func populateConfig(configMap map[string]string) CurdConfig {
206 config := CurdConfig{}
207 configValue := reflect.ValueOf(&config).Elem()
208
209 for i := 0; i < configValue.NumField(); i++ {
210 field := configValue.Type().Field(i)
211 tag := field.Tag.Get("config")
212
213 if value, exists := configMap[tag]; exists {
214 fieldValue := configValue.FieldByName(field.Name)
215
216 if fieldValue.CanSet() {
217 switch fieldValue.Kind() {
218 case reflect.String:
219 fieldValue.SetString(value)
220 case reflect.Int:
221 intVal, _ := strconv.Atoi(value)
222 fieldValue.SetInt(int64(intVal))
223 case reflect.Bool:
224 boolVal, _ := strconv.ParseBool(value)
225 fieldValue.SetBool(boolVal)
226 }
227 }
228 }
229 }
230
231 return config
232}