internal/config.go

387 lines · 11448 bytes · executable

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