internal/config.go

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