internal/config.go

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