config.go

 1package config
 2
 3import (
 4	"encoding/json"
 5	"os"
 6	"path/filepath"
 7)
 8
 9// Config stores the user's email configuration.
10type Config struct {
11	ServiceProvider string `json:"service_provider"`
12	Email           string `json:"email"`
13	Password        string `json:"password"`
14	Name            string `json:"name"`
15}
16
17// configDir returns the path to the configuration directory.
18func configDir() (string, error) {
19	home, err := os.UserHomeDir()
20	if err != nil {
21		return "", err
22	}
23	return filepath.Join(home, ".config", "matcha"), nil
24}
25
26// configFile returns the full path to the configuration file.
27func configFile() (string, error) {
28	dir, err := configDir()
29	if err != nil {
30		return "", err
31	}
32	return filepath.Join(dir, "config.json"), nil
33}
34
35// SaveConfig saves the given configuration to the config file.
36func SaveConfig(config *Config) error {
37	path, err := configFile()
38	if err != nil {
39		return err
40	}
41	if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
42		return err
43	}
44	data, err := json.MarshalIndent(config, "", "  ")
45	if err != nil {
46		return err
47	}
48	return os.WriteFile(path, data, 0600)
49}
50
51// LoadConfig loads the configuration from the config file.
52func LoadConfig() (*Config, error) {
53	path, err := configFile()
54	if err != nil {
55		return nil, err
56	}
57	data, err := os.ReadFile(path)
58	if err != nil {
59		return nil, err
60	}
61	var config Config
62	if err := json.Unmarshal(data, &config); err != nil {
63		return nil, err
64	}
65	return &config, nil
66}
67
68// IMAPServer returns the IMAP server address based on the service provider.
69// This is used to connect to the email provider's IMAP server.
70// It returns an empty string if the service provider is not supported.
71func (c *Config) IMAPServer() string {
72	switch c.ServiceProvider {
73	case "gmail":
74		return "imap.gmail.com"
75	case "icloud":
76		return "imap.mail.me.com"
77	// Add other providers here
78	default:
79		return ""
80	}
81}