internal/config.go

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