// Package config loads the bot configuration. // // Order of precedence, lowest to highest: built-in defaults, an optional TOML // file, environment variables. Secrets are expected to arrive through the // environment (or a .env file that is not committed). package config import ( "bufio" "errors" "fmt" "os" "reflect" "strconv" "strings" "time" "github.com/BurntSushi/toml" ) // Duration is a time.Duration that can be read from TOML and env as "10m". type Duration time.Duration // UnmarshalText implements encoding.TextUnmarshaler. func (d *Duration) UnmarshalText(b []byte) error { v, err := time.ParseDuration(strings.TrimSpace(string(b))) if err != nil { return err } *d = Duration(v) return nil } // D returns the value as a time.Duration. func (d Duration) D() time.Duration { return time.Duration(d) } // Config is the full configuration of the core binary. type Config struct { Telegram Telegram `toml:"telegram"` HTTP HTTP `toml:"http"` Database Database `toml:"database"` Storage Storage `toml:"storage"` Worker Worker `toml:"worker"` Queue Queue `toml:"queue"` Limits Limits `toml:"limits"` Log Log `toml:"log"` // Owners are the Telegram user IDs allowed to use owner commands. Owners []int64 `toml:"owners" env:"OWNER_IDS"` } // Telegram holds the Bot API settings. type Telegram struct { Token string `toml:"token" env:"BOT_TOKEN"` // APIURL is the Bot API root. Point it at a local Bot API server to lift // the upload limit to 2 GB. APIURL string `toml:"api_url" env:"TELEGRAM_API_URL"` // Mode is "polling" (default) or "webhook". Mode string `toml:"mode" env:"TELEGRAM_MODE"` WebhookURL string `toml:"webhook_url" env:"WEBHOOK_URL"` WebhookSecret string `toml:"webhook_secret" env:"WEBHOOK_SECRET"` // MaxUploadMB is the largest file the bot can send. 50 on the cloud Bot // API, up to 2000 with a local Bot API server. MaxUploadMB int64 `toml:"max_upload_mb" env:"TELEGRAM_MAX_UPLOAD_MB"` // UpdateWorkers is the number of goroutines that handle updates. UpdateWorkers int `toml:"update_workers" env:"TELEGRAM_UPDATE_WORKERS"` } // HTTP holds the settings of the embedded HTTP server. type HTTP struct { Listen string `toml:"listen" env:"HTTP_LISTEN"` } // Database selects the SQL backend. type Database struct { // Driver is "sqlite" or "postgres". Driver string `toml:"driver" env:"DB_DRIVER"` // DSN is a file path for sqlite or a connection URL for postgres. DSN string `toml:"dsn" env:"DB_DSN"` } // Storage selects the file storage backend. type Storage struct { // Backend is "local" or "s3". Backend string `toml:"backend" env:"STORAGE_BACKEND"` LocalDir string `toml:"local_dir" env:"STORAGE_LOCAL_DIR"` } // Worker holds the settings of the download worker. type Worker struct { // Embedded runs a worker inside the core process. Embedded bool `toml:"embedded" env:"WORKER_EMBEDDED"` Concurrency int `toml:"concurrency" env:"WORKER_CONCURRENCY"` TempDir string `toml:"temp_dir" env:"WORKER_TEMP_DIR"` YtDlpPath string `toml:"ytdlp_path" env:"YTDLP_PATH"` FfmpegPath string `toml:"ffmpeg_path" env:"FFMPEG_PATH"` // DownloadTimeout is the hard cap for one download attempt. DownloadTimeout Duration `toml:"download_timeout" env:"DOWNLOAD_TIMEOUT"` // ProbeTimeout is the cap for one metadata lookup. ProbeTimeout Duration `toml:"probe_timeout" env:"PROBE_TIMEOUT"` ProbeConcurrency int `toml:"probe_concurrency" env:"PROBE_CONCURRENCY"` } // Queue holds scheduler settings. type Queue struct { // FreeMaxLen is the largest number of queued free jobs accepted. FreeMaxLen int `toml:"free_max_len" env:"QUEUE_FREE_MAX_LEN"` // Lease is how long a claimed job stays owned without a heartbeat. Lease Duration `toml:"lease" env:"QUEUE_LEASE"` // Heartbeat is how often a worker extends its lease. Heartbeat Duration `toml:"heartbeat" env:"QUEUE_HEARTBEAT"` // MaxAttempts is the number of tries per job (2 means one retry). MaxAttempts int `toml:"max_attempts" env:"QUEUE_MAX_ATTEMPTS"` } // Tier is one set of per-download limits. type Tier struct { MaxSizeMB int64 `toml:"max_size_mb"` MaxDuration Duration `toml:"max_duration"` ActiveJobs int `toml:"active_jobs"` } // Limits holds the per-tier limits. type Limits struct { Free Tier `toml:"free"` } // Log holds logging settings. type Log struct { // Level is debug, info, warn or error. Level string `toml:"level" env:"LOG_LEVEL"` // Format is "json" or "text". Format string `toml:"format" env:"LOG_FORMAT"` } // Default returns the configuration with all starting defaults applied. func Default() Config { return Config{ Telegram: Telegram{ APIURL: "https://api.telegram.org", Mode: "polling", MaxUploadMB: 50, UpdateWorkers: 8, }, HTTP: HTTP{Listen: ":8080"}, Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"}, Storage: Storage{Backend: "local", LocalDir: "data/files"}, Worker: Worker{ Embedded: true, Concurrency: 2, TempDir: "data/tmp", YtDlpPath: "yt-dlp", FfmpegPath: "ffmpeg", DownloadTimeout: Duration(30 * time.Minute), ProbeTimeout: Duration(45 * time.Second), ProbeConcurrency: 4, }, Queue: Queue{ FreeMaxLen: 20, Lease: Duration(30 * time.Second), Heartbeat: Duration(10 * time.Second), MaxAttempts: 2, }, Limits: Limits{ Free: Tier{MaxSizeMB: 50, MaxDuration: Duration(10 * time.Minute), ActiveJobs: 1}, }, Log: Log{Level: "info", Format: "json"}, } } // Load builds the configuration. path may be empty, in which case the // DLBOT_CONFIG variable and then ./config.toml are tried. A missing default // file is not an error. A .env file in the working directory is read first // and never overrides variables that are already set. func Load(path string) (Config, error) { cfg := Default() if err := loadDotEnv(".env"); err != nil { return cfg, err } explicit := path != "" if path == "" { path = os.Getenv("DLBOT_CONFIG") explicit = path != "" } if path == "" { path = "config.toml" } if _, err := os.Stat(path); err == nil { if _, err := toml.DecodeFile(path, &cfg); err != nil { return cfg, fmt.Errorf("config file %s: %w", path, err) } } else if explicit { return cfg, fmt.Errorf("config file %s: %w", path, err) } if err := applyEnv(reflect.ValueOf(&cfg).Elem(), os.LookupEnv); err != nil { return cfg, err } // Tier limits are structured, so they get explicit env names. if err := applyTierEnv("FREE", &cfg.Limits.Free, os.LookupEnv); err != nil { return cfg, err } return cfg, cfg.Validate() } // Validate reports configuration mistakes that would break startup. func (c Config) Validate() error { var errs []string if c.Telegram.Token == "" { errs = append(errs, "BOT_TOKEN is required") } switch c.Telegram.Mode { case "polling": case "webhook": if c.Telegram.WebhookURL == "" { errs = append(errs, "WEBHOOK_URL is required when TELEGRAM_MODE=webhook") } default: errs = append(errs, "TELEGRAM_MODE must be polling or webhook") } switch c.Database.Driver { case "sqlite", "postgres": default: errs = append(errs, "DB_DRIVER must be sqlite or postgres") } switch c.Storage.Backend { case "local", "s3": default: errs = append(errs, "STORAGE_BACKEND must be local or s3") } if c.Worker.Concurrency < 1 { errs = append(errs, "WORKER_CONCURRENCY must be at least 1") } if c.Queue.MaxAttempts < 1 { errs = append(errs, "QUEUE_MAX_ATTEMPTS must be at least 1") } if c.Queue.Heartbeat.D() >= c.Queue.Lease.D() { errs = append(errs, "QUEUE_HEARTBEAT must be shorter than QUEUE_LEASE") } if len(errs) > 0 { return errors.New("config: " + strings.Join(errs, "; ")) } return nil } // MaxUploadBytes is the Telegram upload ceiling in bytes. func (c Config) MaxUploadBytes() int64 { return c.Telegram.MaxUploadMB << 20 } // IsOwner reports whether the Telegram user is a configured owner. func (c Config) IsOwner(userID int64) bool { for _, id := range c.Owners { if id == userID { return true } } return false } func applyTierEnv(prefix string, t *Tier, lookup func(string) (string, bool)) error { if v, ok := lookup(prefix + "_MAX_SIZE_MB"); ok && v != "" { n, err := strconv.ParseInt(v, 10, 64) if err != nil { return fmt.Errorf("config: %s_MAX_SIZE_MB: %w", prefix, err) } t.MaxSizeMB = n } if v, ok := lookup(prefix + "_MAX_DURATION"); ok && v != "" { if err := t.MaxDuration.UnmarshalText([]byte(v)); err != nil { return fmt.Errorf("config: %s_MAX_DURATION: %w", prefix, err) } } if v, ok := lookup(prefix + "_ACTIVE_JOBS"); ok && v != "" { n, err := strconv.Atoi(v) if err != nil { return fmt.Errorf("config: %s_ACTIVE_JOBS: %w", prefix, err) } t.ActiveJobs = n } return nil } var durationType = reflect.TypeOf(Duration(0)) // applyEnv walks the struct and overrides every field that has an env tag // and a non-empty variable. func applyEnv(v reflect.Value, lookup func(string) (string, bool)) error { t := v.Type() for i := 0; i < t.NumField(); i++ { f := v.Field(i) sf := t.Field(i) name := sf.Tag.Get("env") if name == "" { if f.Kind() == reflect.Struct { if err := applyEnv(f, lookup); err != nil { return err } } continue } raw, ok := lookup(name) if !ok || raw == "" { continue } if err := setField(f, raw); err != nil { return fmt.Errorf("config: %s: %w", name, err) } } return nil } func setField(f reflect.Value, raw string) error { raw = strings.TrimSpace(raw) if f.Type() == durationType { d, err := time.ParseDuration(raw) if err != nil { return err } f.SetInt(int64(d)) return nil } switch f.Kind() { case reflect.String: f.SetString(raw) case reflect.Bool: b, err := strconv.ParseBool(raw) if err != nil { return err } f.SetBool(b) case reflect.Int, reflect.Int64: n, err := strconv.ParseInt(raw, 10, 64) if err != nil { return err } f.SetInt(n) case reflect.Float64: n, err := strconv.ParseFloat(raw, 64) if err != nil { return err } f.SetFloat(n) case reflect.Slice: parts := splitList(raw) switch f.Type().Elem().Kind() { case reflect.String: f.Set(reflect.ValueOf(parts)) case reflect.Int64: out := make([]int64, 0, len(parts)) for _, p := range parts { n, err := strconv.ParseInt(p, 10, 64) if err != nil { return err } out = append(out, n) } f.Set(reflect.ValueOf(out)) default: return fmt.Errorf("unsupported list type %s", f.Type()) } default: return fmt.Errorf("unsupported type %s", f.Type()) } return nil } func splitList(raw string) []string { var out []string for _, p := range strings.FieldsFunc(raw, func(r rune) bool { return r == ',' || r == ' ' || r == ';' }) { if p = strings.TrimSpace(p); p != "" { out = append(out, p) } } return out } // loadDotEnv reads KEY=VALUE lines into the process environment without // overriding existing variables. A missing file is fine. func loadDotEnv(path string) error { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { return nil } return err } defer f.Close() sc := bufio.NewScanner(f) for sc.Scan() { line := strings.TrimSpace(sc.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } line = strings.TrimPrefix(line, "export ") k, v, ok := strings.Cut(line, "=") if !ok { continue } k = strings.TrimSpace(k) v = strings.TrimSpace(v) if len(v) >= 2 && (v[0] == '"' && v[len(v)-1] == '"' || v[0] == '\'' && v[len(v)-1] == '\'') { v = v[1 : len(v)-1] } if _, set := os.LookupEnv(k); !set { _ = os.Setenv(k, v) } } return sc.Err() }