config.go
2327 bytes
1package config
2
3import (
4 "fmt"
5 "os"
6 "strings"
7 "time"
8
9 flags "github.com/jessevdk/go-flags"
10)
11
12type Config struct {
13 Dev bool `long:"dev" env:"DEV"`
14 Port int `long:"port" env:"PORT" default:"8080"`
15 DBURI string `long:"db-uri" env:"DB_URI"`
16 AuthToken string `long:"auth-token" env:"AUTH_TOKEN"`
17 YouTubeAPIKey string `long:"youtube-api-key" env:"YOUTUBE_API_KEY"`
18 DownloadsDir string `long:"downloads-dir" env:"DOWNLOADS_DIR" default:"/var/lib/ytrssil/downloads"`
19 YTDLPCookiesFile string `long:"ytdlp-cookies-file" env:"YTDLP_COOKIES_FILE"`
20 FetchInterval time.Duration `long:"fetch-interval" env:"FETCH_INTERVAL" default:"5m"`
21 CleanupInterval time.Duration `long:"cleanup-interval" env:"CLEANUP_INTERVAL" default:"1h"`
22 CleanupAge time.Duration `long:"cleanup-age" env:"CLEANUP_AGE" default:"48h"`
23}
24
25func getenvOrDefault(key string, defaultValue string) string {
26 value, found := os.LookupEnv(key)
27 if found {
28 return value
29 }
30
31 return defaultValue
32}
33
34// Parse parses all the supplied configurations and returns
35func Parse() (Config, error) {
36 var config Config
37 parser := flags.NewParser(&config, flags.Default)
38 _, err := parser.Parse()
39 if err != nil {
40 return config, err
41 }
42
43 if config.AuthToken == "" {
44 return config, fmt.Errorf("missing AUTH_TOKEN env var")
45 }
46 if config.YouTubeAPIKey == "" {
47 return config, fmt.Errorf("missing YOUTUBE_API_KEY env var")
48 }
49
50 if config.DownloadsDir == "" {
51 return config, fmt.Errorf("missing DOWNLOADS_DIR env var")
52 }
53 if err := os.MkdirAll(config.DownloadsDir, 0o755); err != nil {
54 return config, fmt.Errorf("failed to create downloads directory: %w", err)
55 }
56
57 return config, nil
58}
59
60// TestConfig returns a mostly hardcoded configuration used for running tests
61func TestConfig() Config {
62 dbURI := getenvOrDefault("DB_URI", "postgres://ytrssil:ytrssil@localhost:5432/ytrssil?sslmode=disable")
63 if !strings.Contains(dbURI, "sslmode") {
64 dbURI = dbURI + "?sslmode=disable"
65 }
66
67 config := Config{
68 Port: 8080,
69 DBURI: dbURI,
70 AuthToken: "foo",
71 DownloadsDir: "/tmp/ytrssil-test-downloads",
72 FetchInterval: 5 * time.Minute,
73 CleanupInterval: 1 * time.Hour,
74 CleanupAge: 48 * time.Hour,
75 }
76
77 return config
78}