internal/config.go

333 lines · 9897 bytes

  1package internal
  2
  3import (
  4	"bufio"
  5	"fmt"
  6	"os"
  7	"path/filepath"
  8	"reflect"
  9	"strconv"
 10	"os/exec"
 11	"runtime"
 12	"strings"
 13)
 14
 15// CurdConfig struct with field names that match the config keys
 16type CurdConfig struct {
 17	Player                   string   `config:"Player"`
 18	MpvArgs                  []string `config:MpvArgs`
 19	SubsLanguage             string   `config:"SubsLanguage"`
 20	SubOrDub                 string   `config:"SubOrDub"`
 21	StoragePath              string   `config:"StoragePath"`
 22	AnimeNameLanguage        string   `config:"AnimeNameLanguage"`
 23	PercentageToMarkComplete int      `config:"PercentageToMarkComplete"`
 24	NextEpisodePrompt        bool     `config:"NextEpisodePrompt"`
 25	SkipOp                   bool     `config:"SkipOp"`
 26	SkipEd                   bool     `config:"SkipEd"`
 27	SkipFiller               bool     `config:"SkipFiller"`
 28	ImagePreview             bool     `config:"ImagePreview"`
 29	SkipRecap                bool     `config:"SkipRecap"`
 30	RofiSelection            bool     `config:"RofiSelection"`
 31	CurrentCategory          bool     `config:"CurrentCategory"`
 32	ScoreOnCompletion        bool     `config:"ScoreOnCompletion"`
 33	SaveMpvSpeed             bool     `config:"SaveMpvSpeed"`
 34	AddMissingOptions        bool     `config:"AddMissingOptions"`
 35	AlternateScreen          bool     `config:"AlternateScreen"`
 36	DiscordPresence          bool     `config:"DiscordPresence"`
 37}
 38
 39// Default configuration values as a map
 40func defaultConfigMap() map[string]string {
 41	return map[string]string{
 42		"Player":                   "mpv",
 43		"MpvArgs":                  "[]",
 44		"StoragePath":              "$HOME/.local/share/curd",
 45		"AnimeNameLanguage":        "english",
 46		"SubsLanguage":             "english",
 47		"SubOrDub":                 "sub",
 48		"PercentageToMarkComplete": "85",
 49		"NextEpisodePrompt":        "false",
 50		"SkipOp":                   "true",
 51		"SkipEd":                   "true",
 52		"SkipFiller":               "true",
 53		"SkipRecap":                "true",
 54		"RofiSelection":            "false",
 55		"ImagePreview":             "false",
 56		"ScoreOnCompletion":        "true",
 57		"SaveMpvSpeed":             "true",
 58		"AddMissingOptions":        "true",
 59		"AlternateScreen":          "true",
 60		"DiscordPresence":          "true",
 61	}
 62}
 63
 64var globalConfig *CurdConfig
 65
 66func SetGlobalConfig(config *CurdConfig) {
 67	globalConfig = config
 68}
 69
 70func GetGlobalConfig() *CurdConfig {
 71	return globalConfig
 72}
 73
 74// Helper function to parse string array from config
 75func parseStringArray(value string) []string {
 76	// Remove brackets and split by comma
 77	value = strings.TrimPrefix(value, "[")
 78	value = strings.TrimSuffix(value, "]")
 79	if value == "" {
 80		return nil
 81	}
 82
 83	// Split by comma and trim spaces and quotes from each element
 84	parts := strings.Split(value, ",")
 85	result := make([]string, 0, len(parts))
 86	for _, part := range parts {
 87		// Trim spaces and quotes
 88		part = strings.TrimSpace(part)
 89		part = strings.Trim(part, "\"")
 90		if part != "" {
 91			result = append(result, part)
 92		}
 93	}
 94	return result
 95}
 96
 97// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
 98func LoadConfig(configPath string) (CurdConfig, error) {
 99	configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
100
101	// Check if config file exists
102	if _, err := os.Stat(configPath); os.IsNotExist(err) {
103		// Create the config file with default values if it doesn't exist
104		CurdOut("Config file not found. Creating default config...")
105		if err := createDefaultConfig(configPath); err != nil {
106			return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
107		}
108	}
109
110	// Load the config from file
111	configMap, err := loadConfigFromFile(configPath)
112	if err != nil {
113		return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
114	}
115
116	// Check AddMissingOptions setting first
117	addMissing := true
118	if val, exists := configMap["AddMissingOptions"]; exists {
119		addMissing, _ = strconv.ParseBool(val)
120	}
121
122	// Add missing fields to the config map
123	updated := false
124	defaultConfigMap := defaultConfigMap()
125	for key, defaultValue := range defaultConfigMap {
126		if _, exists := configMap[key]; !exists {
127			configMap[key] = defaultValue
128			updated = true
129		}
130	}
131
132	// Write updated config back to file only if AddMissingOptions is true
133	if addMissing && updated {
134		if err := saveConfigToFile(configPath, configMap); err != nil {
135			return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
136		}
137	}
138
139	// Parse string arrays
140	if mpvArgs, exists := configMap["MpvArgs"]; exists {
141		configMap["MpvArgs"] = mpvArgs
142	}
143
144	// Populate the CurdConfig struct from the config map
145	config := populateConfig(configMap)
146
147	return config, nil
148}
149
150// Create a config file with default values in key=value format
151// Ensure the directory exists before creating the file
152func createDefaultConfig(path string) error {
153	defaultConfig := defaultConfigMap()
154
155	// Ensure the directory exists
156	dir := filepath.Dir(path)
157	if err := os.MkdirAll(dir, 0755); err != nil {
158		return fmt.Errorf("error creating directory: %v", err)
159	}
160
161	file, err := os.Create(path)
162	if err != nil {
163		return fmt.Errorf("error creating file: %v", err)
164	}
165	defer file.Close()
166
167	writer := bufio.NewWriter(file)
168	for key, value := range defaultConfig {
169		line := fmt.Sprintf("%s=%s\n", key, value)
170		if _, err := writer.WriteString(line); err != nil {
171			return fmt.Errorf("error writing to file: %v", err)
172		}
173	}
174	if err := writer.Flush(); err != nil {
175		return fmt.Errorf("error flushing writer: %v", err)
176	}
177	return nil
178}
179
180func getTokenFromTempFile(isWindowsPlatform bool) (string, error) {
181    // Create a temporary file for the token
182    tempFile, err := os.CreateTemp("", "curd-token-*.txt")
183    if err != nil {
184        return "", fmt.Errorf("error creating temp file: %v", err)
185    }
186    tempPath := tempFile.Name()
187    tempFile.Close()
188
189    // Write instructions to the temp file
190    instructions := "Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token\n" +
191        "Replace this text with your token and save the file.\n"
192    if err := os.WriteFile(tempPath, []byte(instructions), 0644); err != nil {
193        return "", fmt.Errorf("error writing instructions: %v", err)
194    }
195
196    // Open the file with appropriate editor
197    var cmd *exec.Cmd
198    if isWindowsPlatform {
199        cmd = exec.Command("notepad.exe", tempPath)
200    } else {
201        editor := os.Getenv("EDITOR")
202        if editor == "" {
203            editor = "nano" // Default to nano if $EDITOR is not set
204        }
205        cmd = exec.Command(editor, tempPath)
206        cmd.Stdin = os.Stdin
207        cmd.Stdout = os.Stdout
208        cmd.Stderr = os.Stderr
209    }
210
211    if err := cmd.Run(); err != nil {
212        return "", fmt.Errorf("error opening editor: %v", err)
213    }
214
215    // Read the token from the file
216    content, err := os.ReadFile(tempPath)
217    if err != nil {
218        return "", fmt.Errorf("error reading token: %v", err)
219    }
220
221    // Clean up the temp file
222    os.Remove(tempPath)
223
224    // Extract token (remove instructions and whitespace)
225    return strings.TrimSpace(string(content)), nil
226}
227
228func ChangeToken(config *CurdConfig, user *User) {
229    var err error
230    tokenPath := filepath.Join(os.ExpandEnv(config.StoragePath), "token")
231
232    switch {
233    case runtime.GOOS == "darwin" || runtime.GOOS == "windows":
234        user.Token, err = getTokenFromTempFile(runtime.GOOS == "windows")
235    case config.RofiSelection:
236        user.Token, err = GetTokenFromRofi()
237    default:
238        fmt.Println("Please generate a token from https://anilist.co/api/v2/oauth/authorize?client_id=20686&response_type=token")
239        fmt.Scanln(&user.Token)
240    }
241
242    if err != nil {
243        Log("Error getting user input: "+err.Error())
244        ExitCurd(err)
245    }
246
247    WriteTokenToFile(user.Token, tokenPath)
248}
249
250// Load config file from disk into a map (key=value format)
251func loadConfigFromFile(path string) (map[string]string, error) {
252	file, err := os.Open(path)
253	if err != nil {
254		return nil, err
255	}
256	defer file.Close()
257
258	configMap := make(map[string]string)
259	scanner := bufio.NewScanner(file)
260
261	for scanner.Scan() {
262		line := strings.TrimSpace(scanner.Text())
263		if line == "" || strings.HasPrefix(line, "#") {
264			continue // Skip empty lines and comments
265		}
266
267		parts := strings.SplitN(line, "=", 2)
268		if len(parts) == 2 {
269			key := strings.TrimSpace(parts[0])
270			value := strings.TrimSpace(parts[1])
271			configMap[key] = value
272		}
273	}
274
275	if err := scanner.Err(); err != nil {
276		return nil, err
277	}
278
279	return configMap, nil
280}
281
282// Save updated config map to file in key=value format
283func saveConfigToFile(path string, configMap map[string]string) error {
284	file, err := os.Create(path)
285	if err != nil {
286		return err
287	}
288	defer file.Close()
289
290	writer := bufio.NewWriter(file)
291	for key, value := range configMap {
292		line := fmt.Sprintf("%s=%s\n", key, value)
293		if _, err := writer.WriteString(line); err != nil {
294			return err
295		}
296	}
297	return writer.Flush()
298}
299
300// Populate the CurdConfig struct from a map
301func populateConfig(configMap map[string]string) CurdConfig {
302	config := CurdConfig{}
303	configValue := reflect.ValueOf(&config).Elem()
304
305	for i := 0; i < configValue.NumField(); i++ {
306		field := configValue.Type().Field(i)
307		tag := field.Tag.Get("config")
308
309		if value, exists := configMap[tag]; exists {
310			fieldValue := configValue.FieldByName(field.Name)
311
312			if fieldValue.CanSet() {
313				switch fieldValue.Kind() {
314				case reflect.String:
315					fieldValue.SetString(value)
316				case reflect.Int:
317					intVal, _ := strconv.Atoi(value)
318					fieldValue.SetInt(int64(intVal))
319				case reflect.Bool:
320					boolVal, _ := strconv.ParseBool(value)
321					fieldValue.SetBool(boolVal)
322				}
323			}
324		}
325	}
326
327	// Handle MpvArgs specially
328	if mpvArgs, exists := configMap["MpvArgs"]; exists {
329		config.MpvArgs = parseStringArray(mpvArgs)
330	}
331
332	return config
333}