Group wallets, group passes, spending rules and admin-only settings. - Groups recorded from my_chat_member; admin rights verified with getChatMember and cached for five minutes - Group context in entitlement resolution: group pass, group credits under the spending rule (anyone, admins only, capped per person per day) and the group's daily cap; refunds go back to the wallet that paid - Group gate before any lookup: bot on or off, who may use it, allowed and blocked sites, plus the owner's maintenance mode - /settings with inline toggles checked on every press, /grouplang, /autodetect, /allow, /block, /spending, /groupwallet, /grouppass, /groupstats - Deep links with the target pre-selected: paying for a group happens in the private chat; a refused download in a group offers "Buy for me" and "Add group credits" - Optional link detection, tidy mode, default quality and language per group; per-member usage - /quality, /language, /app, /privacy, /terms, /support - Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban, /grant (passes and gift codes), /credit, /refund, /blocklist, /broadcast with confirmation, /maint, /reload i18n Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
745 lines
24 KiB
Go
745 lines
24 KiB
Go
// 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"
|
|
"sort"
|
|
"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"`
|
|
LNbits LNbits `toml:"lnbits"`
|
|
Cache Cache `toml:"cache"`
|
|
Prices Prices `toml:"prices"`
|
|
Rate Rate `toml:"rate"`
|
|
Log Log `toml:"log"`
|
|
|
|
// SiteTags says which worker tags a site requires. A job for a listed
|
|
// site is only given to workers that advertise all of its tags. The
|
|
// usual case is a site that refuses datacenter addresses:
|
|
//
|
|
// [site_tags]
|
|
// "youtube.com" = ["residential"]
|
|
//
|
|
// A host also covers its subdomains. In the environment the same map
|
|
// is SITE_TAGS="youtube.com=residential;example.com=eu,residential".
|
|
SiteTags map[string][]string `toml:"site_tags"`
|
|
|
|
// WorkerTokens registers remote workers at startup, as "name:token"
|
|
// pairs. It is the simple way for a fixed setup such as docker
|
|
// compose. "core worker add" creates tokens without a restart.
|
|
WorkerTokens []string `toml:"worker_tokens" env:"WORKER_TOKENS"`
|
|
|
|
// ProbeMode says who runs metadata lookups: "local" (the core runs
|
|
// yt-dlp), "worker" (remote workers do), or "auto", which is local
|
|
// when the embedded worker is on and worker otherwise.
|
|
ProbeMode string `toml:"probe_mode" env:"PROBE_MODE"`
|
|
|
|
// Support is where /support points users: a @username or a link.
|
|
Support string `toml:"support" env:"SUPPORT_CONTACT"`
|
|
|
|
// MiniApp turns the Mini App links on. It needs PublicURL.
|
|
MiniApp bool `toml:"miniapp" env:"MINIAPP_ENABLED"`
|
|
|
|
// LocalesDir, when set, loads the translation catalogs from this
|
|
// directory instead of the ones built into the binary, and makes
|
|
// "/reload i18n" pick up edits without a restart.
|
|
LocalesDir string `toml:"locales_dir" env:"LOCALES_DIR"`
|
|
|
|
// PublicURL is the HTTPS base URL this server is reachable at from the
|
|
// internet, without a trailing slash. It is used for payment webhooks,
|
|
// "open in wallet" links and the Mini App.
|
|
PublicURL string `toml:"public_url" env:"PUBLIC_URL"`
|
|
|
|
// 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"`
|
|
S3 S3 `toml:"s3"`
|
|
}
|
|
|
|
// S3 holds the settings of an S3 compatible bucket (AWS, Garage, MinIO).
|
|
type S3 struct {
|
|
// Endpoint is host:port or a URL, for example https://s3.example.com.
|
|
Endpoint string `toml:"endpoint" env:"S3_ENDPOINT"`
|
|
Region string `toml:"region" env:"S3_REGION"`
|
|
Bucket string `toml:"bucket" env:"S3_BUCKET"`
|
|
AccessKey string `toml:"access_key" env:"S3_ACCESS_KEY"`
|
|
SecretKey string `toml:"secret_key" env:"S3_SECRET_KEY"`
|
|
UseSSL bool `toml:"use_ssl" env:"S3_USE_SSL"`
|
|
// PathStyle addresses the bucket as /bucket/key. Garage and MinIO need
|
|
// it; AWS prefers it off.
|
|
PathStyle bool `toml:"path_style" env:"S3_PATH_STYLE"`
|
|
Prefix string `toml:"prefix" env:"S3_PREFIX"`
|
|
// Presign lets workers upload straight to the bucket with presigned
|
|
// URLs. When off, files pass through the core.
|
|
Presign bool `toml:"presign" env:"S3_PRESIGN"`
|
|
// PresignEndpoint is the address workers reach the bucket at, when it
|
|
// is not the one the core uses.
|
|
PresignEndpoint string `toml:"presign_endpoint" env:"S3_PRESIGN_ENDPOINT"`
|
|
}
|
|
|
|
// 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"`
|
|
// Tags are the tags of the embedded worker.
|
|
Tags []string `toml:"tags" env:"WORKER_TAGS"`
|
|
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 limits.
|
|
type Tier struct {
|
|
MaxSizeMB int64 `toml:"max_size_mb"`
|
|
MaxDuration Duration `toml:"max_duration"`
|
|
ActiveJobs int `toml:"active_jobs"`
|
|
// DailyDownloads is the number of downloads per UTC day, 0 for no cap.
|
|
DailyDownloads int `toml:"daily_downloads"`
|
|
// DailyMB is the volume per UTC day in MB, 0 for no cap. It applies to
|
|
// paid users too, as a guard against abuse.
|
|
DailyMB int64 `toml:"daily_mb"`
|
|
// PlaylistItems is how many items of one playlist link are fetched.
|
|
PlaylistItems int `toml:"playlist_items"`
|
|
}
|
|
|
|
// Cache holds the smart cache settings.
|
|
type Cache struct {
|
|
Enabled bool `toml:"enabled" env:"CACHE_ENABLED"`
|
|
// BudgetMB caps the total size of stored copies. 0 means no cap.
|
|
BudgetMB int64 `toml:"budget_mb" env:"CACHE_BUDGET_MB"`
|
|
// TTLs by source class: how long a result is served before it is
|
|
// fetched again.
|
|
TTL Duration `toml:"ttl" env:"CACHE_TTL"`
|
|
TTLStable Duration `toml:"ttl_stable" env:"CACHE_TTL_STABLE"`
|
|
TTLEphemeral Duration `toml:"ttl_ephemeral" env:"CACHE_TTL_EPHEMERAL"`
|
|
// StableSites and EphemeralSites are yt-dlp extractor name prefixes.
|
|
StableSites []string `toml:"stable_sites" env:"CACHE_STABLE_SITES"`
|
|
EphemeralSites []string `toml:"ephemeral_sites" env:"CACHE_EPHEMERAL_SITES"`
|
|
// MetaTTL is how long link metadata is remembered, so cards for known
|
|
// links appear at once.
|
|
MetaTTL Duration `toml:"meta_ttl" env:"CACHE_META_TTL"`
|
|
// Derive makes lower profiles and audio from a stored higher profile
|
|
// with ffmpeg instead of downloading again.
|
|
Derive bool `toml:"derive" env:"CACHE_DERIVE"`
|
|
// SweepInterval is how often expiry, the size budget and orphan files
|
|
// are checked.
|
|
SweepInterval Duration `toml:"sweep_interval" env:"CACHE_SWEEP_INTERVAL"`
|
|
}
|
|
|
|
// Limits holds the per-tier limits. Free applies to everyone without a
|
|
// paid entitlement. Paid applies to passes, credits and one-off payments.
|
|
type Limits struct {
|
|
Free Tier `toml:"free"`
|
|
Paid Tier `toml:"paid"`
|
|
}
|
|
|
|
// LNbits holds the Lightning payment backend settings. Payments are
|
|
// enabled when both URL and InvoiceKey are set.
|
|
type LNbits struct {
|
|
URL string `toml:"url" env:"LNBITS_URL"`
|
|
// InvoiceKey is the wallet's invoice (read) key. The admin key is never
|
|
// needed and must not be given to the bot.
|
|
InvoiceKey string `toml:"invoice_key" env:"LNBITS_INVOICE_KEY"`
|
|
// WebhookSecret is a random string that becomes part of the webhook
|
|
// path, so only LNbits knows where to post.
|
|
WebhookSecret string `toml:"webhook_secret" env:"LNBITS_WEBHOOK_SECRET"`
|
|
// PollInterval is how often unsettled invoices are checked as a
|
|
// fallback for lost webhooks.
|
|
PollInterval Duration `toml:"poll_interval" env:"LNBITS_POLL_INTERVAL"`
|
|
// InvoiceExpiry is how long an invoice can be paid.
|
|
InvoiceExpiry Duration `toml:"invoice_expiry" env:"INVOICE_EXPIRY"`
|
|
}
|
|
|
|
// Enabled reports whether payments are configured.
|
|
func (l LNbits) Enabled() bool { return l.URL != "" && l.InvoiceKey != "" }
|
|
|
|
// Prices holds every price in sats. Nothing is hardcoded elsewhere.
|
|
type Prices struct {
|
|
PassDay int64 `toml:"pass_day" env:"PRICE_PASS_DAY"`
|
|
PassWeek int64 `toml:"pass_week" env:"PRICE_PASS_WEEK"`
|
|
PassMonth int64 `toml:"pass_month" env:"PRICE_PASS_MONTH"`
|
|
// CreditPerDownload is what one download costs when credits pay.
|
|
CreditPerDownload int64 `toml:"credit_per_download" env:"PRICE_CREDIT_DOWNLOAD"`
|
|
// OneOff is base plus a step per started 100 MB.
|
|
OneOffBase int64 `toml:"one_off_base" env:"PRICE_ONE_OFF_BASE"`
|
|
OneOffPer100MB int64 `toml:"one_off_per_100mb" env:"PRICE_ONE_OFF_PER_100MB"`
|
|
// SkipQueue moves one waiting free job to the paid lane.
|
|
SkipQueue int64 `toml:"skip_queue" env:"PRICE_SKIP_QUEUE"`
|
|
// CreditPacks are the top-up amounts offered.
|
|
CreditPacks []int64 `toml:"credit_packs" env:"CREDIT_PACKS"`
|
|
// DonationAmounts are the tip amounts offered by /donate.
|
|
DonationAmounts []int64 `toml:"donation_amounts" env:"DONATION_AMOUNTS"`
|
|
// ReferralReward is credited to the inviter when an invited user makes
|
|
// a first purchase. 0 turns the reward off.
|
|
ReferralReward int64 `toml:"referral_reward" env:"REFERRAL_REWARD"`
|
|
}
|
|
|
|
// Rate holds the request rate limits.
|
|
type Rate struct {
|
|
// UserPerMinute is how many links one user may send per minute.
|
|
UserPerMinute int `toml:"user_per_minute" env:"RATE_USER_PER_MINUTE"`
|
|
// GroupPerMinute is how many links one group may send per minute.
|
|
GroupPerMinute int `toml:"group_per_minute" env:"RATE_GROUP_PER_MINUTE"`
|
|
}
|
|
|
|
// 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,
|
|
},
|
|
ProbeMode: "auto",
|
|
HTTP: HTTP{Listen: ":8080"},
|
|
Database: Database{Driver: "sqlite", DSN: "data/dlbot.db"},
|
|
Storage: Storage{Backend: "local", LocalDir: "data/files",
|
|
S3: S3{Region: "garage", UseSSL: true, PathStyle: true, Presign: true}},
|
|
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,
|
|
DailyDownloads: 5, DailyMB: 250, PlaylistItems: 3},
|
|
Paid: Tier{MaxSizeMB: 2000, MaxDuration: Duration(3 * time.Hour), ActiveJobs: 3,
|
|
DailyDownloads: 100, DailyMB: 20000, PlaylistItems: 25},
|
|
},
|
|
Cache: Cache{
|
|
Enabled: true,
|
|
BudgetMB: 20000,
|
|
TTL: Duration(7 * 24 * time.Hour),
|
|
TTLStable: Duration(30 * 24 * time.Hour),
|
|
TTLEphemeral: Duration(6 * time.Hour),
|
|
StableSites: []string{"youtube", "vimeo", "archive.org", "soundcloud", "dailymotion", "peertube", "bandcamp"},
|
|
EphemeralSites: []string{"twitter", "instagram", "tiktok", "facebook", "reddit", "twitch", "generic"},
|
|
MetaTTL: Duration(30 * time.Minute),
|
|
Derive: true,
|
|
SweepInterval: Duration(10 * time.Minute),
|
|
},
|
|
LNbits: LNbits{
|
|
PollInterval: Duration(5 * time.Second),
|
|
InvoiceExpiry: Duration(10 * time.Minute),
|
|
},
|
|
Prices: Prices{
|
|
PassDay: 700, PassWeek: 3000, PassMonth: 9000,
|
|
CreditPerDownload: 50,
|
|
OneOffBase: 100, OneOffPer100MB: 50,
|
|
SkipQueue: 50,
|
|
CreditPacks: []int64{1000, 5000, 20000},
|
|
DonationAmounts: []int64{500, 2100, 10000},
|
|
ReferralReward: 200,
|
|
},
|
|
Rate: Rate{UserPerMinute: 10, GroupPerMinute: 30},
|
|
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
|
|
}
|
|
if err := applyTierEnv("PAID", &cfg.Limits.Paid, os.LookupEnv); err != nil {
|
|
return cfg, err
|
|
}
|
|
if raw, ok := os.LookupEnv("SITE_TAGS"); ok && raw != "" {
|
|
m, err := ParseSiteTags(raw)
|
|
if err != nil {
|
|
return cfg, err
|
|
}
|
|
cfg.SiteTags = m
|
|
}
|
|
cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/")
|
|
cfg.LNbits.URL = strings.TrimRight(cfg.LNbits.URL, "/")
|
|
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 c.Storage.Backend == "s3" {
|
|
if c.Storage.S3.Endpoint == "" || c.Storage.S3.Bucket == "" {
|
|
errs = append(errs, "S3_ENDPOINT and S3_BUCKET are required when STORAGE_BACKEND=s3")
|
|
}
|
|
if c.Storage.S3.AccessKey == "" || c.Storage.S3.SecretKey == "" {
|
|
errs = append(errs, "S3_ACCESS_KEY and S3_SECRET_KEY are required when STORAGE_BACKEND=s3")
|
|
}
|
|
}
|
|
switch c.ProbeMode {
|
|
case "auto", "local", "worker":
|
|
default:
|
|
errs = append(errs, "PROBE_MODE must be auto, local or worker")
|
|
}
|
|
for _, pair := range c.WorkerTokens {
|
|
if name, token, ok := strings.Cut(pair, ":"); !ok || name == "" || len(token) < 16 {
|
|
errs = append(errs, "WORKER_TOKENS entries must be name:token with a token of at least 16 characters")
|
|
break
|
|
}
|
|
}
|
|
if (c.LNbits.URL == "") != (c.LNbits.InvoiceKey == "") {
|
|
errs = append(errs, "LNBITS_URL and LNBITS_INVOICE_KEY must be set together")
|
|
}
|
|
if c.LNbits.Enabled() {
|
|
if c.LNbits.InvoiceExpiry.D() < time.Minute {
|
|
errs = append(errs, "INVOICE_EXPIRY must be at least 1m")
|
|
}
|
|
if c.LNbits.PollInterval.D() <= 0 {
|
|
errs = append(errs, "LNBITS_POLL_INTERVAL must be positive")
|
|
}
|
|
for name, v := range map[string]int64{
|
|
"PRICE_PASS_DAY": c.Prices.PassDay, "PRICE_PASS_WEEK": c.Prices.PassWeek,
|
|
"PRICE_PASS_MONTH": c.Prices.PassMonth, "PRICE_CREDIT_DOWNLOAD": c.Prices.CreditPerDownload,
|
|
} {
|
|
if v <= 0 {
|
|
errs = append(errs, name+" must be positive")
|
|
}
|
|
}
|
|
}
|
|
if len(errs) > 0 {
|
|
return errors.New("config: " + strings.Join(errs, "; "))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ParseSiteTags reads "host=tag,tag;host=tag".
|
|
func ParseSiteTags(raw string) (map[string][]string, error) {
|
|
out := map[string][]string{}
|
|
for _, part := range strings.Split(raw, ";") {
|
|
part = strings.TrimSpace(part)
|
|
if part == "" {
|
|
continue
|
|
}
|
|
host, tags, ok := strings.Cut(part, "=")
|
|
host = strings.ToLower(strings.TrimSpace(host))
|
|
if !ok || host == "" {
|
|
return nil, fmt.Errorf("config: SITE_TAGS: %q is not host=tag,tag", part)
|
|
}
|
|
for _, t := range strings.Split(tags, ",") {
|
|
if t = strings.ToLower(strings.TrimSpace(t)); t != "" {
|
|
out[host] = append(out[host], t)
|
|
}
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// RequiredTags returns the worker tags a site requires, sorted and comma
|
|
// separated, or "" when any worker will do. A rule for a host also covers
|
|
// its subdomains, and the rules of a host and of its parents add up.
|
|
func (c Config) RequiredTags(site string) string {
|
|
if len(c.SiteTags) == 0 || site == "" {
|
|
return ""
|
|
}
|
|
seen := map[string]bool{}
|
|
var tags []string
|
|
for host := strings.ToLower(site); host != ""; {
|
|
for _, t := range c.SiteTags[host] {
|
|
if t = strings.ToLower(strings.TrimSpace(t)); t != "" && !seen[t] {
|
|
seen[t] = true
|
|
tags = append(tags, t)
|
|
}
|
|
}
|
|
i := strings.IndexByte(host, '.')
|
|
if i < 0 {
|
|
break
|
|
}
|
|
host = host[i+1:]
|
|
}
|
|
sort.Strings(tags)
|
|
return strings.Join(tags, ",")
|
|
}
|
|
|
|
// MiniAppEnabled reports whether Mini App links can be shown. The Mini App
|
|
// is served from PublicURL, so both are needed.
|
|
func (c Config) MiniAppEnabled() bool { return c.MiniApp && c.PublicURL != "" }
|
|
|
|
// ProbeLocally reports whether the core itself runs metadata lookups.
|
|
func (c Config) ProbeLocally() bool {
|
|
switch c.ProbeMode {
|
|
case "local":
|
|
return true
|
|
case "worker":
|
|
return false
|
|
}
|
|
return c.Worker.Embedded
|
|
}
|
|
|
|
// 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
|
|
}
|
|
if v, ok := lookup(prefix + "_DAILY_DOWNLOADS"); ok && v != "" {
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil {
|
|
return fmt.Errorf("config: %s_DAILY_DOWNLOADS: %w", prefix, err)
|
|
}
|
|
t.DailyDownloads = n
|
|
}
|
|
if v, ok := lookup(prefix + "_PLAYLIST_ITEMS"); ok && v != "" {
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil {
|
|
return fmt.Errorf("config: %s_PLAYLIST_ITEMS: %w", prefix, err)
|
|
}
|
|
t.PlaylistItems = n
|
|
}
|
|
if v, ok := lookup(prefix + "_DAILY_MB"); ok && v != "" {
|
|
n, err := strconv.ParseInt(v, 10, 64)
|
|
if err != nil {
|
|
return fmt.Errorf("config: %s_DAILY_MB: %w", prefix, err)
|
|
}
|
|
t.DailyMB = n
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// PassPrice returns the price of a pass kind ("day", "week", "month").
|
|
func (p Prices) PassPrice(kind string) int64 {
|
|
switch kind {
|
|
case "day":
|
|
return p.PassDay
|
|
case "week":
|
|
return p.PassWeek
|
|
case "month":
|
|
return p.PassMonth
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// OneOffPrice returns the price of a single download of the given size.
|
|
// An unknown size is priced as 200 MB.
|
|
func (p Prices) OneOffPrice(sizeBytes int64) int64 {
|
|
const step = 100 << 20
|
|
if sizeBytes <= 0 {
|
|
sizeBytes = 2 * step
|
|
}
|
|
steps := (sizeBytes + step - 1) / step
|
|
return p.OneOffBase + steps*p.OneOffPer100MB
|
|
}
|
|
|
|
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()
|
|
}
|