internal/config.go

382 lines · 11146 bytes

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