commit 3b361c17a1188d15881c8b0e7c2783f42bee274b Author: Michilis Date: Wed Nov 18 07:33:27 2026 +0000 Phase 1: core bot Link in, card, download, send, in private chats and groups. - cmd/core with an embedded download worker - Telegram front end on telego v1.13.0 (Bot API 10.4): link card with thumbnail and format buttons, one live status message, /dl /audio /thumb /info /queue /cancel, group support with requester-only buttons - Database backed queue: paid and free lanes, leases with heartbeats, one automatic retry, cancel, queue position and wait estimate - yt-dlp and ffprobe behind a Runner interface with classified, redacted errors mapped to friendly messages - SQLite via modernc with goose migrations, portable schema - Local file storage behind a Storage interface - go-i18n with an English catalog, no literal text in handlers - Free tier limits enforced before queueing and again on the real file - Bot token and webhook secret are stripped from all log output - Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end flows against a fake Bot API server; opt-in test with the real yt-dlp Co-Authored-By: Claude Fable 5.2 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0f65f12 --- /dev/null +++ b/.env.example @@ -0,0 +1,73 @@ +# Copy to .env and fill in. The core reads .env from its working directory +# and never overrides variables that are already set in the environment. +# Structured settings can also live in a TOML file, see config.example.toml. + +# --- Telegram --------------------------------------------------------------- +# Token from @BotFather. Required. +BOT_TOKEN= +# Bot API root. Point it at a local Bot API server to send files up to 2 GB. +TELEGRAM_API_URL=https://api.telegram.org +# polling (default) or webhook. +TELEGRAM_MODE=polling +# Public HTTPS base URL of this server. Only for webhook mode. Telegram will +# call /telegram/webhook. +WEBHOOK_URL= +# Random string Telegram echoes back in a header. Only for webhook mode. +WEBHOOK_SECRET= +# Largest file the bot can send, in MB. 50 on the cloud Bot API. +TELEGRAM_MAX_UPLOAD_MB=50 +# Goroutines that handle updates. +TELEGRAM_UPDATE_WORKERS=8 + +# Telegram user IDs allowed to use owner commands, comma separated. +OWNER_IDS= + +# --- HTTP ------------------------------------------------------------------- +# Listen address of the health endpoint and the webhook. +HTTP_LISTEN=:8080 + +# --- Database --------------------------------------------------------------- +# sqlite or postgres. +DB_DRIVER=sqlite +# File path for sqlite, connection URL for postgres. +DB_DSN=data/dlbot.db + +# --- Storage ---------------------------------------------------------------- +# local or s3. +STORAGE_BACKEND=local +STORAGE_LOCAL_DIR=data/files + +# --- Worker ----------------------------------------------------------------- +# Run a download worker inside the core process. +WORKER_EMBEDDED=true +# Downloads running at the same time. +WORKER_CONCURRENCY=2 +# Scratch space for downloads. Each worker process needs its own directory. +WORKER_TEMP_DIR=data/tmp +YTDLP_PATH=yt-dlp +FFMPEG_PATH=ffmpeg +# Hard cap for one download attempt. +DOWNLOAD_TIMEOUT=30m +# Cap for one metadata lookup, and how many may run at once. +PROBE_TIMEOUT=45s +PROBE_CONCURRENCY=4 + +# --- Queue ------------------------------------------------------------------ +# Most queued jobs accepted from free users. +QUEUE_FREE_MAX_LEN=20 +# A claimed job goes back to the queue when no heartbeat arrives for this long. +QUEUE_LEASE=30s +QUEUE_HEARTBEAT=10s +# Tries per job. 2 means one automatic retry. +QUEUE_MAX_ATTEMPTS=2 + +# --- Free tier limits ------------------------------------------------------- +FREE_MAX_SIZE_MB=50 +FREE_MAX_DURATION=10m +FREE_ACTIVE_JOBS=1 + +# --- Logging ---------------------------------------------------------------- +# debug, info, warn or error. +LOG_LEVEL=info +# json or text. +LOG_FORMAT=json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9fa6e76 --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# Secrets and local configuration +.env +config.toml + +# Runtime data: database, stored files, temp downloads +data/ + +# Build output and local tools +bin/ +.tools/ +*.test +coverage.out + +# Mini App build artifacts +web/miniapp/node_modules/ +web/miniapp/dist/ + +# Editors +.idea/ +.vscode/ +*.swp diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0b88627 --- /dev/null +++ b/Makefile @@ -0,0 +1,35 @@ +GO ?= go +BIN := bin +VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) + +.PHONY: all build test race vet fmt check run e2e clean + +all: check build + +build: + $(GO) build -trimpath -ldflags "-s -w" -o $(BIN)/core ./cmd/core + +test: + $(GO) test ./... + +race: + $(GO) test -race -count=1 ./... + +vet: + $(GO) vet ./... + +fmt: + @out="$$(gofmt -l .)"; if [ -n "$$out" ]; then echo "gofmt needed on:"; echo "$$out"; exit 1; fi + +# Everything CI runs. +check: fmt vet race + +run: build + ./$(BIN)/core + +# End-to-end test with the real yt-dlp and ffmpeg. Needs network access. +e2e: + DLBOT_E2E_YTDLP=$${YTDLP_PATH:-$$(command -v yt-dlp)} $(GO) test -count=1 -v -run TestRealYtDlp ./internal/app + +clean: + rm -rf $(BIN) diff --git a/README.md b/README.md new file mode 100644 index 0000000..dacc793 --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# The Noderunners Download Bot + +A Telegram bot that downloads video and audio from links, in private chats +and in groups. Written in Go on top of yt-dlp. + +> Status: Phase 1 of 8 (core bot). Payments, the cache, remote workers, +> group settings, the Mini App and more languages follow. See +> [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md) for the decisions made so far. + +## What works today + +- Send a link in a private chat and get a card with title, thumbnail, + duration and format buttons: Best, 720p, 480p, MP3, Thumbnail, Cancel. +- In groups: `/dl `, or reply `/dl` to a message with a link. Buttons + only work for the person who asked. +- One status message, edited live: queued with position and wait, + downloading with a progress bar, processing, sending, done. +- A database backed queue with leases, one automatic retry and cancel. +- Free tier limits: size, duration, one active job, bounded queue. +- Friendly, translated error messages. Raw tool output stays in the logs. + +## Quick start + +You need Go 1.26.11 or newer (older Go toolchains download it on their +own), plus `yt-dlp` and `ffmpeg` on the PATH. + +```sh +# 1. Create a bot with @BotFather and copy its token. +cp .env.example .env +$EDITOR .env # set BOT_TOKEN + +# 2. Build and run. +make build +./bin/core +``` + +Open your bot in Telegram, press Start and send it a link. + +To use the bot in a group, add it to the group. Group privacy mode can stay +on: the bot only needs to see commands. + +### Check that it is alive + +```sh +curl localhost:8080/healthz +# {"status":"ok"} +``` + +## Commands + +| Command | What it does | +| --- | --- | +| `/start` | Welcome message | +| `/help` | Usage and your limits | +| `/dl ` | Download a video. In groups also works as a reply to a link. | +| `/audio ` | Download the audio as MP3 | +| `/thumb ` | Send the thumbnail | +| `/info ` | Show formats and sizes without downloading | +| `/queue` | Your downloads in progress | +| `/cancel` | Cancel your downloads | + +## Configuration + +Everything is configured through environment variables. `.env.example` +lists all of them with comments. A TOML file with the same settings is +optional, see `config.example.toml`; the environment overrides the file. + +The settings you are most likely to touch: + +| Variable | Default | Meaning | +| --- | --- | --- | +| `BOT_TOKEN` | none | Token from @BotFather. Required. | +| `TELEGRAM_MODE` | `polling` | `polling` or `webhook` | +| `WORKER_CONCURRENCY` | `2` | Downloads running at the same time | +| `FREE_MAX_SIZE_MB` | `50` | Size cap per download | +| `FREE_MAX_DURATION` | `10m` | Duration cap per download | +| `FREE_ACTIVE_JOBS` | `1` | Active downloads per user | +| `QUEUE_FREE_MAX_LEN` | `20` | Most queued free jobs | +| `DB_DSN` | `data/dlbot.db` | SQLite file | +| `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | + +## Development + +```sh +make check # gofmt, go vet, tests with the race detector +make test # tests only +make e2e # real yt-dlp against a public test file, needs network +``` + +The tests need neither a bot token nor network access. They run the real +bot against a fake Bot API server (`internal/tg/fakeserver`) and a scripted +yt-dlp. + +## Documentation + +- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit. +- [docs/ASSUMPTIONS.md](docs/ASSUMPTIONS.md): decisions and verified facts. + +## Layout + +``` +cmd/core the bot gateway (and, for now, the embedded worker) +internal/bot Telegram handlers, cards, status, delivery +internal/service download rules shared by all front ends +internal/sched the job queue +internal/worker the download worker +internal/ytdlp yt-dlp and ffprobe wrapper +internal/db migrations and queries +internal/storage file storage backends +internal/i18n translations and formatting +locales translation catalogs +docs architecture and assumptions +``` diff --git a/cmd/core/main.go b/cmd/core/main.go new file mode 100644 index 0000000..787d647 --- /dev/null +++ b/cmd/core/main.go @@ -0,0 +1,41 @@ +// Command core is the bot gateway: it talks to Telegram, owns the queue and +// the database, serves the HTTP API and, by default, runs an embedded +// download worker. +package main + +import ( + "context" + "flag" + "fmt" + "os" + "os/signal" + "syscall" + + "github.com/noderunners/dlbot/internal/app" + "github.com/noderunners/dlbot/internal/config" +) + +func main() { + configPath := flag.String("config", "", "path to a TOML config file (optional, env vars override it)") + flag.Parse() + + cfg, err := config.Load(*configPath) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(2) + } + log := app.NewLogger(cfg.Log, app.Secrets(cfg)...) + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + a, err := app.New(ctx, app.Options{Config: cfg, Log: log}) + if err != nil { + log.Error("startup failed", "err", err) + os.Exit(1) + } + if err := a.Run(ctx); err != nil { + log.Error("core exited with error", "err", err) + os.Exit(1) + } +} diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..c295b84 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,50 @@ +# Optional config file. Copy to config.toml, or pass a path with -config or +# the DLBOT_CONFIG variable. Every value here can also be set through the +# environment (see .env.example), and the environment wins. +# Keep secrets such as the bot token in the environment, not in this file. + +# Telegram user IDs allowed to use owner commands. +owners = [] + +[telegram] +api_url = "https://api.telegram.org" +mode = "polling" # polling or webhook +webhook_url = "" +max_upload_mb = 50 # 2000 with a local Bot API server +update_workers = 8 + +[http] +listen = ":8080" + +[database] +driver = "sqlite" # sqlite or postgres +dsn = "data/dlbot.db" + +[storage] +backend = "local" # local or s3 +local_dir = "data/files" + +[worker] +embedded = true +concurrency = 2 +temp_dir = "data/tmp" +ytdlp_path = "yt-dlp" +ffmpeg_path = "ffmpeg" +download_timeout = "30m" +probe_timeout = "45s" +probe_concurrency = 4 + +[queue] +free_max_len = 20 +lease = "30s" +heartbeat = "10s" +max_attempts = 2 + +[limits.free] +max_size_mb = 50 +max_duration = "10m" +active_jobs = 1 + +[log] +level = "info" +format = "json" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..fcc7611 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,157 @@ +# Architecture + +This document describes the system as it is built today. It grows with each +phase; sections for later phases say so. + +## The shape of it + +``` + Telegram <----> core <---- claim / heartbeat / complete / fail ---- worker(s) + | \ | + | \__ storage (local disk today, S3 in Phase 4) <___/ + | + database (SQLite today, Postgres in Phase 4) +``` + +- **core** (`cmd/core`) talks to Telegram, owns the database and the queue, + serves HTTP and sends finished files. It is the only process that holds + the bot token. +- **worker** pulls jobs, runs yt-dlp and ffmpeg, uploads the result to + storage and reports back. It is stateless. Today it runs inside the core + process; the code is already split along the future network boundary. + +## Packages + +| Package | Role | +| --- | --- | +| `cmd/core` | Process entry point. Loads config, starts `internal/app`. | +| `internal/app` | Wires everything together. Tests start the bot through it too. | +| `internal/config` | Defaults, optional TOML file, environment overrides, validation. | +| `internal/bot` | Telegram front end: update routing, cards, live status, delivery. | +| `internal/service` | Download rules shared by all front ends: probe, limits, start. | +| `internal/sched` | The queue: enqueue, claim with leases, retry, cancel, positions. | +| `internal/worker` | The download worker loop. Talks to a `Coordinator` interface. | +| `internal/workerproto` | Messages between core and worker. | +| `internal/ytdlp` | yt-dlp and ffprobe behind a `Runner` interface, error classes. | +| `internal/media` | Format profiles: best, 1080, 720, 480, mp3, m4a, subs:lang, thumb. | +| `internal/links` | URL extraction, validation, redaction. | +| `internal/storage` | `Storage` interface and the local disk backend. | +| `internal/db` | Schema migrations and queries for SQLite and Postgres. | +| `internal/i18n` | go-i18n wrapper, locale aware formatting. | +| `internal/tg` | Narrow Bot API interface, error helpers, the fake Bot API server. | +| `internal/api` | HTTP server: health check, Telegram webhook. | +| `locales` | Translation catalogs, embedded in the binary. | + +Dependencies point one way: `bot` uses `service`, `service` uses `sched`, +`sched` uses `db`. `worker` knows none of them; it only sees the +`Coordinator` interface and `workerproto`. + +## Data model + +Four tables carry Phase 1. + +- **users**: one row per Telegram user, with detected and chosen language. +- **requests**: one row per link a user sent. It holds the metadata shown on + the card and which message the card is. +- **jobs**: one unit of work for a worker: URL, profile, limits, status, + lease, progress, result. +- **deliveries**: one requester waiting for a job: where to send the file, + which message shows the status. + +A job and its deliveries are separate on purpose. Today a job has exactly +one delivery. When the cache arrives, a second person asking for the same +video attaches a second delivery to the running job instead of starting a +second download. + +### Job states + +``` + claim complete all requesters served + queued ----------> running ------------> delivering ------------------> done + ^ | | + | retryable fail | | final fail cancel (any state before done) + +-----------------+ +-----------> failed ------------------> cancelled + | lease expired | + +-----------------+ +``` + +### Delivery states + +`pending -> sending -> sent`, or `failed`, or `cancelled`. The move from +pending to sending is a single conditional UPDATE, which is what guarantees +that a file is sent by one goroutine only. + +## Life of a download + +1. A message with a link arrives. `links.Extract` finds and validates it. +2. The bot replies "Looking up the link" and asks `service.Probe` for + metadata (yt-dlp `-J`). Probes are limited to a few at a time. +3. The bot stores a request and shows the card: a photo with title, facts + and format buttons. Callback data is `dl::`. +4. The requester presses a format. The request is taken with a conditional + UPDATE (so a double tap starts one job), limits are checked, and + `sched.Enqueue` inserts the job and its delivery in one transaction + together with the per-user and queue-length checks. +5. A worker claims the job. It runs yt-dlp in a private temp directory, + reports progress with every heartbeat, uploads the file to storage and + calls complete. +6. The scheduler emits events. The bot edits the status message (throttled) + and, on `stored`, streams the file from storage to Telegram. +7. When every delivery is closed the job is marked done and the stored file + is deleted. + +## Queue rules + +- Order: paid lane before free lane, then priority, then first come first + served. The same SQL ordering is used for claiming and for the position + shown to users, so they always agree. +- Claiming is atomic. On SQLite every transaction is `BEGIN IMMEDIATE`, so + the select and update of a claim cannot interleave with another claim. On + Postgres the select uses `FOR UPDATE SKIP LOCKED`. +- A claimed job has a lease. Each heartbeat extends it. A sweeper requeues + jobs whose lease ran out, or fails them when no attempts remain. +- A worker that loses its lease is told so on its next call and drops the + job without reporting a result. + +## Events and reconciliation + +The scheduler notifies the bot through an in-process callback after each +committed change. Events are only an optimization. Every few seconds the +bot also reconciles: it looks for stored jobs with waiting requesters, +failed jobs nobody was told about, uploads stuck since a crash, and queued +jobs whose position changed. Because all of that is driven by database +state, the core can be killed at any point and picks up where it left off. + +## Limits are checked in one place + +`service.Check` decides whether a download may start, from metadata. +`service.Start` is the only way to create a job. The worker enforces the +same size and duration caps on the real file, because metadata is often +missing. When the cache arrives, a cache hit goes through `service.Start` +like everything else: it only skips the worker. + +## Internationalization + +Handlers never contain user-facing text. They call `i18n.Bundle` with a +message ID. `HTML` escapes arguments for Telegram's HTML parse mode, `T` +returns plain text for buttons and callback answers. Sizes, durations and +percentages are formatted per locale. Callback data contains IDs only. + +## Secrets + +Configuration comes from the environment or a config file; neither is in +the repository. The logger removes the bot token and webhook secret from +all output. URLs are redacted before they are logged. + +## Testing approach + +- Pure logic (links, profiles, error classes, size estimates) has table + driven unit tests. +- The scheduler and the worker are tested against a real SQLite database. +- yt-dlp is replaced at two levels: `ytdlptest.Fake` implements the + `Runner` interface, and a shell script stands in for the binary to test + argument building and output parsing. +- The bot is tested end to end through `internal/app` against + `tg/fakeserver`, an HTTP server that speaks enough of the Bot API to push + updates in and record every call, including multipart uploads. +- One opt-in test runs the real yt-dlp against a public test file. diff --git a/docs/ASSUMPTIONS.md b/docs/ASSUMPTIONS.md new file mode 100644 index 0000000..b889ddc --- /dev/null +++ b/docs/ASSUMPTIONS.md @@ -0,0 +1,142 @@ +# Assumptions + +Decisions taken where the brief was open. Each one was the simplest +reasonable option at the time. They are grouped by phase and can be revisited. + +## Verified third-party facts + +Checked against source or live behavior before use, not from memory. + +| What | Version | How it was checked | +| --- | --- | --- | +| telego | v1.13.0, Bot API 10.4 | Module source. `SendWidget` and `WidgetQuery` exist natively. | +| yt-dlp | 2026.10.26 | `--help` of the release binary plus real downloads. | +| go-i18n | v2.7.0 | Module source (`parse.go` for nested TOML keys). | +| goose | v3.30.1 | Module source (`NewProvider`, dialect constants). | +| modernc.org/sqlite | v1.62.0 | Module source (`_pragma` and `_txlock` DSN keys). | + +**Go version.** telego v1.13.0, the release that supports Bot API 10.4, +declares `go 1.26.11`, so that is the minimum for this module. The brief asks +for Go 1.23 or newer, which this satisfies. With the default +`GOTOOLCHAIN=auto` an older Go downloads the right toolchain by itself. + +yt-dlp behaviors that shaped the wrapper: + +- A download that is rejected by `--match-filters` or `--max-filesize` exits + with status 0 and no file. The wrapper detects the missing file and maps + it to `too_long`, `live_stream` or `too_large`. +- `--print pre_process:...` still fires when a filter rejects the item, so + the worker always learns duration and live status. +- `filesize_approx` can be a float and many numbers can be null. The JSON + types tolerate all of that. +- YouTube refuses requests from many datacenter addresses ("Sign in to + confirm you are not a bot"). This maps to `site_blocked` and is the reason + worker tags such as `residential` exist (Phase 4). + +## Phase 1 + +### Project + +- **Module path** is `github.com/noderunners/dlbot`. No remote was given. + Renaming is a search and replace. +- **One binary for now.** Phase 1 asks for "one local worker", so the worker + runs inside `cmd/core` (`WORKER_EMBEDDED=true`). The worker code already + talks to the core through the `worker.Coordinator` interface and the + `workerproto` messages, so `cmd/worker` in Phase 4 only adds an HTTPS + transport. +- **Configuration** is environment first. An optional TOML file holds the + same settings for people who prefer a file; the environment overrides it. + A `.env` file in the working directory is loaded for convenience. +- **IDs** are 26 character, time sortable, lowercase strings generated by + the application. This avoids autoincrement differences between SQLite and + Postgres and keeps callback data short. +- **Timestamps** are unix milliseconds in `BIGINT` columns, for the same + portability reason. + +### Bot behavior + +- **Private chat:** any message with a link starts the flow. Up to 3 links + per message get a card each. Text without a link gets a short hint. +- **Groups:** only commands are handled. `/dl `, or `/dl` as a reply to + a message with a link. The card and the file reply to the message that + holds the link. Auto-detect of pasted links arrives with group settings in + Phase 5. +- **The card is the status message.** After a format is picked the same + message is edited through queued, downloading, processing, uploading and + done. One request is one download; to get a second format the user sends + the link again. +- **Card buttons:** Best, 720p, 480p, MP3, Thumbnail, Cancel. Resolution + buttons at or above the source height are hidden because they would + duplicate Best. MP3 is hidden when the source has no audio, Thumbnail when + there is none. The 1080 and m4a profiles exist but are not on the card. +- **"Skip the queue"** is not shown yet. It is a paid action and appears with + payments in Phase 2, rather than as a button that does nothing. +- **Thumbnail:** the card is a photo sent by URL. When Telegram cannot fetch + the thumbnail the bot falls back to a text card with the same buttons. +- **/audio and /thumb** skip the card and start the profile directly. +- **Playlists** are detected and politely refused for now. Per-item jobs + with an item cap come with the cache in Phase 3, because each item is its + own cache entry. +- **Language:** the user's Telegram `language_code` is stored and resolved + on every update. Only English ships in Phase 1, but no handler contains + literal text. +- **Forum topics:** replies keep messages in the right topic. If the + original message is deleted the fallback message goes to the general + topic. + +### Formats + +- Video prefers **h264 with AAC in mp4** (`-S vcodec:h264,res[:N],acodec:m4a`, + merge to `mp4/mkv`). This is what Telegram clients stream inline. "Best" + therefore means the best h264 rendition, which on YouTube is up to 1080p. +- Files that are not mp4, m4v or mov are sent as documents instead of being + transcoded. Transcoding belongs to the derive step of Phase 3. +- A video or photo Telegram rejects is sent once more as a document. +- MP3 is 192 kbit/s. + +### Limits + +- Until payments exist everyone is on the free tier from the config: + 50 MB, 10 minutes, 1 active job, at most 20 queued free jobs. The daily + quota arrives with the entitlement resolver in Phase 2. +- The Telegram upload ceiling (`TELEGRAM_MAX_UPLOAD_MB`, 50 on the cloud Bot + API) always caps the size, whatever the tier allows. +- Limits are checked twice: on the metadata before queueing, and by the + worker on the real file. Metadata is often incomplete. +- Live streams are refused. + +### Queue + +- **Retry:** a retryable failure is retried once (`QUEUE_MAX_ATTEMPTS=2`). + A retried job keeps its original place in the queue. +- **Lease expiry** (worker died) counts as an attempt, which bounds the + damage of a job that crashes workers. A **clean worker shutdown** hands the + job back without spending an attempt. +- **Cancel:** a queued job is cancelled at once. A running job is flagged + and stops at the worker's next heartbeat (10 seconds by default). +- **Wait estimate** is jobs ahead (plus half of the running ones) divided by + worker slots, times the average duration of the last 20 jobs, or 45 + seconds when there is no history. It is deliberately rough. + +### Delivery + +- The stored file is deleted as soon as every requester has it. Keeping + files is the job of the cache in Phase 3. +- A failed send to Telegram is retried up to 3 times, then reported. +- If the core stops during an upload, the delivery is retried on the next + start. A crash at exactly the wrong moment can therefore send a file + twice; losing it was judged worse. + +### Safety + +- Links to localhost, private, link-local and similar addresses are + rejected before yt-dlp sees them. This is a first line of defense, not a + full SSRF guard: a public hostname can still resolve to a private address. + Workers should run in a network that cannot reach internal services. +- Raw yt-dlp output never reaches users. It is redacted (URLs lose + credentials and signed query values) and kept for owner logs. +- The bot token and the webhook secret are removed from all log output by + the logger itself, because HTTP client errors quote request URLs and Bot + API URLs contain the token. +- No age verification or KYC flow exists or is planned. Content a site + gates behind a login is reported as "needs a login". diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..bee0ad2 --- /dev/null +++ b/go.mod @@ -0,0 +1,41 @@ +module github.com/noderunners/dlbot + +go 1.26.11 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/mymmrac/telego v1.13.0 + github.com/nicksnyder/go-i18n/v2 v2.7.0 + github.com/pressly/goose/v3 v3.30.1 + golang.org/x/text v0.44.0 + modernc.org/sqlite v1.62.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.5 // indirect + github.com/bytedance/sonic/loader v0.5.3 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/goccy/go-json v0.12.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/klauspost/compress v1.20.4 // indirect + github.com/klauspost/cpuid/v2 v2.2.9 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mfridman/interpolate v0.2.0 // indirect + github.com/molecule-man/go-brrr v1.3.1 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/sethvargo/go-retry v0.5.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.78.0 // indirect + github.com/valyala/fastjson v1.6.10 // indirect + go.uber.org/multierr v1.11.0 // indirect + golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + modernc.org/libc v1.80.2 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b4b4784 --- /dev/null +++ b/go.sum @@ -0,0 +1,115 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.5 h1:gKWTBfYCIQpQHZ7LpwGf9Gj3N88ZN0G/GaB3EQhiGXE= +github.com/bytedance/sonic v1.15.5/go.mod h1:nn7CoK5W+LKbl22XGJrXg6SwzaFAcVs89miqzkqDwOU= +github.com/bytedance/sonic/loader v0.5.3 h1:ziVGAbXQtLoaot/M6YQxntGkekxz6B/DyuJVwnTbMAA= +github.com/bytedance/sonic/loader v0.5.3/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI= +github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= +github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg= +github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= +github.com/molecule-man/go-brrr v1.3.1 h1:EwaJUzRIlp/dFmIpzq4J17CA5Zi5OHo2vOGmu09hF1w= +github.com/molecule-man/go-brrr v1.3.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= +github.com/mymmrac/telego v1.13.0 h1:1sz4F5bstBJYjZNPPJykYBT0HHIIKvPLvARZt45swM0= +github.com/mymmrac/telego v1.13.0/go.mod h1:gsRatcXPP0UBU9gWbKzp21yQWoPHte86AUKrVcikuaw= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/nicksnyder/go-i18n/v2 v2.7.0 h1:oiVQUmuCeNggvm/fUVb6/R0aP82BDVphZnmVHwut+J0= +github.com/nicksnyder/go-i18n/v2 v2.7.0/go.mod h1:ZMYiWg8ndQSGNk4zbzbyJjrrVjQjuQ8pERFrnBik+c8= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= +github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= +github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.78.0 h1:tKfLdx7cD8HZOTP1wc2OpbQMbgO1HP12J0y/XMdyW6Q= +github.com/valyala/fasthttp v1.78.0/go.mod h1:8NXUY/ZXyjqEWN5cbfIdAAv+ES+5yfcl2EGNo872KzQ= +github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4= +github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= +go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= +modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.38.1 h1:wdxJVBuFT8JufZnnQyS6Bbz3NOWhViD0xJOGR96Bpd4= +modernc.org/ccgo/v4 v4.38.1/go.mod h1:kOpEkJRbFwBvjUWwn4j1j9B7iFHbl1+orhgTMCDkDBk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A= +modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= +modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 0000000..011cbf8 --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,97 @@ +// Package api is the HTTP server of the core: health checks today, the +// Telegram webhook when enabled, and later the worker and Mini App APIs. +package api + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net" + "net/http" + "time" +) + +// Server is the core HTTP server. +type Server struct { + mux *http.ServeMux + srv *http.Server + log *slog.Logger + health func(ctx context.Context) error + ln net.Listener +} + +// New creates the server. health reports whether the core can serve; it is +// called on every /healthz request. +func New(listen string, health func(ctx context.Context) error, log *slog.Logger) *Server { + if log == nil { + log = slog.Default() + } + s := &Server{mux: http.NewServeMux(), log: log, health: health} + s.srv = &http.Server{ + Addr: listen, + Handler: s.mux, + ReadHeaderTimeout: 10 * time.Second, + } + s.mux.HandleFunc("GET /healthz", s.handleHealth) + return s +} + +// Mux exposes the router so other parts can add their routes. +func (s *Server) Mux() *http.ServeMux { return s.mux } + +func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + defer cancel() + status, code := "ok", http.StatusOK + if s.health != nil { + if err := s.health(ctx); err != nil { + s.log.Warn("health check failed", "err", err) + status, code = "unavailable", http.StatusServiceUnavailable + } + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(map[string]string{"status": status}) +} + +// Listen binds the address. It is separate from Serve so startup fails +// early when the port is taken. +func (s *Server) Listen() error { + ln, err := net.Listen("tcp", s.srv.Addr) + if err != nil { + return err + } + s.ln = ln + return nil +} + +// Addr returns the bound address, useful when the port was 0. +func (s *Server) Addr() string { + if s.ln == nil { + return s.srv.Addr + } + return s.ln.Addr().String() +} + +// Serve runs until ctx ends, then shuts down gracefully. +func (s *Server) Serve(ctx context.Context) error { + if s.ln == nil { + if err := s.Listen(); err != nil { + return err + } + } + errc := make(chan error, 1) + go func() { errc <- s.srv.Serve(s.ln) }() + select { + case err := <-errc: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return err + case <-ctx.Done(): + shutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.srv.Shutdown(shutCtx) + } +} diff --git a/internal/app/app.go b/internal/app/app.go new file mode 100644 index 0000000..3917fdc --- /dev/null +++ b/internal/app/app.go @@ -0,0 +1,287 @@ +// Package app wires the core together. cmd/core and the end-to-end tests +// both start the bot through it, so tests exercise the real startup path. +package app + +import ( + "context" + "fmt" + "log/slog" + "os" + "strings" + "sync" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/api" + "github.com/noderunners/dlbot/internal/bot" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/tg" + "github.com/noderunners/dlbot/internal/worker" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/locales" +) + +// Options configure a core instance. +type Options struct { + Config config.Config + Log *slog.Logger + // Runner replaces the real yt-dlp, for tests. + Runner ytdlp.Runner + // Tune is called with the bot before it starts, for tests. + Tune func(*bot.Bot) +} + +// App is a running core. +type App struct { + cfg config.Config + log *slog.Logger + DB *db.DB + Store *db.Store + Storage storage.Storage + Sched *sched.Scheduler + Service *service.Service + Bot *bot.Bot + HTTP *api.Server + + tgBot *telego.Bot + runner ytdlp.Runner + worker *worker.Worker + ready chan struct{} +} + +// Ready is closed once the core is listening and receiving updates. +func (a *App) Ready() <-chan struct{} { return a.ready } + +// NewLogger builds the process logger from the config. Every secret given +// is blanked out of all log output, whatever field it shows up in. This +// matters because HTTP client errors quote the request URL, and Bot API +// URLs contain the bot token. +func NewLogger(cfg config.Log, secrets ...string) *slog.Logger { + var level slog.Level + if err := level.UnmarshalText([]byte(cfg.Level)); err != nil { + level = slog.LevelInfo + } + opts := &slog.HandlerOptions{Level: level, ReplaceAttr: Redactor(secrets...)} + if strings.EqualFold(cfg.Format, "text") { + return slog.New(slog.NewTextHandler(os.Stderr, opts)) + } + return slog.New(slog.NewJSONHandler(os.Stderr, opts)) +} + +// Redactor returns a slog ReplaceAttr function that removes the secrets +// from string and error values. +func Redactor(secrets ...string) func(groups []string, a slog.Attr) slog.Attr { + var pairs []string + for _, s := range secrets { + if len(s) >= 6 { // too short to be a secret, and it would mangle logs + pairs = append(pairs, s, "[REDACTED]") + } + } + if len(pairs) == 0 { + return nil + } + r := strings.NewReplacer(pairs...) + return func(_ []string, a slog.Attr) slog.Attr { + switch a.Value.Kind() { + case slog.KindString: + a.Value = slog.StringValue(r.Replace(a.Value.String())) + case slog.KindAny: + switch v := a.Value.Any().(type) { + case error: + a.Value = slog.StringValue(r.Replace(v.Error())) + case fmt.Stringer: + a.Value = slog.StringValue(r.Replace(v.String())) + } + } + return a + } +} + +// Secrets lists the configured values that must never appear in logs. +func Secrets(cfg config.Config) []string { + return []string{cfg.Telegram.Token, cfg.Telegram.WebhookSecret} +} + +// New opens the database and storage and builds every component. Nothing +// runs until Run is called. +func New(ctx context.Context, opts Options) (*App, error) { + cfg := opts.Config + log := opts.Log + if log == nil { + log = NewLogger(cfg.Log, Secrets(cfg)...) + } + a := &App{cfg: cfg, log: log, ready: make(chan struct{})} + + var err error + if a.DB, err = db.Open(ctx, cfg.Database.Driver, cfg.Database.DSN); err != nil { + return nil, err + } + fail := func(err error) (*App, error) { + a.DB.Close() + return nil, err + } + if err := a.DB.Migrate(ctx); err != nil { + return fail(err) + } + a.Store = a.DB.Store() + + switch cfg.Storage.Backend { + case "local": + if a.Storage, err = storage.NewLocal(cfg.Storage.LocalDir); err != nil { + return fail(err) + } + default: + return fail(fmt.Errorf("app: storage backend %q is not available in this version", cfg.Storage.Backend)) + } + + tr, err := i18n.Load(locales.FS, log) + if err != nil { + return fail(err) + } + + a.runner = opts.Runner + if a.runner == nil { + a.runner = &ytdlp.Exec{ + Path: cfg.Worker.YtDlpPath, + FfmpegPath: cfg.Worker.FfmpegPath, + ProbeTimeout: cfg.Worker.ProbeTimeout.D(), + DownloadTimeout: cfg.Worker.DownloadTimeout.D(), + } + } + + a.Sched = sched.New(a.Store, sched.Config{ + Lease: cfg.Queue.Lease.D(), + FreeMaxLen: cfg.Queue.FreeMaxLen, + MaxAttempts: cfg.Queue.MaxAttempts, + }, log) + a.Service = service.New(cfg, a.Store, a.Sched, a.runner, log) + + if a.tgBot, err = tg.NewBot(cfg.Telegram.Token, cfg.Telegram.APIURL); err != nil { + return fail(fmt.Errorf("app: telegram client: %w", err)) + } + a.Bot, err = bot.New(ctx, bot.Deps{ + API: a.tgBot, + Config: cfg, + Store: a.Store, + Sched: a.Sched, + Service: a.Service, + Storage: a.Storage, + I18n: tr, + Log: log, + WorkerSlots: func() int { return cfg.Worker.Concurrency }, + }) + if err != nil { + return fail(err) + } + if opts.Tune != nil { + opts.Tune(a.Bot) + } + + a.HTTP = api.New(cfg.HTTP.Listen, func(ctx context.Context) error { return a.DB.SQL.PingContext(ctx) }, log) + + if cfg.Worker.Embedded { + a.worker = worker.New(worker.Config{ + ID: "embedded", + Concurrency: cfg.Worker.Concurrency, + TempDir: cfg.Worker.TempDir, + Heartbeat: cfg.Queue.Heartbeat.D(), + ClaimWait: 5 * time.Second, + }, &sched.Local{Sched: a.Sched, Storage: a.Storage}, a.runner, log) + } + return a, nil +} + +// allowedUpdates is the list of update types the bot asks Telegram for. +var allowedUpdates = []string{"message", "callback_query"} + +// Run starts every loop and blocks until ctx ends. Shutdown is ordered: +// updates stop first, then the worker hands back its jobs, then the +// database closes. +func (a *App) Run(ctx context.Context) error { + defer a.DB.Close() + if err := a.HTTP.Listen(); err != nil { + return fmt.Errorf("app: http listen: %w", err) + } + + updates, err := a.updates(ctx) + if err != nil { + if ctx.Err() != nil { + return nil // asked to stop while still starting + } + return err + } + a.Bot.RegisterCommands(ctx) + close(a.ready) + a.log.Info("core started", "bot", a.Bot.Username(), "mode", a.cfg.Telegram.Mode, + "http", a.HTTP.Addr(), "db", a.cfg.Database.Driver, "storage", a.cfg.Storage.Backend, + "embedded_worker", a.cfg.Worker.Embedded) + + var wg sync.WaitGroup + run := func(fn func()) { + wg.Add(1) + go func() { + defer wg.Done() + fn() + }() + } + errc := make(chan error, 1) + run(func() { + if err := a.HTTP.Serve(ctx); err != nil { + select { + case errc <- fmt.Errorf("app: http: %w", err): + default: + } + } + }) + run(func() { a.Sched.Run(ctx) }) + if a.worker != nil { + run(func() { a.worker.Run(ctx) }) + } + run(func() { a.Bot.Run(ctx, updates) }) + + var runErr error + select { + case <-ctx.Done(): + case runErr = <-errc: + } + wg.Wait() + a.log.Info("core stopped") + return runErr +} + +func (a *App) updates(ctx context.Context) (<-chan telego.Update, error) { + t := a.cfg.Telegram + if t.Mode == "webhook" { + hook := strings.TrimRight(t.WebhookURL, "/") + "/telegram/webhook" + var secret []string + if t.WebhookSecret != "" { + secret = append(secret, t.WebhookSecret) + } + ch, err := a.tgBot.UpdatesViaWebhook(ctx, + telego.WebhookHTTPServeMux(a.HTTP.Mux(), "POST /telegram/webhook", secret...), + telego.WithWebhookSet(ctx, &telego.SetWebhookParams{ + URL: hook, SecretToken: t.WebhookSecret, AllowedUpdates: allowedUpdates, + })) + if err != nil { + return nil, fmt.Errorf("app: webhook: %w", err) + } + return ch, nil + } + // A webhook left over from an earlier run would make getUpdates fail. + if err := a.tgBot.DeleteWebhook(ctx, &telego.DeleteWebhookParams{}); err != nil { + return nil, fmt.Errorf("app: deleteWebhook: %w", err) + } + ch, err := a.tgBot.UpdatesViaLongPolling(ctx, &telego.GetUpdatesParams{ + Timeout: 30, AllowedUpdates: allowedUpdates, + }, telego.WithLongPollingRetryTimeout(3*time.Second)) + if err != nil { + return nil, fmt.Errorf("app: long polling: %w", err) + } + return ch, nil +} diff --git a/internal/app/app_test.go b/internal/app/app_test.go new file mode 100644 index 0000000..7ef98fb --- /dev/null +++ b/internal/app/app_test.go @@ -0,0 +1,811 @@ +package app_test + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/noderunners/dlbot/internal/app" + "github.com/noderunners/dlbot/internal/bot" + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/tg/fakeserver" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/internal/ytdlp/ytdlptest" +) + +// harness runs the real core against a fake Bot API and a scripted yt-dlp. +type harness struct { + t *testing.T + srv *fakeserver.Server + fake *ytdlptest.Fake + runner ytdlp.Runner + app *app.App + cfg config.Config + cancel context.CancelFunc + done chan error +} + +const ( + alice = int64(42) + bob = int64(43) + group = int64(-1001234567890) + link = "https://example.com/watch?v=1" +) + +func start(t *testing.T, fake *ytdlptest.Fake, mut func(*config.Config)) *harness { + t.Helper() + if fake == nil { + fake = &ytdlptest.Fake{} + } + h := startWithRunner(t, fake, mut) + h.fake = fake + return h +} + +func startWithRunner(t *testing.T, runner ytdlp.Runner, mut func(*config.Config)) *harness { + t.Helper() + dir := t.TempDir() + srv := fakeserver.New() + cfg := config.Default() + cfg.Telegram.Token = fakeserver.Token + cfg.Telegram.APIURL = srv.URL() + cfg.HTTP.Listen = "127.0.0.1:0" + cfg.Database.DSN = filepath.Join(dir, "bot.db") + cfg.Storage.LocalDir = filepath.Join(dir, "files") + cfg.Worker.TempDir = filepath.Join(dir, "tmp") + cfg.Queue.Lease = config.Duration(2 * time.Second) + cfg.Queue.Heartbeat = config.Duration(40 * time.Millisecond) + if mut != nil { + mut(&cfg) + } + h := &harness{t: t, srv: srv, runner: runner, cfg: cfg} + h.boot() + t.Cleanup(func() { + h.stop() + srv.Close() + }) + return h +} + +// boot starts (or restarts) the core on the same database and storage. +func (h *harness) boot() { + h.t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + a, err := app.New(ctx, app.Options{ + Config: h.cfg, + Log: slog.New(slog.NewTextHandler(io.Discard, nil)), + Runner: h.runner, + Tune: func(b *bot.Bot) { b.SetTimings(60*time.Millisecond, 0) }, + }) + if err != nil { + cancel() + h.t.Fatalf("app.New: %v", err) + } + h.app, h.cancel, h.done = a, cancel, make(chan error, 1) + go func() { h.done <- a.Run(ctx) }() + select { + case <-a.Ready(): + case err := <-h.done: + h.t.Fatalf("app.Run stopped during startup: %v", err) + case <-time.After(10 * time.Second): + h.t.Fatal("the core did not become ready") + } +} + +func (h *harness) stop() { + if h.cancel == nil { + return + } + h.cancel() + h.cancel = nil + select { + case err := <-h.done: + if err != nil { + h.t.Errorf("app.Run: %v", err) + } + case <-time.After(15 * time.Second): + h.t.Error("the core did not shut down") + } +} + +// wait blocks until the bot makes a matching call after sequence "after". +func (h *harness) wait(after int, method string, match func(fakeserver.Call) bool) fakeserver.Call { + h.t.Helper() + c, ok := h.srv.WaitFor(after, 10*time.Second, method, match) + if !ok { + var sb strings.Builder + for _, c := range h.srv.Calls("") { + if c.Seq > after { + fmt.Fprintf(&sb, "\n #%d %s chat=%s text=%q", c.Seq, c.Method, c.Params["chat_id"], c.Text()) + } + } + h.t.Fatalf("no %s call matched. Calls since #%d:%s", method, after, sb.String()) + } + return c +} + +// never asserts that no matching call shows up for a short while. +func (h *harness) never(after int, method string, match func(fakeserver.Call) bool) { + h.t.Helper() + if c, ok := h.srv.WaitFor(after, 400*time.Millisecond, method, match); ok { + h.t.Fatalf("unexpected %s call: %+v", method, c.Params) + } +} + +func textHas(sub string) func(fakeserver.Call) bool { + return func(c fakeserver.Call) bool { return strings.Contains(c.Text(), sub) } +} + +func textIs(want string) func(fakeserver.Call) bool { + return func(c fakeserver.Call) bool { return c.Text() == want } +} + +const edits = "editMessageText|editMessageCaption" + +// card sends a link and returns the card call. +func (h *harness) card(chat, user int64, text string, opts ...fakeserver.MsgOpt) fakeserver.Call { + h.t.Helper() + seq := h.srv.Seq() + h.srv.PushMessage(chat, user, text, opts...) + return h.wait(seq, "sendPhoto|editMessageText", func(c fakeserver.Call) bool { + _, ok := c.Button("dl:") + return ok + }) +} + +func (h *harness) press(chat, user int64, card fakeserver.Call, prefix string) (seq int) { + h.t.Helper() + btn, ok := card.Button(prefix) + if !ok { + h.t.Fatalf("no button starting with %q in %+v", prefix, card.Buttons()) + } + seq = h.srv.Seq() + h.srv.PushCallback(chat, user, card.MessageID, btn.Data) + return seq +} + +func replyTarget(c fakeserver.Call) int { + var rp struct { + MessageID int `json:"message_id"` + } + _ = json.Unmarshal([]byte(c.Params["reply_parameters"]), &rp) + return rp.MessageID +} + +func (h *harness) jobs(status string) []*db.Job { + h.t.Helper() + js, err := h.app.Store.JobsByStatus(context.Background(), status, 100) + if err != nil { + h.t.Fatal(err) + } + return js +} + +func (h *harness) waitJobs(status string, n int) []*db.Job { + h.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + js := h.jobs(status) + if len(js) == n { + return js + } + if time.Now().After(deadline) { + h.t.Fatalf("%d jobs in %s, want %d", len(js), status, n) + } + time.Sleep(20 * time.Millisecond) + } +} + +func (h *harness) storedFiles() int { + n := 0 + _ = h.app.Storage.List(context.Background(), "", func(storage.Object) error { n++; return nil }) + return n +} + +// --- acceptance: pasting a link returns the file --------------------------- + +func TestPrivateLinkReturnsFile(t *testing.T) { + h := start(t, &ytdlptest.Fake{FileSize: 4096}, nil) + seq := h.srv.Seq() + msgID := h.srv.PushMessage(alice, alice, "look at this "+link) + + h.wait(seq, "sendMessage", textHas("Looking up")) + card := h.wait(seq, "sendPhoto", nil) + if !strings.Contains(card.Text(), "Test Video") || !strings.Contains(card.Text(), "1:00") || + !strings.Contains(card.Text(), "example.com") { + t.Fatalf("card text = %q", card.Text()) + } + if card.Params["photo"] != "https://img.example.com/t.jpg" { + t.Fatalf("card photo = %q", card.Params["photo"]) + } + if replyTarget(card) != msgID { + t.Fatalf("the card must reply to the link message") + } + var labels []string + for _, b := range card.Buttons() { + labels = append(labels, b.Text) + // Callback data carries identifiers only, never translated text. + if strings.ContainsAny(b.Data, " ") || len(b.Data) > 64 { + t.Errorf("bad callback data %q", b.Data) + } + } + want := []string{"Best · 10.0 MB", "480p · 5.0 MB", "MP3 · 1.0 MB", "Thumbnail", "Cancel"} + if strings.Join(labels, "|") != strings.Join(want, "|") { + t.Fatalf("buttons = %v, want %v", labels, want) + } + // The placeholder is replaced by the photo card. + h.wait(seq, "deleteMessage", nil) + + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "answerCallbackQuery", nil) + video := h.wait(seq, "sendVideo", nil) + if video.ChatID() != alice || video.Files["video"].Size != 4096 { + t.Fatalf("sendVideo = %+v files=%+v", video.Params, video.Files) + } + if video.Files["video"].Name != "Test Video.mp4" { + t.Fatalf("file name = %q", video.Files["video"].Name) + } + if video.Params["supports_streaming"] != "true" || video.Params["width"] != "1280" || video.Params["duration"] != "60" { + t.Fatalf("video params = %+v", video.Params) + } + if replyTarget(video) != msgID { + t.Fatalf("the file must reply to the link message") + } + done := h.wait(seq, "editMessageCaption", textHas("Done")) + if done.MessageID != card.MessageID || len(done.Buttons()) != 0 { + t.Fatalf("the card must end as a status without buttons: %+v", done.Params) + } + + h.waitJobs(db.JobDone, 1) + if n := h.storedFiles(); n != 0 { + t.Fatalf("%d files left in storage after delivery", n) + } + if n := len(h.fake.Probes()); n != 1 { + t.Fatalf("probes = %d, want 1", n) + } +} + +func TestStatusGoesThroughDownloadingAndUploading(t *testing.T) { + block := make(chan struct{}) + h := start(t, &ytdlptest.Fake{Block: block, FileSize: 2000}, nil) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + + // The fake reports half of the file before it blocks. + down := h.wait(seq, edits, textHas("50%")) + if !strings.Contains(down.Text(), "Downloading") || !strings.Contains(down.Text(), "▰▰▰▰▰▱▱▱▱▱") || + !strings.Contains(down.Text(), "1,000 B of 2 KB") { + t.Fatalf("progress text = %q", down.Text()) + } + if _, ok := down.Button("jc:"); !ok { + t.Fatal("a running job must offer Cancel") + } + close(block) + h.wait(seq, edits, textHas("Sending it to Telegram")) + h.wait(seq, "sendChatAction", func(c fakeserver.Call) bool { return c.Params["action"] == "upload_video" }) + h.wait(seq, "sendVideo", nil) + h.wait(seq, edits, textHas("Done")) +} + +// --- acceptance: groups work with /dl -------------------------------------- + +func TestGroupDlCommand(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + cmdID := h.srv.PushMessage(group, alice, "/dl@"+fakeserver.BotUsername+" "+link) + card := h.wait(seq, "sendPhoto", nil) + if card.ChatID() != group || replyTarget(card) != cmdID { + t.Fatalf("the card must reply to the command in the group: %+v", card.Params) + } + + // Somebody else presses a button: a short notice, no job. + seq = h.press(group, bob, card, "dl:") + notice := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(notice.Params["text"], "belong to the person who asked") { + t.Fatalf("notice = %q", notice.Params["text"]) + } + h.never(seq, "sendVideo", nil) + if n := len(h.jobs(db.JobQueued)) + len(h.jobs(db.JobRunning)); n != 0 { + t.Fatalf("a stranger's press created %d jobs", n) + } + // The stranger cannot dismiss the card either. + seq = h.press(group, bob, card, "cx:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "belong to the person who asked") + }) + h.never(seq, "deleteMessage", nil) + + seq = h.press(group, alice, card, "dl:"+strings.Split(card.Buttons()[0].Data, ":")[1]+":480") + video := h.wait(seq, "sendVideo", nil) + if video.ChatID() != group || replyTarget(video) != cmdID { + t.Fatalf("the file must reply to the original message: %+v", video.Params) + } + if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "480" { + t.Fatalf("downloads = %+v", dl) + } +} + +func TestGroupReplyDlUsesTheRepliedMessage(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl", fakeserver.ReplyTo(555, "watch "+link+" tonight")) + card := h.wait(seq, "sendPhoto", nil) + if replyTarget(card) != 555 { + t.Fatalf("card replies to %d, want the message with the link (555)", replyTarget(card)) + } + if got := h.fake.Probes(); len(got) != 1 || got[0] != link { + t.Fatalf("probed %v", got) + } +} + +func TestGroupIgnoresPlainLinksAndForeignCommands(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(group, alice, "check "+link) + h.srv.PushMessage(group, alice, "/dl@some_other_bot "+link) + h.srv.PushMessage(group, alice, "/unknowncommand") + h.never(seq, "", nil) + if n := len(h.fake.Probes()); n != 0 { + t.Fatalf("probes = %d, want 0", n) + } + // /dl without a link explains itself. + seq = h.srv.Seq() + h.srv.PushMessage(group, alice, "/dl") + h.wait(seq, "sendMessage", textHas("Add a link after the command")) +} + +// --- acceptance: cancel works ---------------------------------------------- + +func TestCancelCardBeforeChoosing(t *testing.T) { + h := start(t, nil, nil) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "cx:") + h.wait(seq, "answerCallbackQuery", textIs("Cancelled.")) + h.wait(0, "deleteMessage", func(c fakeserver.Call) bool { + return c.Params["message_id"] == fmt.Sprint(card.MessageID) + }) + // The card is dead: its format buttons no longer start anything. + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "answerCallbackQuery", nil) + h.never(seq, "sendVideo", nil) +} + +func TestCancelRunningJob(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := start(t, &ytdlptest.Fake{Block: block}, nil) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + status := h.wait(seq, edits, textHas("Downloading")) + + // Bob cannot cancel Alice's download. + seq = h.press(alice, bob, status, "jc:") + h.wait(seq, "answerCallbackQuery", func(c fakeserver.Call) bool { + return strings.Contains(c.Params["text"], "belong to the person who asked") + }) + if len(h.jobs(db.JobRunning)) != 1 { + t.Fatal("the job must keep running") + } + + seq = h.press(alice, alice, status, "jc:") + cancelled := h.wait(seq, edits, textHas("Cancelled")) + if len(cancelled.Buttons()) != 0 { + t.Fatal("a cancelled status must have no buttons") + } + h.waitJobs(db.JobCancelled, 1) + h.never(seq, "sendVideo", nil) + if n := h.storedFiles(); n != 0 { + t.Fatalf("%d files left in storage after cancel", n) + } +} + +func TestCancelCommandCancelsQueuedAndRunning(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { + c.Worker.Concurrency = 1 + c.Limits.Free.ActiveJobs = 3 + }) + for i := 0; i < 2; i++ { + card := h.card(alice, alice, fmt.Sprintf("https://example.com/v%d", i)) + h.press(alice, alice, card, "dl:") + } + h.waitJobs(db.JobRunning, 1) + h.waitJobs(db.JobQueued, 1) + + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/queue") + h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { + return strings.Contains(c.Text(), "2 downloads in progress") && strings.Contains(c.Text(), "In the queue. Position 1") + }) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/cancel") + h.wait(seq, "sendMessage", textHas("Cancelled 2 downloads.")) + h.waitJobs(db.JobCancelled, 2) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/cancel") + h.wait(seq, "sendMessage", textHas("nothing to cancel")) +} + +// --- failures -------------------------------------------------------------- + +func TestDownloadFailureShowsFriendlyError(t *testing.T) { + raw := "ERROR: [youtube] abc: Private video. token=SECRET" + h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{ + link: {&ytdlp.Error{Code: ytdlp.CodePrivate, Raw: raw}}, + }}, nil) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + failed := h.wait(seq, edits, textHas("That did not work")) + if !strings.Contains(failed.Text(), "private or for members only") { + t.Fatalf("failure text = %q", failed.Text()) + } + for _, c := range h.srv.Calls("") { + if strings.Contains(c.Text(), "SECRET") || strings.Contains(c.Text(), "ERROR:") { + t.Fatalf("raw yt-dlp output reached the user: %q", c.Text()) + } + } + h.waitJobs(db.JobFailed, 1) + h.never(seq, "sendVideo", nil) +} + +func TestRetryableFailureIsRetriedOnce(t *testing.T) { + h := start(t, &ytdlptest.Fake{DownloadErrs: map[string][]error{ + link: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "reset"}}, + }}, nil) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", nil) + if n := len(h.fake.Downloads()); n != 2 { + t.Fatalf("downloads = %d, want 2 (one retry)", n) + } +} + +func TestProbeFailureShowsFriendlyError(t *testing.T) { + h := start(t, &ytdlptest.Fake{ProbeErrs: map[string]error{ + link: &ytdlp.Error{Code: ytdlp.CodeUnsupported, Raw: "ERROR: Unsupported URL"}, + }}, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, link) + h.wait(seq, "editMessageText", textHas("I cannot download from that link")) +} + +func TestPlaylistLinkIsExplained(t *testing.T) { + h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{ + link: {Type: "playlist", ID: "PL", Title: "List"}, + }}, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, link) + h.wait(seq, "editMessageText", textHas("playlist")) +} + +func TestThumbnailFetchFailureFallsBackToTextCard(t *testing.T) { + h := start(t, nil, nil) + h.srv.FailNext("sendPhoto", 400, "Bad Request: wrong file identifier/HTTP URL specified") + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, link) + card := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { _, ok := c.Button("dl:"); return ok }) + + // The text card works exactly like the photo card. + seq = h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", nil) + done := h.wait(seq, "editMessageText", textHas("Done")) + if done.MessageID != card.MessageID { + t.Fatal("the text card must become the status message") + } +} + +func TestRejectedVideoIsSentAsDocument(t *testing.T) { + h := start(t, nil, nil) + card := h.card(alice, alice, link) + h.srv.FailNext("sendVideo", 400, "Bad Request: wrong file type") + seq := h.press(alice, alice, card, "dl:") + doc := h.wait(seq, "sendDocument", nil) + if doc.Files["document"].Size != 1024 { + t.Fatalf("document upload = %+v", doc.Files) + } + h.wait(seq, edits, textHas("Done")) +} + +func TestTransientSendFailureIsRetried(t *testing.T) { + h := start(t, nil, nil) + card := h.card(alice, alice, link) + h.srv.FailNext("sendVideo", 500, "Internal Server Error") + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, "sendVideo", func(c fakeserver.Call) bool { return !c.Failed }) + h.wait(seq, edits, textHas("Done")) + h.waitJobs(db.JobDone, 1) +} + +func TestSendGivesUpAfterRepeatedFailures(t *testing.T) { + h := start(t, nil, nil) + card := h.card(alice, alice, link) + for i := 0; i < 3; i++ { + h.srv.FailNext("sendVideo", 500, "Internal Server Error") + } + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, textHas("could not send the file to Telegram")) + h.waitJobs(db.JobDone, 1) // the job itself is closed and cleaned up + if n := h.storedFiles(); n != 0 { + t.Fatalf("%d files left in storage", n) + } +} + +// --- limits ---------------------------------------------------------------- + +func TestOverSizeAndOverDurationAreRefused(t *testing.T) { + big := "https://example.com/big" + long := "https://example.com/long" + h := start(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{ + big: {Type: "video", ID: "b", Title: "Big", Extractor: "fake", Duration: 60, + Formats: []ytdlp.Format{{Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 1080, Filesize: 80 << 20}}}, + long: {Type: "video", ID: "l", Title: "Long", Extractor: "fake", Duration: 3600}, + }}, nil) + + card := h.card(alice, alice, big) + seq := h.press(alice, alice, card, "dl:") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "larger than your limit of 50.0 MB") || alert.Params["show_alert"] != "true" { + t.Fatalf("alert = %+v", alert.Params) + } + // The card stays usable: the thumbnail-free card still lets the user + // pick something else, here MP3 is absent so we only check no job ran. + h.never(seq, "sendVideo|sendDocument", nil) + + card = h.card(alice, alice, long) + seq = h.press(alice, alice, card, "dl:") + alert = h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "longer than your limit of 10 minutes") { + t.Fatalf("alert = %+v", alert.Params) + } + if n := len(h.fake.Downloads()); n != 0 { + t.Fatalf("downloads = %d, want 0", n) + } +} + +func TestWorkerEnforcesCapWhenMetadataHasNoSize(t *testing.T) { + // The card cannot know the size, the worker finds out and stops. + h := start(t, &ytdlptest.Fake{FileSize: 3 << 20, Infos: map[string]*ytdlp.Info{ + link: {Type: "video", ID: "x", Title: "No Sizes", Extractor: "fake"}, + }}, func(c *config.Config) { c.Limits.Free.MaxSizeMB = 2 }) + card := h.card(alice, alice, link) + seq := h.press(alice, alice, card, "dl:") + h.wait(seq, edits, textHas("larger than your limit")) + h.never(seq, "sendVideo", nil) +} + +func TestOneActiveJobPerFreeUser(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := start(t, &ytdlptest.Fake{Block: block}, nil) + first := h.card(alice, alice, "https://example.com/a") + second := h.card(alice, alice, "https://example.com/b") + h.press(alice, alice, first, "dl:") + h.waitJobs(db.JobRunning, 1) + + seq := h.press(alice, alice, second, "dl:") + alert := h.wait(seq, "answerCallbackQuery", nil) + if !strings.Contains(alert.Params["text"], "already have 1 download running") { + t.Fatalf("alert = %q", alert.Params["text"]) + } + // Another user is not affected. + other := h.card(bob, bob, "https://example.com/c") + h.press(bob, bob, other, "dl:") + h.waitJobs(db.JobRunning, 2) +} + +func TestDoubleTapStartsOneJob(t *testing.T) { + block := make(chan struct{}) + defer close(block) + h := start(t, &ytdlptest.Fake{Block: block}, func(c *config.Config) { c.Limits.Free.ActiveJobs = 5 }) + card := h.card(alice, alice, link) + btn, _ := card.Button("dl:") + for i := 0; i < 4; i++ { + h.srv.PushCallback(alice, alice, card.MessageID, btn.Data) + } + h.waitJobs(db.JobRunning, 1) + time.Sleep(300 * time.Millisecond) + if n := len(h.jobs(db.JobRunning)) + len(h.jobs(db.JobQueued)); n != 1 { + t.Fatalf("%d jobs after a quadruple tap, want 1", n) + } +} + +// --- other commands -------------------------------------------------------- + +func TestAudioCommandSkipsTheCard(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/audio "+link) + audio := h.wait(seq, "sendAudio", nil) + if audio.Files["audio"].Name != "Test Video.mp3" || audio.Params["title"] != "Test Video" || audio.Params["performer"] != "Tester" { + t.Fatalf("sendAudio = %+v files=%+v", audio.Params, audio.Files) + } + h.wait(seq, "editMessageText", textHas("Done")) + if len(h.srv.Calls("sendPhoto")) != 0 { + t.Fatal("/audio must not show a card") + } +} + +func TestThumbCommandSendsPhoto(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/thumb "+link) + photo := h.wait(seq, "sendPhoto", func(c fakeserver.Call) bool { _, up := c.Files["photo"]; return up }) + if photo.Files["photo"].Name != "Test Video.jpg" { + t.Fatalf("photo upload = %+v", photo.Files) + } +} + +func TestInfoCommandListsFormatsWithoutDownloading(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/info "+link) + info := h.wait(seq, "sendMessage", textHas("Test Video")) + for _, want := range []string{"Best: 10.0 MB", "720p: 10.0 MB", "480p: 5.0 MB", "MP3: 1.0 MB", "Tester"} { + if !strings.Contains(info.Text(), want) { + t.Errorf("info text lacks %q: %q", want, info.Text()) + } + } + if strings.Contains(info.Text(), "1080p") { + t.Errorf("1080p is above the source height and must not be listed: %q", info.Text()) + } + if n := len(h.fake.Downloads()); n != 0 { + t.Fatalf("/info downloaded %d files", n) + } +} + +func TestStartHelpAndHints(t *testing.T) { + h := start(t, nil, nil) + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, "/start", fakeserver.From("Ana ", "ana")) + welcome := h.wait(seq, "sendMessage", textHas("welcome")) + if !strings.Contains(welcome.Text(), "Ana <b>") { + t.Fatalf("the name must be escaped: %q", welcome.Text()) + } + if welcome.Params["parse_mode"] != "HTML" { + t.Fatalf("parse_mode = %q", welcome.Params["parse_mode"]) + } + u, err := h.app.Store.GetUser(context.Background(), alice) + if err != nil || u.Username != "ana" || u.FirstName != "Ana " || u.Lang != "en" { + t.Fatalf("user row = %+v, %v", u, err) + } + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/help") + h.wait(seq, "sendMessage", textHas("Up to 50.0 MB and 10 minutes per download")) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "hello bot") + h.wait(seq, "sendMessage", textHas("Send me a link")) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "/nope") + h.wait(seq, "sendMessage", textHas("do not know that command")) + + seq = h.srv.Seq() + h.srv.PushMessage(alice, alice, "http://127.0.0.1:8080/admin") + h.wait(seq, "sendMessage", textHas("Send me a link")) + if n := len(h.fake.Probes()); n != 0 { + t.Fatalf("a private address was probed %d times", n) + } +} + +// --- durability ------------------------------------------------------------ + +func TestRestartResumesQueuedJob(t *testing.T) { + block := make(chan struct{}) + fake := &ytdlptest.Fake{Block: block} + h := start(t, fake, nil) + card := h.card(alice, alice, link) + h.press(alice, alice, card, "dl:") + h.waitJobs(db.JobRunning, 1) + + // Stop the core in the middle of the download. The worker hands the + // job back, and the next start picks it up and delivers it. + h.stop() + close(block) + seq := h.srv.Seq() + h.boot() + video := h.wait(seq, "sendVideo", nil) + if video.ChatID() != alice { + t.Fatalf("sendVideo after restart = %+v", video.Params) + } + h.wait(seq, edits, textHas("Done")) + h.waitJobs(db.JobDone, 1) +} + +func TestCommandMenuIsRegistered(t *testing.T) { + h := start(t, nil, nil) + calls := h.srv.Calls("setMyCommands") + if len(calls) == 0 { + t.Fatal("setMyCommands was not called") + } + var cmds []struct { + Command string `json:"command"` + Description string `json:"description"` + } + if err := json.Unmarshal([]byte(calls[0].Params["commands"]), &cmds); err != nil { + t.Fatal(err) + } + if len(cmds) != 7 || cmds[0].Command != "dl" || cmds[0].Description != "Download a video from a link" { + t.Fatalf("commands = %+v", cmds) + } + for _, c := range cmds { + if c.Command != strings.ToLower(c.Command) || strings.HasPrefix(c.Description, "menu.") { + t.Errorf("bad menu entry %+v", c) + } + } +} + +func TestHealthEndpoint(t *testing.T) { + h := start(t, nil, nil) + resp, err := http.Get("http://" + h.app.HTTP.Addr() + "/healthz") + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != 200 || !strings.Contains(string(body), `"ok"`) { + t.Fatalf("healthz = %d %s", resp.StatusCode, body) + } +} + +// TestRealYtDlp runs the whole path with the real yt-dlp and ffmpeg against +// a small public test file. It needs network access, so it only runs when +// DLBOT_E2E_YTDLP points at a yt-dlp binary: +// +// DLBOT_E2E_YTDLP=$(command -v yt-dlp) go test ./internal/app -run TestRealYtDlp -v +func TestRealYtDlp(t *testing.T) { + bin := os.Getenv("DLBOT_E2E_YTDLP") + if bin == "" { + t.Skip("set DLBOT_E2E_YTDLP to a yt-dlp binary to run this test") + } + url := os.Getenv("DLBOT_E2E_URL") + if url == "" { + url = "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4" + } + real := &ytdlp.Exec{Path: bin, ProbeTimeout: 60 * time.Second, DownloadTimeout: 3 * time.Minute} + h := startWithRunner(t, real, nil) + + seq := h.srv.Seq() + h.srv.PushMessage(alice, alice, url) + card, ok := h.srv.WaitFor(seq, 90*time.Second, "sendPhoto|editMessageText", func(c fakeserver.Call) bool { + _, ok := c.Button("dl:") + return ok + }) + if !ok { + t.Fatalf("no card for the real link. Calls: %+v", h.srv.Calls("")) + } + t.Logf("card: %q buttons=%v", card.Text(), card.Buttons()) + + seq = h.press(alice, alice, card, "dl:") + video, ok := h.srv.WaitFor(seq, 3*time.Minute, "sendVideo|sendDocument", nil) + if !ok { + var last string + for _, c := range h.srv.Calls("") { + if c.Text() != "" { + last = c.Text() + } + } + t.Fatalf("the real download was not delivered. Last status: %q", last) + } + f := video.Files["video"] + t.Logf("delivered via %s: %s (%d bytes), duration=%s %sx%s", video.Method, f.Name, f.Size, + video.Params["duration"], video.Params["width"], video.Params["height"]) + if video.Method != "sendVideo" || f.Size < 100_000 || video.Params["duration"] != "10" || + video.Params["width"] != "640" || video.Params["height"] != "360" { + t.Fatalf("unexpected delivery: %+v %+v", video.Params, video.Files) + } +} diff --git a/internal/app/logger_test.go b/internal/app/logger_test.go new file mode 100644 index 0000000..d4230ed --- /dev/null +++ b/internal/app/logger_test.go @@ -0,0 +1,33 @@ +package app + +import ( + "bytes" + "errors" + "log/slog" + "strings" + "testing" +) + +func TestRedactorRemovesSecretsFromLogs(t *testing.T) { + const token = "123456789:FAKEfakeFAKEfakeFAKEfakeFAKEfake-01" + var buf bytes.Buffer + log := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{ReplaceAttr: Redactor(token, "", "abc")})) + + err := errors.New(`Post "https://api.telegram.org/bot` + token + `/sendMessage": context canceled`) + log.Error("request failed: "+token, "err", err, "url", "https://x/bot"+token+"/y", + slog.Group("nested", "token", token), "n", 3) + + out := buf.String() + if strings.Contains(out, token) { + t.Fatalf("the token leaked into the log: %s", out) + } + if strings.Count(out, "[REDACTED]") != 4 { + t.Fatalf("expected the message, the error, the url and the nested value to be redacted: %s", out) + } + if !strings.Contains(out, "context canceled") || !strings.Contains(out, `"n":3`) { + t.Fatalf("the rest of the entry must survive: %s", out) + } + if Redactor("", "abc") != nil { + t.Fatal("without usable secrets no replacer is needed") + } +} diff --git a/internal/bot/bot.go b/internal/bot/bot.go new file mode 100644 index 0000000..1201146 --- /dev/null +++ b/internal/bot/bot.go @@ -0,0 +1,317 @@ +// Package bot is the Telegram front end: it turns updates into requests +// and jobs, keeps the status message of every delivery current and sends +// finished files. +package bot + +import ( + "context" + "fmt" + "log/slog" + "runtime/debug" + "sync" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/config" + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/tg" +) + +// Deps are the collaborators of the bot. +type Deps struct { + API tg.API + Config config.Config + Store *db.Store + Sched *sched.Scheduler + Service *service.Service + Storage storage.Storage + I18n *i18n.Bundle + Log *slog.Logger + // WorkerSlots is the number of download slots serving the queue. It + // only feeds the wait estimate. + WorkerSlots func() int +} + +// Bot handles Telegram updates and job events. +type Bot struct { + api tg.API + cfg config.Config + store *db.Store + sched *sched.Scheduler + svc *service.Service + storage storage.Storage + tr *i18n.Bundle + log *slog.Logger + slots func() int + id int64 + username string + + events chan sched.Event + uploads chan struct{} // limits concurrent uploads to Telegram + bg sync.WaitGroup + baseCtx context.Context + + statusMu sync.Mutex + statuses map[string]*statusState // by delivery ID + sending map[string]bool // jobs being delivered right now + + // Tunables, shortened in tests. + reconcileEvery time.Duration + statusMinGap time.Duration +} + +// New creates the bot and learns its own username, which is needed to +// recognize commands addressed as /cmd@botname. +func New(ctx context.Context, d Deps) (*Bot, error) { + me, err := d.API.GetMe(ctx) + if err != nil { + return nil, fmt.Errorf("bot: getMe: %w", err) + } + if d.Log == nil { + d.Log = slog.Default() + } + if d.WorkerSlots == nil { + d.WorkerSlots = func() int { return 1 } + } + b := &Bot{ + api: d.API, + cfg: d.Config, + store: d.Store, + sched: d.Sched, + svc: d.Service, + storage: d.Storage, + tr: d.I18n, + log: d.Log, + slots: d.WorkerSlots, + id: me.ID, + username: me.Username, + events: make(chan sched.Event, 1024), + uploads: make(chan struct{}, 4), + baseCtx: ctx, + statuses: map[string]*statusState{}, + sending: map[string]bool{}, + reconcileEvery: 5 * time.Second, + statusMinGap: 3 * time.Second, + } + d.Sched.Subscribe(func(ev sched.Event) { + select { + case b.events <- ev: + default: + // The reconcile loop picks up anything dropped here. + } + }) + return b, nil +} + +// Username returns the bot's @username without the at sign. +func (b *Bot) Username() string { return b.username } + +// SetTimings overrides the reconcile interval and the minimum gap between +// status edits. Tests use it to run fast. +func (b *Bot) SetTimings(reconcile, statusGap time.Duration) { + b.reconcileEvery = reconcile + b.statusMinGap = statusGap +} + +// Run processes updates and job events until ctx ends, then waits for +// in-flight work to finish. +func (b *Bot) Run(ctx context.Context, updates <-chan telego.Update) { + b.baseCtx = ctx + n := b.cfg.Telegram.UpdateWorkers + if n < 1 { + n = 1 + } + // Updates of one chat always go to the same worker, so they are + // handled in order. + lanes := make([]chan telego.Update, n) + var wg sync.WaitGroup + for i := range lanes { + lanes[i] = make(chan telego.Update, 64) + wg.Add(1) + go func(ch <-chan telego.Update) { + defer wg.Done() + for u := range ch { + b.safely("update", func() { b.HandleUpdate(ctx, u) }) + } + }(lanes[i]) + } + wg.Add(1) + go func() { + defer wg.Done() + b.eventLoop(ctx) + }() + +loop: + for { + select { + case <-ctx.Done(): + break loop + case u, ok := <-updates: + if !ok { + break loop + } + key := updateChatID(u) + if key < 0 { + key = -key + } + select { + case lanes[int(key%int64(n))] <- u: + case <-ctx.Done(): + break loop + } + } + } + for _, ch := range lanes { + close(ch) + } + wg.Wait() + b.bg.Wait() +} + +// goBG runs fn in the background and tracks it for shutdown. +func (b *Bot) goBG(name string, fn func()) { + b.bg.Add(1) + go func() { + defer b.bg.Done() + b.safely(name, fn) + }() +} + +func (b *Bot) safely(name string, fn func()) { + defer func() { + if r := recover(); r != nil { + b.log.Error("panic recovered", "where", name, "panic", fmt.Sprint(r), "stack", string(debug.Stack())) + } + }() + fn() +} + +func updateChatID(u telego.Update) int64 { + switch { + case u.Message != nil: + return u.Message.Chat.ID + case u.CallbackQuery != nil: + if u.CallbackQuery.Message != nil { + return u.CallbackQuery.Message.GetChat().ID + } + return u.CallbackQuery.From.ID + } + return int64(u.UpdateID) +} + +// HandleUpdate routes one update. +func (b *Bot) HandleUpdate(ctx context.Context, u telego.Update) { + switch { + case u.Message != nil: + b.handleMessage(ctx, u.Message) + case u.CallbackQuery != nil: + b.handleCallback(ctx, u.CallbackQuery) + } +} + +// actor is the user behind an update, with the language to answer in. +type actor struct { + user *db.User + lang string +} + +func (b *Bot) actorFor(ctx context.Context, from *telego.User) (actor, error) { + u, err := b.store.UpsertUser(ctx, from.ID, from.Username, from.FirstName, from.LanguageCode) + if err != nil { + return actor{}, err + } + lang := u.LangOverride + if lang == "" { + lang = b.tr.Resolve(u.Lang) + } + return actor{user: u, lang: lang}, nil +} + +func isPrivate(chatType string) bool { return chatType == telego.ChatTypePrivate } + +// --- sending helpers ------------------------------------------------------- + +func chatID(id int64) telego.ChatID { return telego.ChatID{ID: id} } + +func replyParams(messageID int64) *telego.ReplyParameters { + if messageID == 0 { + return nil + } + return &telego.ReplyParameters{MessageID: int(messageID), AllowSendingWithoutReply: true} +} + +var noPreview = &telego.LinkPreviewOptions{IsDisabled: true} + +// send posts an HTML message, optionally as a reply and with buttons. +func (b *Bot) send(ctx context.Context, chat, replyTo int64, text string, kb *telego.InlineKeyboardMarkup) (*telego.Message, error) { + p := &telego.SendMessageParams{ + ChatID: chatID(chat), + Text: text, + ParseMode: telego.ModeHTML, + LinkPreviewOptions: noPreview, + ReplyParameters: replyParams(replyTo), + } + if kb != nil { + p.ReplyMarkup = kb + } + msg, err := b.api.SendMessage(ctx, p) + if err != nil { + b.log.Warn("sendMessage failed", "chat_id", chat, "err", err) + } + return msg, err +} + +// edit changes the text (or the caption, for photo cards) and the buttons +// of a message. A nil keyboard removes the buttons. +func (b *Bot) edit(ctx context.Context, chat, messageID int64, isPhoto bool, text string, kb *telego.InlineKeyboardMarkup) error { + if messageID == 0 { + return nil + } + var err error + if isPhoto { + _, err = b.api.EditMessageCaption(ctx, &telego.EditMessageCaptionParams{ + ChatID: chatID(chat), MessageID: int(messageID), Caption: clip(text, 1024), + ParseMode: telego.ModeHTML, ReplyMarkup: kb, + }) + } else { + _, err = b.api.EditMessageText(ctx, &telego.EditMessageTextParams{ + ChatID: chatID(chat), MessageID: int(messageID), Text: clip(text, 4096), + ParseMode: telego.ModeHTML, LinkPreviewOptions: noPreview, ReplyMarkup: kb, + }) + } + if err != nil && !tg.IsNotModified(err) { + if !tg.IsMessageGone(err) { + b.log.Warn("edit failed", "chat_id", chat, "message_id", messageID, "err", err) + } + return err + } + return nil +} + +// answer acknowledges a button press, optionally with a short notice. +func (b *Bot) answer(ctx context.Context, q *telego.CallbackQuery, text string, alert bool) { + err := b.api.AnswerCallbackQuery(ctx, &telego.AnswerCallbackQueryParams{ + CallbackQueryID: q.ID, Text: clip(text, 200), ShowAlert: alert, + }) + if err != nil { + b.log.Debug("answerCallbackQuery failed", "err", err) + } +} + +func (b *Bot) deleteMessage(ctx context.Context, chat, messageID int64) { + if messageID == 0 { + return + } + if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ChatID: chatID(chat), MessageID: int(messageID)}); err != nil { + b.log.Debug("deleteMessage failed", "chat_id", chat, "err", err) + } +} + +func (b *Bot) chatAction(ctx context.Context, chat int64, action string) { + _ = b.api.SendChatAction(ctx, &telego.SendChatActionParams{ChatID: chatID(chat), Action: action}) +} diff --git a/internal/bot/card.go b/internal/bot/card.go new file mode 100644 index 0000000..ae8bfa0 --- /dev/null +++ b/internal/bot/card.go @@ -0,0 +1,250 @@ +package bot + +import ( + "context" + "errors" + "html" + "strings" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/ids" + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +func secondsDuration(s int64) time.Duration { return time.Duration(s) * time.Second } + +// linkRequest is one link a user asked about. +type linkRequest struct { + chatID int64 + chatType string + // sourceID is the message that holds the link. The card and the file + // are sent as replies to it. + sourceID int64 + act actor + url string + // preset skips the card and starts this profile right away. + preset media.Profile +} + +// startLink runs the link flow in the background so a slow metadata lookup +// never blocks other updates of the chat. +func (b *Bot) startLink(ctx context.Context, lr linkRequest) { + b.goBG("link", func() { b.linkFlow(ctx, lr) }) +} + +func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { + lang := lr.act.lang + log := b.log.With("user_id", lr.act.user.ID, "chat_id", lr.chatID, "url", links.Redact(lr.url)) + + placeholder, err := b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lang, "card.looking", nil), nil) + if err != nil { + return + } + phID := int64(placeholder.MessageID) + + info, err := b.svc.Probe(ctx, lr.url) + if err != nil { + if ctx.Err() == nil { + _ = b.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil) + } + return + } + + req := &db.Request{ + ID: ids.New(), + UserID: lr.act.user.ID, + ChatID: lr.chatID, + ChatType: lr.chatType, + SourceMessageID: lr.sourceID, + CardMessageID: phID, + URL: lr.url, + Status: db.RequestReady, + Info: info.JSON(), + Lang: lang, + } + if lr.preset != "" { + req.Status = db.RequestChosen + } + if err := b.store.InsertRequest(ctx, req); err != nil { + log.Error("insert request", "err", err) + _ = b.edit(ctx, lr.chatID, phID, false, b.tr.HTML(lang, "error.internal", nil), nil) + return + } + log = log.With("request_id", req.ID) + + if lr.preset != "" { + job, _, err := b.svc.Start(ctx, service.StartParams{ + Request: req, Info: info, Profile: lr.preset, + StatusMessageID: phID, ReplyToMessageID: lr.sourceID, + }) + if err != nil { + _ = b.edit(ctx, lr.chatID, phID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) + return + } + b.refreshStatus(ctx, job.ID) + return + } + + text := b.cardText(lang, info, true) + kb := b.cardKeyboard(lang, req.ID, info) + if info.Thumbnail != "" { + msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ + ChatID: chatID(lr.chatID), + Photo: telego.InputFile{URL: info.Thumbnail}, + Caption: clip(text, 1024), + ParseMode: telego.ModeHTML, + ReplyParameters: replyParams(lr.sourceID), + ReplyMarkup: kb, + }) + if err == nil { + if err := b.store.SetRequestCard(ctx, req.ID, int64(msg.MessageID), true); err != nil { + log.Error("save card", "err", err) + } + b.deleteMessage(ctx, lr.chatID, phID) + return + } + // Telegram could not fetch the thumbnail. The text card still works. + log.Debug("photo card failed, using text card", "err", err) + } + _ = b.edit(ctx, lr.chatID, phID, false, text, kb) +} + +// cardText renders the card: title, a line of facts and, for cards with +// buttons, the prompt to pick a format. +func (b *Bot) cardText(lang string, info *service.CardInfo, withPrompt bool) string { + var facts []string + if info.Uploader != "" { + facts = append(facts, html.EscapeString(shorten(info.Uploader, 40))) + } + if info.Duration > 0 { + facts = append(facts, i18n.Clock(info.Duration)) + } + if info.Site != "" { + facts = append(facts, html.EscapeString(info.Site)) + } + var sb strings.Builder + sb.WriteString(titleLine(info.Title)) + if len(facts) > 0 { + sb.WriteString("\n") + sb.WriteString(strings.Join(facts, " · ")) + } + if withPrompt { + sb.WriteString("\n\n") + sb.WriteString(b.tr.HTML(lang, "card.pick", nil)) + } + return sb.String() +} + +// probeErrorText maps a lookup failure to a friendly message. Raw yt-dlp +// output never reaches the user. +func (b *Bot) probeErrorText(lang string, err error) string { + if errors.Is(err, service.ErrPlaylist) { + return b.tr.HTML(lang, "error.playlist", nil) + } + return b.tr.HTML(lang, "error."+string(ytdlp.CodeOf(err)), nil) +} + +// startErrorText maps a refused or failed start to plain text. +func (b *Bot) startErrorText(lang string, err error) string { + var le *service.LimitError + if errors.As(err, &le) { + return b.limitText(lang, le) + } + b.log.Error("start download", "err", err) + return b.tr.T(lang, "error.internal", nil) +} + +// cbDownload handles a format button on a card. +func (b *Bot) cbDownload(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) { + req, err := b.store.GetRequest(ctx, requestID) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if req.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) + return + } + profile, perr := media.Parse(profileArg) + info, ierr := service.ParseCardInfo(req.Info) + if perr != nil || ierr != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + // Taking the request first makes a double tap start only one job. + took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen) + if err != nil { + b.log.Error("take request", "request_id", req.ID, "err", err) + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + return + } + if !took { + b.answer(ctx, q, b.tr.T(act.lang, "notice.already_chosen", nil), false) + return + } + cardID, cardIsPhoto := cardMessage(q, req) + job, _, err := b.svc.Start(ctx, service.StartParams{ + Request: req, Info: info, Profile: profile, + StatusMessageID: cardID, StatusIsPhoto: cardIsPhoto, + ReplyToMessageID: req.SourceMessageID, + }) + if err != nil { + // Give the card back so another format can be picked. + if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { + b.log.Error("release request", "request_id", req.ID, "err", rerr) + } + b.answer(ctx, q, b.startErrorText(act.lang, err), true) + return + } + b.answer(ctx, q, "", false) + b.refreshStatus(ctx, job.ID) +} + +// cbCancelCard handles the Cancel button on a card that has no job yet. +func (b *Bot) cbCancelCard(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) { + req, err := b.store.GetRequest(ctx, requestID) + if err != nil { + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + return + } + if req.UserID != act.user.ID { + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) + return + } + took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestCancelled) + if err != nil || !took { + b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false) + return + } + b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false) + cardID, cardIsPhoto := cardMessage(q, req) + if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ + ChatID: chatID(req.ChatID), MessageID: int(cardID), + }); err != nil { + _ = b.edit(ctx, req.ChatID, cardID, cardIsPhoto, b.tr.HTML(req.Lang, "card.cancelled", nil), nil) + } +} + +// cardMessage identifies the message a card button was pressed on. The +// callback itself is the source of truth: a press can arrive before the +// card's message ID has been saved with the request. +func cardMessage(q *telego.CallbackQuery, req *db.Request) (id int64, isPhoto bool) { + if q.Message == nil || q.Message.GetMessageID() == 0 { + return req.CardMessageID, req.CardIsPhoto + } + id = int64(q.Message.GetMessageID()) + if m := q.Message.Message(); m != nil && q.Message.IsAccessible() { + return id, len(m.Photo) > 0 + } + if id == req.CardMessageID { + return id, req.CardIsPhoto + } + return id, false +} diff --git a/internal/bot/commands.go b/internal/bot/commands.go new file mode 100644 index 0000000..31b620a --- /dev/null +++ b/internal/bot/commands.go @@ -0,0 +1,293 @@ +package bot + +import ( + "context" + "errors" + "strings" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/links" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/service" +) + +// maxLinksPerMessage caps how many links of one message get a card. +const maxLinksPerMessage = 3 + +func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { + if m.From == nil || m.From.IsBot { + return + } + act, err := b.actorFor(ctx, m.From) + if err != nil { + b.log.Error("load user", "user_id", m.From.ID, "err", err) + return + } + if act.user.Banned { + return + } + private := isPrivate(m.Chat.Type) + cmd, forUs, isCmd := b.parseCommand(m) + if isCmd { + if !forUs { + return // addressed to another bot in the group + } + switch cmd { + case "start": + b.cmdStart(ctx, m, act) + case "help": + b.cmdHelp(ctx, m, act) + case "dl": + b.cmdDownload(ctx, m, act, "") + case "audio": + b.cmdDownload(ctx, m, act, media.MP3) + case "thumb": + b.cmdDownload(ctx, m, act, media.Thumb) + case "info": + b.cmdInfo(ctx, m, act) + case "queue": + b.cmdQueue(ctx, m, act) + case "cancel": + b.cmdCancel(ctx, m, act) + default: + if private { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil) + } + } + return + } + if !private { + return // groups are driven by commands; auto-detect is an admin opt-in + } + urls := messageLinks(m) + if len(urls) == 0 { + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil) + return + } + if len(urls) > maxLinksPerMessage { + urls = urls[:maxLinksPerMessage] + } + for _, u := range urls { + b.startLink(ctx, linkRequest{ + chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: u, + }) + } +} + +// parseCommand finds a bot command at the start of the message. forUs is +// false when the command names a different bot (/dl@otherbot). +func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) { + for _, e := range m.Entities { + if e.Type != telego.EntityTypeBotCommand || e.Offset != 0 { + continue + } + // Commands are ASCII, so the UTF-16 length is also the byte length. + if e.Length > len(m.Text) || e.Length < 2 { + return "", false, false + } + full := m.Text[1:e.Length] + name, target, hasTarget := strings.Cut(full, "@") + if hasTarget && !strings.EqualFold(target, b.username) { + return "", false, true + } + return strings.ToLower(name), true, true + } + return "", false, false +} + +func toLinkEntities(ents []telego.MessageEntity) []links.Entity { + out := make([]links.Entity, 0, len(ents)) + for _, e := range ents { + out = append(out, links.Entity{Type: e.Type, Offset: e.Offset, Length: e.Length, URL: e.URL}) + } + return out +} + +// messageLinks extracts links from the text or the caption of a message. +func messageLinks(m *telego.Message) []string { + if m == nil { + return nil + } + if urls := links.Extract(m.Text, toLinkEntities(m.Entities)); len(urls) > 0 { + return urls + } + return links.Extract(m.Caption, toLinkEntities(m.CaptionEntities)) +} + +func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { + key := "start.private" + if !isPrivate(m.Chat.Type) { + key = "start.group" + } + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, key, i18n.Args{"Name": act.user.FirstName}), nil) +} + +func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) { + lim := b.svc.LimitsFor(ctx, act.user.ID) + _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{ + "MaxSize": b.tr.Size(act.lang, lim.MaxSize), + "MaxDuration": b.tr.Span(act.lang, secondsDuration(lim.MaxDuration)), + }), nil) +} + +// cmdDownload handles /dl, /audio and /thumb. The link comes from the +// command itself or from the message the command replies to. The bot +// answers under the message that holds the link. +func (b *Bot) cmdDownload(ctx context.Context, m *telego.Message, act actor, preset media.Profile) { + urls := messageLinks(m) + source := int64(m.MessageID) + if len(urls) == 0 && m.ReplyToMessage != nil { + urls = messageLinks(m.ReplyToMessage) + source = int64(m.ReplyToMessage.MessageID) + } + if len(urls) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil) + return + } + b.startLink(ctx, linkRequest{ + chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: source, act: act, url: urls[0], preset: preset, + }) +} + +func (b *Bot) cmdInfo(ctx context.Context, m *telego.Message, act actor) { + urls := messageLinks(m) + if len(urls) == 0 && m.ReplyToMessage != nil { + urls = messageLinks(m.ReplyToMessage) + } + if len(urls) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "info.usage", nil), nil) + return + } + url := urls[0] + b.goBG("info", func() { + b.chatAction(ctx, m.Chat.ID, telego.ChatActionTyping) + info, err := b.svc.Probe(ctx, url) + if err != nil { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.probeErrorText(act.lang, err), nil) + return + } + var sb strings.Builder + sb.WriteString(b.cardText(act.lang, info, false)) + sb.WriteString("\n") + profiles := append([]media.Profile{}, media.VideoProfiles...) + if info.HasAudio { + profiles = append(profiles, media.MP3, media.M4A) + } + for _, p := range profiles { + if h := p.Height(); h > 0 && info.MaxHeight > 0 && info.MaxHeight < h { + continue + } + size := b.tr.T(act.lang, "info.size_unknown", nil) + if n := info.Sizes[string(p)]; n > 0 { + size = b.tr.Size(act.lang, n) + } + sb.WriteString("\n") + sb.WriteString(b.tr.HTML(act.lang, "info.line", i18n.Args{"Label": b.profileLabel(act.lang, p), "Size": size})) + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil) + }) +} + +func (b *Bot) cmdQueue(ctx context.Context, m *telego.Message, act actor) { + dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID) + if err != nil { + b.log.Error("list deliveries", "err", err) + return + } + if len(dels) == 0 { + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "queue.empty", nil), nil) + return + } + var sb strings.Builder + sb.WriteString(b.tr.HTML(act.lang, "queue.header", i18n.Args{"Count": len(dels)})) + for _, d := range dels { + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil { + continue + } + text, _, _ := b.renderStatus(ctx, d, job) + sb.WriteString("\n\n") + sb.WriteString(text) + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil) +} + +func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) { + dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID) + if err != nil { + b.log.Error("list deliveries", "err", err) + return + } + n := 0 + for _, d := range dels { + if b.cancelDelivery(ctx, d.ID, act.user.ID) == nil { + n++ + } + } + key := "cancel.done" + if n == 0 { + key = "cancel.nothing" + } + _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key, i18n.Args{"Count": n}), nil) +} + +// cancelDelivery withdraws one delivery and updates its status message. +func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int64) error { + d, err := b.sched.CancelDelivery(ctx, deliveryID, userID) + if err != nil { + return err + } + job, err := b.store.GetJob(ctx, d.JobID) + if err != nil { + return nil + } + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)) + return nil +} + +func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { + act, err := b.actorFor(ctx, &q.From) + if err != nil { + b.log.Error("load user", "user_id", q.From.ID, "err", err) + return + } + if act.user.Banned { + b.answer(ctx, q, "", false) + return + } + action, id, arg := parseCallback(q.Data) + switch action { + case cbDownload: + b.cbDownload(ctx, q, act, id, arg) + case cbCancelCard: + b.cbCancelCard(ctx, q, act, id) + case cbCancelJob: + err := b.cancelDelivery(ctx, id, act.user.ID) + switch { + case err == nil: + b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false) + case errors.Is(err, sched.ErrNotOwner): + b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) + case errors.Is(err, sched.ErrTooLate), errors.Is(err, db.ErrNotFound): + b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false) + default: + b.log.Error("cancel delivery", "delivery_id", id, "err", err) + b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) + } + default: + b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) + } +} + +// limitText renders a limit refusal for the user. +func (b *Bot) limitText(lang string, le *service.LimitError) string { + return b.tr.T(lang, "limit."+le.Code, i18n.Args{ + "MaxSize": b.tr.Size(lang, le.Limits.MaxSize), + "MaxDuration": b.tr.Span(lang, secondsDuration(le.Limits.MaxDuration)), + "Count": le.Limits.ActiveJobs, + }) +} diff --git a/internal/bot/deliver.go b/internal/bot/deliver.go new file mode 100644 index 0000000..7104f41 --- /dev/null +++ b/internal/bot/deliver.go @@ -0,0 +1,349 @@ +package bot + +import ( + "context" + "errors" + "io" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/storage" + "github.com/noderunners/dlbot/internal/tg" +) + +// maxSendAttempts is how often one delivery is tried before giving up. +const maxSendAttempts = 3 + +// uploadTimeout bounds one upload to Telegram. +const uploadTimeout = 30 * time.Minute + +// namedReader gives a storage stream the file name Telegram should show. +type namedReader struct { + io.Reader + name string +} + +func (n namedReader) Name() string { return n.name } + +// deliverJob sends the stored file of a job to every waiting requester. +// It is safe to call more than once: a job is delivered by one goroutine +// at a time and each delivery is taken with an atomic status change. +func (b *Bot) deliverJob(ctx context.Context, jobID string) { + b.statusMu.Lock() + if b.sending[jobID] { + b.statusMu.Unlock() + return + } + b.sending[jobID] = true + b.statusMu.Unlock() + defer func() { + b.statusMu.Lock() + delete(b.sending, jobID) + b.statusMu.Unlock() + }() + + select { + case b.uploads <- struct{}{}: + defer func() { <-b.uploads }() + case <-ctx.Done(): + return + } + + job, err := b.store.GetJob(ctx, jobID) + if err != nil || job.Status != db.JobDelivering { + return + } + dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending) + if err != nil { + b.log.Error("list deliveries", "job_id", jobID, "err", err) + return + } + // The first upload yields a file_id that later requesters reuse, so the + // file crosses the wire once. + var fileID string + for _, d := range dels { + if ctx.Err() != nil { + return + } + if id := b.deliverOne(ctx, job, d, fileID); id != "" { + fileID = id + } + } + b.finishIfServed(ctx, job) +} + +// deliverOne sends the file to one requester and returns the Telegram +// file_id on success. +func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) string { + log := b.log.With("job_id", job.ID, "delivery_id", d.ID, "chat_id", d.ChatID) + took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliverySending, "") + if err != nil || !took { + return "" + } + text, _, _ := b.renderStatus(ctx, d, job) + b.setStatus(ctx, d, text, nil, "uploading", true) + + sendCtx, cancel := context.WithTimeout(ctx, uploadTimeout) + defer cancel() + stopAction := b.keepChatAction(sendCtx, d.ChatID, uploadAction(job)) + fileID, messageID, err := b.sendFile(sendCtx, job, d, reuseFileID) + stopAction() + + if err != nil { + // Status changes must be saved even when we are shutting down. + saveCtx := context.WithoutCancel(ctx) + switch { + case ctx.Err() != nil: + // Shutdown interrupted the upload. Leave it for the next start. + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "") + case tg.IsBlocked(err): + log.Info("requester unreachable", "err", err) + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "blocked") + case tg.IsFileTooBig(err): + log.Warn("telegram refused file size", "size", job.FileSize, "err", err) + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "too_large") + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "too_large")) + case d.Attempts+1 < maxSendAttempts: + log.Warn("send failed, will retry", "attempt", d.Attempts+1, "err", err) + if wait := tg.RetryAfter(err); wait > 0 && wait <= time.Minute { + sleepCtx(ctx, wait) + } + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "send_failed") + default: + log.Error("send failed, giving up", "err", err) + _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, "send_failed") + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, "send_failed")) + } + return "" + } + if err := b.store.MarkDeliverySent(context.WithoutCancel(ctx), d.ID, fileID, messageID); err != nil { + log.Error("mark delivery sent", "err", err) + } + log.Info("file delivered", "size", job.FileSize, "profile", job.Profile) + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil)) + return fileID +} + +// streamable lists the containers Telegram plays inline as video. +func streamable(ext string) bool { + switch ext { + case "mp4", "m4v", "mov": + return true + } + return false +} + +func uploadAction(job *db.Job) string { + switch jobProfile(job).Kind() { + case media.KindVideo: + if streamable(job.FileExt) { + return telego.ChatActionUploadVideo + } + case media.KindAudio: + return telego.ChatActionUploadVoice + case media.KindThumb: + return telego.ChatActionUploadPhoto + } + return telego.ChatActionUploadDocument +} + +// keepChatAction shows the "sending a file" indicator until stop is +// called. Telegram clears it after five seconds, so it is repeated. +func (b *Bot) keepChatAction(ctx context.Context, chat int64, action string) (stop func()) { + done := make(chan struct{}) + go func() { + t := time.NewTicker(4500 * time.Millisecond) + defer t.Stop() + for { + b.chatAction(ctx, chat, action) + select { + case <-done: + return + case <-ctx.Done(): + return + case <-t.C: + } + } + }() + return func() { close(done) } +} + +// sendFile uploads the stored file, or resends by file_id when one is +// known. A video or photo that Telegram rejects is sent again as a plain +// document, which accepts any content. +func (b *Bot) sendFile(ctx context.Context, job *db.Job, d *db.Delivery, reuseFileID string) (fileID string, messageID int64, err error) { + kind := jobProfile(job).Kind() + mode := "document" + switch { + case kind == media.KindVideo && streamable(job.FileExt): + mode = "video" + case kind == media.KindAudio: + mode = "audio" + case kind == media.KindThumb: + mode = "photo" + } + fileID, messageID, err = b.sendAs(ctx, mode, job, d, reuseFileID) + if err != nil && mode != "document" && reuseFileID == "" && tg.ErrorCode(err) == 400 && !tg.IsBlocked(err) { + b.log.Info("media rejected, sending as document", "job_id", job.ID, "mode", mode, "err", err) + return b.sendAs(ctx, "document", job, d, "") + } + return fileID, messageID, err +} + +func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (string, int64, error) { + var input telego.InputFile + if reuseFileID != "" { + input = telego.InputFile{FileID: reuseFileID} + } else { + if job.StorageKey == "" { + return "", 0, errors.New("bot: job has no stored file") + } + rc, _, err := b.storage.Open(ctx, job.StorageKey) + if err != nil { + if errors.Is(err, storage.ErrNotFound) { + return "", 0, errors.New("bot: stored file is missing") + } + return "", 0, err + } + defer rc.Close() + input = telego.InputFile{File: namedReader{Reader: rc, name: fileName(job.Title, job.FileExt)}} + } + caption := clip(titleLine(job.Title), 1024) + chat := chatID(d.ChatID) + reply := replyParams(d.ReplyToMessageID) + + switch mode { + case "video": + msg, err := b.api.SendVideo(ctx, &telego.SendVideoParams{ + ChatID: chat, Video: input, Caption: caption, ParseMode: telego.ModeHTML, + Duration: int(job.Duration), Width: job.Width, Height: job.Height, + SupportsStreaming: true, ReplyParameters: reply, + }) + if err != nil { + return "", 0, err + } + if msg.Video != nil { + return msg.Video.FileID, int64(msg.MessageID), nil + } + if msg.Document != nil { // Telegram may store odd videos as documents + return msg.Document.FileID, int64(msg.MessageID), nil + } + return "", int64(msg.MessageID), nil + case "audio": + msg, err := b.api.SendAudio(ctx, &telego.SendAudioParams{ + ChatID: chat, Audio: input, Title: shorten(job.Title, 120), Performer: shorten(job.Uploader, 60), + Duration: int(job.Duration), ReplyParameters: reply, + }) + if err != nil { + return "", 0, err + } + if msg.Audio != nil { + return msg.Audio.FileID, int64(msg.MessageID), nil + } + return "", int64(msg.MessageID), nil + case "photo": + msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ + ChatID: chat, Photo: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, + }) + if err != nil { + return "", 0, err + } + if n := len(msg.Photo); n > 0 { + return msg.Photo[n-1].FileID, int64(msg.MessageID), nil + } + return "", int64(msg.MessageID), nil + default: + msg, err := b.api.SendDocument(ctx, &telego.SendDocumentParams{ + ChatID: chat, Document: input, Caption: caption, ParseMode: telego.ModeHTML, ReplyParameters: reply, + }) + if err != nil { + return "", 0, err + } + if msg.Document != nil { + return msg.Document.FileID, int64(msg.MessageID), nil + } + return "", int64(msg.MessageID), nil + } +} + +// finishIfServed closes a delivering job once nobody waits for it, and +// removes the stored file. Until the cache exists a file has no use after +// it reached Telegram. +func (b *Bot) finishIfServed(ctx context.Context, job *db.Job) { + ctx = context.WithoutCancel(ctx) + left, err := b.store.CountDeliveriesInStatus(ctx, job.ID, db.DeliveryPending, db.DeliverySending) + if err != nil || left > 0 { + return + } + if err := b.sched.FinishDelivered(ctx, job.ID); err != nil { + b.log.Error("finish job", "job_id", job.ID, "err", err) + return + } + b.removeStored(ctx, job) +} + +func (b *Bot) removeStored(ctx context.Context, job *db.Job) { + if job.StorageKey == "" { + return + } + if err := b.storage.Delete(ctx, job.StorageKey); err != nil { + b.log.Warn("delete stored file", "job_id", job.ID, "key", job.StorageKey, "err", err) + } +} + +// failJob tells every waiting requester that the job failed. +func (b *Bot) failJob(ctx context.Context, jobID string) { + job, err := b.store.GetJob(ctx, jobID) + if err != nil || job.Status != db.JobFailed { + return + } + dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending) + if err != nil { + b.log.Error("list deliveries", "job_id", jobID, "err", err) + return + } + for _, d := range dels { + took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliveryFailed, job.ErrorCode) + if err != nil || !took { + continue + } + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)) + } + b.removeStored(ctx, job) +} + +// cleanupCancelled closes the deliveries of a cancelled job and removes +// any file the worker had already stored. +func (b *Bot) cleanupCancelled(ctx context.Context, jobID string) { + job, err := b.store.GetJob(ctx, jobID) + if err != nil || job.Status != db.JobCancelled { + return + } + dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending) + if err == nil { + for _, d := range dels { + took, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliveryPending, db.DeliveryCancelled, "") + if err != nil || !took { + continue + } + b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)) + } + } + // The worker may have uploaded before it noticed the cancel. + if err := b.storage.Delete(ctx, sched.UploadKey(job.ID)); err != nil { + b.log.Debug("delete cancelled upload", "job_id", job.ID, "err", err) + } +} + +func sleepCtx(ctx context.Context, d time.Duration) { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + case <-t.C: + } +} diff --git a/internal/bot/keyboards.go b/internal/bot/keyboards.go new file mode 100644 index 0000000..727342a --- /dev/null +++ b/internal/bot/keyboards.go @@ -0,0 +1,90 @@ +package bot + +import ( + "strings" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" + "github.com/noderunners/dlbot/internal/service" +) + +// Callback data is ":[:]". It carries identifiers only, +// never translated text, so buttons keep working when the language changes. +const ( + cbDownload = "dl" // dl:: + cbCancelCard = "cx" // cx: + cbCancelJob = "jc" // jc: +) + +func cbData(parts ...string) string { return strings.Join(parts, ":") } + +// parseCallback splits callback data into the action, the ID and the rest. +func parseCallback(data string) (action, id, arg string) { + parts := strings.SplitN(data, ":", 3) + action = parts[0] + if len(parts) > 1 { + id = parts[1] + } + if len(parts) > 2 { + arg = parts[2] + } + return +} + +func button(text, data string) telego.InlineKeyboardButton { + return telego.InlineKeyboardButton{Text: text, CallbackData: data} +} + +func keyboard(rows ...[]telego.InlineKeyboardButton) *telego.InlineKeyboardMarkup { + var kept [][]telego.InlineKeyboardButton + for _, r := range rows { + if len(r) > 0 { + kept = append(kept, r) + } + } + return &telego.InlineKeyboardMarkup{InlineKeyboard: kept} +} + +// cardProfiles picks the video buttons worth showing: Best always, then the +// lower resolutions the source can actually be scaled down to. +func cardProfiles(info *service.CardInfo) []media.Profile { + out := []media.Profile{media.Best} + for _, p := range []media.Profile{media.P720, media.P480} { + if info.MaxHeight == 0 || info.MaxHeight > p.Height() { + out = append(out, p) + } + } + return out +} + +// cardKeyboard builds the format buttons of a link card. +func (b *Bot) cardKeyboard(lang, requestID string, info *service.CardInfo) *telego.InlineKeyboardMarkup { + label := func(p media.Profile) string { + name := b.profileLabel(lang, p) + if size := info.Sizes[string(p)]; size > 0 { + return b.tr.T(lang, "btn.with_size", i18n.Args{"Label": name, "Size": b.tr.Size(lang, size)}) + } + return name + } + var video, extra []telego.InlineKeyboardButton + for _, p := range cardProfiles(info) { + video = append(video, button(label(p), cbData(cbDownload, requestID, string(p)))) + } + if info.HasAudio { + extra = append(extra, button(label(media.MP3), cbData(cbDownload, requestID, string(media.MP3)))) + } + if info.Thumbnail != "" { + extra = append(extra, button(b.profileLabel(lang, media.Thumb), cbData(cbDownload, requestID, string(media.Thumb)))) + } + cancel := []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, requestID))} + return keyboard(video, extra, cancel) +} + +// cancelJobKeyboard is the single Cancel button under a live status. +func (b *Bot) cancelJobKeyboard(lang, deliveryID string) *telego.InlineKeyboardMarkup { + return keyboard([]telego.InlineKeyboardButton{ + button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelJob, deliveryID)), + }) +} diff --git a/internal/bot/menu.go b/internal/bot/menu.go new file mode 100644 index 0000000..dd675ec --- /dev/null +++ b/internal/bot/menu.go @@ -0,0 +1,32 @@ +package bot + +import ( + "context" + + "github.com/mymmrac/telego" +) + +// menuCommands are the commands shown in Telegram's command menu, in +// order. Names are lowercase ASCII in every language; only descriptions +// are translated, under "menu.". +var menuCommands = []string{"dl", "audio", "thumb", "info", "queue", "cancel", "help"} + +// RegisterCommands publishes the command menu. A failure is logged and +// otherwise ignored: the bot works without a menu. +func (b *Bot) RegisterCommands(ctx context.Context) { + for _, lang := range b.tr.Langs() { + cmds := make([]telego.BotCommand, 0, len(menuCommands)) + for _, name := range menuCommands { + cmds = append(cmds, telego.BotCommand{Command: name, Description: b.tr.T(lang, "menu."+name, nil)}) + } + params := &telego.SetMyCommandsParams{Commands: cmds} + if lang != b.tr.Langs()[0] { + // The source language is the default menu; the others are + // registered for their own language code. + params.LanguageCode = lang + } + if err := b.api.SetMyCommands(ctx, params); err != nil { + b.log.Warn("setMyCommands failed", "lang", lang, "err", err) + } + } +} diff --git a/internal/bot/status.go b/internal/bot/status.go new file mode 100644 index 0000000..2653adf --- /dev/null +++ b/internal/bot/status.go @@ -0,0 +1,226 @@ +package bot + +import ( + "context" + "time" + + "github.com/mymmrac/telego" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/sched" + "github.com/noderunners/dlbot/internal/tg" + "github.com/noderunners/dlbot/internal/ytdlp" +) + +// statusState remembers what a status message shows, so edits that would +// change nothing or come too fast are skipped. +type statusState struct { + text string + phase string + at time.Time +} + +// eventLoop reacts to job events and periodically reconciles, which covers +// dropped events and work left over from before a restart. +func (b *Bot) eventLoop(ctx context.Context) { + b.safely("reconcile", func() { b.reconcile(ctx) }) + t := time.NewTicker(b.reconcileEvery) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case ev := <-b.events: + b.safely("event", func() { b.handleEvent(ctx, ev) }) + case <-t.C: + b.safely("reconcile", func() { b.reconcile(ctx) }) + } + } +} + +func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) { + switch ev.Type { + case sched.EventStarted, sched.EventProgress, sched.EventRequeued: + b.refreshStatus(ctx, ev.JobID) + case sched.EventStored: + b.goBG("deliver", func() { b.deliverJob(ctx, ev.JobID) }) + case sched.EventFailed: + b.failJob(ctx, ev.JobID) + case sched.EventCancelled: + b.cleanupCancelled(ctx, ev.JobID) + } +} + +// reconcile brings Telegram in line with the database: it resumes +// deliveries, reports failures, frees stuck uploads and refreshes the +// position shown on queued jobs. +func (b *Bot) reconcile(ctx context.Context) { + if ctx.Err() != nil { + return + } + stale, err := b.store.StaleSendingDeliveries(ctx, db.NowMilli()-staleSending.Milliseconds()) + if err != nil { + b.log.Error("reconcile: stale deliveries", "err", err) + } + for _, d := range stale { + if _, err := b.store.TransitionDelivery(ctx, d.ID, db.DeliverySending, db.DeliveryPending, ""); err != nil { + b.log.Error("reconcile: reset delivery", "delivery_id", d.ID, "err", err) + } + } + each := func(status string, fn func(jobID string)) { + jobIDs, err := b.store.PendingDeliveryJobIDs(ctx, status, 200) + if err != nil { + b.log.Error("reconcile: list jobs", "status", status, "err", err) + return + } + for _, id := range jobIDs { + fn(id) + } + } + each(db.JobDelivering, func(id string) { b.goBG("deliver", func() { b.deliverJob(ctx, id) }) }) + each(db.JobFailed, func(id string) { b.failJob(ctx, id) }) + each(db.JobCancelled, func(id string) { b.cleanupCancelled(ctx, id) }) + each(db.JobQueued, func(id string) { b.refreshStatus(ctx, id) }) + each(db.JobRunning, func(id string) { b.refreshStatus(ctx, id) }) + + // Jobs whose requesters were all served but that were never closed. + delivering, err := b.store.JobsByStatus(ctx, db.JobDelivering, 200) + if err != nil { + b.log.Error("reconcile: delivering jobs", "err", err) + return + } + for _, j := range delivering { + b.finishIfServed(ctx, j) + } +} + +// staleSending is how long a delivery may sit in "sending" before it is +// assumed to be left over from a crash. +const staleSending = 20 * time.Minute + +// refreshStatus updates the status message of every waiting requester of +// a job. +func (b *Bot) refreshStatus(ctx context.Context, jobID string) { + job, err := b.store.GetJob(ctx, jobID) + if err != nil { + return + } + if job.Status != db.JobQueued && job.Status != db.JobRunning { + return + } + dels, err := b.store.DeliveriesForJob(ctx, jobID, db.DeliveryPending) + if err != nil { + b.log.Error("list deliveries", "job_id", jobID, "err", err) + return + } + for _, d := range dels { + text, kb, phase := b.renderStatus(ctx, d, job) + b.setStatus(ctx, d, text, kb, phase, false) + } +} + +// renderStatus builds the live status text of a delivery. phase groups +// states that only differ in numbers, which is what throttling keys on. +func (b *Bot) renderStatus(ctx context.Context, d *db.Delivery, job *db.Job) (text string, kb *telego.InlineKeyboardMarkup, phase string) { + lang := d.Lang + head := titleLine(job.Title) + "\n" + cancel := b.cancelJobKeyboard(lang, d.ID) + switch job.Status { + case db.JobQueued: + pos, err := b.sched.Position(ctx, job, b.slots()) + if err != nil { + b.log.Error("queue position", "job_id", job.ID, "err", err) + } + return head + b.tr.HTML(lang, "status.queued", i18n.Args{ + "Position": pos.Ahead + 1, + "Wait": b.tr.Span(lang, pos.Wait), + }), cancel, "queued" + case db.JobRunning: + switch job.Stage { + case ytdlp.StageProcessing: + return head + b.tr.HTML(lang, "status.processing", nil), cancel, "processing" + case ytdlp.StageUploading: + return head + b.tr.HTML(lang, "status.uploading", nil), cancel, "uploading" + } + switch { + case job.TotalBytes > 0: + ratio := float64(job.ProgressBytes) / float64(job.TotalBytes) + return head + b.tr.HTML(lang, "status.downloading_progress", i18n.Args{ + "Bar": bar(ratio), + "Percent": b.tr.Percent(lang, ratio), + "Done": b.tr.Size(lang, job.ProgressBytes), + "Total": b.tr.Size(lang, job.TotalBytes), + }), cancel, "downloading" + case job.ProgressBytes > 0: + return head + b.tr.HTML(lang, "status.downloading_bytes", i18n.Args{ + "Done": b.tr.Size(lang, job.ProgressBytes), + }), cancel, "downloading" + } + return head + b.tr.HTML(lang, "status.downloading", nil), cancel, "downloading" + case db.JobDelivering: + return head + b.tr.HTML(lang, "status.uploading", nil), nil, "uploading" + case db.JobDone: + return head + b.tr.HTML(lang, "status.done", nil), nil, "done" + case db.JobCancelled: + return head + b.tr.HTML(lang, "status.cancelled", nil), nil, "cancelled" + default: + return head + b.failureText(lang, job.ErrorCode), nil, "failed" + } +} + +// failureText is the user-facing explanation of a failed job. +func (b *Bot) failureText(lang, code string) string { + if code == "" { + code = string(ytdlp.CodeUnknown) + } + return b.tr.HTML(lang, "status.failed", i18n.Args{"Reason": b.tr.T(lang, "error."+code, nil)}) +} + +// setStatus edits the status message unless nothing changed or the last +// edit of the same phase was too recent. Telegram limits how often a +// message may be edited, and progress numbers are not worth a flood wait. +func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup, phase string, force bool) { + if d.StatusMessageID == 0 { + return + } + now := time.Now() + b.statusMu.Lock() + st := b.statuses[d.ID] + if st != nil { + if st.text == text || (!force && st.phase == phase && now.Sub(st.at) < b.statusMinGap) { + b.statusMu.Unlock() + return + } + } + b.statuses[d.ID] = &statusState{text: text, phase: phase, at: now} + b.statusMu.Unlock() + + if err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb); err != nil { + if wait := tg.RetryAfter(err); wait > 0 { + // Back off this message for as long as Telegram asked. + b.statusMu.Lock() + if cur := b.statuses[d.ID]; cur != nil { + cur.text = "" + cur.at = now.Add(wait) + } + b.statusMu.Unlock() + } + } +} + +// finalStatus writes the last state of a delivery and forgets its +// throttling state. When the status message is gone a new one is sent, so +// the requester always learns the outcome. +func (b *Bot) finalStatus(ctx context.Context, d *db.Delivery, text string) { + b.statusMu.Lock() + delete(b.statuses, d.ID) + b.statusMu.Unlock() + if d.StatusMessageID != 0 { + err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, nil) + if err == nil || !tg.IsMessageGone(err) { + return + } + } + _, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, nil) +} diff --git a/internal/bot/text.go b/internal/bot/text.go new file mode 100644 index 0000000..507d594 --- /dev/null +++ b/internal/bot/text.go @@ -0,0 +1,107 @@ +package bot + +import ( + "html" + "strings" + "unicode" + "unicode/utf8" + + "github.com/noderunners/dlbot/internal/db" + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/media" +) + +// clip shortens s to at most max bytes without cutting a rune, and without +// leaving an HTML entity or tag half open at the end. +func clip(s string, max int) string { + if len(s) <= max { + return s + } + cut := max - 1 + for cut > 0 && !utf8.RuneStart(s[cut]) { + cut-- + } + out := s[:cut] + if i := strings.LastIndexAny(out, "<&"); i >= 0 && !strings.ContainsAny(out[i:], ">;") { + out = out[:i] + } + return out + "…" +} + +// shorten cuts plain text to a number of runes, adding an ellipsis. +func shorten(s string, runes int) string { + s = strings.TrimSpace(s) + if utf8.RuneCountInString(s) <= runes { + return s + } + r := []rune(s) + return strings.TrimSpace(string(r[:runes-1])) + "…" +} + +// titleLine is the bold, escaped title used at the top of cards and +// status messages. +func titleLine(title string) string { + return "" + html.EscapeString(shorten(title, 120)) + "" +} + +// fileName builds the name a delivered file gets in Telegram. +func fileName(title, ext string) string { + var sb strings.Builder + for _, r := range title { + switch { + case r == '/' || r == '\\' || r == ':' || r == '*' || r == '?' || r == '"' || r == '<' || r == '>' || r == '|': + sb.WriteRune(' ') + case unicode.IsControl(r): + default: + sb.WriteRune(r) + } + } + name := strings.Join(strings.Fields(sb.String()), " ") + name = strings.Trim(shorten(name, 80), ". ") + if name == "" { + name = "media" + } + if ext == "" { + return name + } + return name + "." + ext +} + +// bar renders a ten segment progress bar. It has no words, so it needs no +// translation. +func bar(ratio float64) string { + if ratio < 0 { + ratio = 0 + } + if ratio > 1 { + ratio = 1 + } + filled := int(ratio*10 + 0.5) + return strings.Repeat("▰", filled) + strings.Repeat("▱", 10-filled) +} + +// profileLabel is the human name of a profile, as used on buttons. +func (b *Bot) profileLabel(lang string, p media.Profile) string { + switch { + case p == media.Best: + return b.tr.T(lang, "btn.best", nil) + case p == media.MP3: + return b.tr.T(lang, "btn.mp3", nil) + case p == media.M4A: + return b.tr.T(lang, "btn.m4a", nil) + case p == media.Thumb: + return b.tr.T(lang, "btn.thumb", nil) + case p.Kind() == media.KindSubs: + return b.tr.T(lang, "btn.subs", i18n.Args{"Lang": p.SubLang()}) + default: + return b.tr.T(lang, "btn.res", i18n.Args{"Height": p.Height()}) + } +} + +func jobProfile(j *db.Job) media.Profile { + p, err := media.Parse(j.Profile) + if err != nil { + return media.Best + } + return p +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..913e8e1 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,407 @@ +// 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() +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..e09b18b --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,175 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +func lookup(env map[string]string) func(string) (string, bool) { + return func(k string) (string, bool) { + v, ok := env[k] + return v, ok + } +} + +func TestDefaultsAreValidOnceTokenIsSet(t *testing.T) { + cfg := Default() + if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "BOT_TOKEN") { + t.Fatalf("missing token must be reported, got %v", err) + } + cfg.Telegram.Token = "x" + if err := cfg.Validate(); err != nil { + t.Fatalf("defaults should validate: %v", err) + } + if cfg.Limits.Free.MaxSizeMB != 50 || cfg.Limits.Free.MaxDuration.D() != 10*time.Minute || + cfg.Limits.Free.ActiveJobs != 1 || cfg.Queue.FreeMaxLen != 20 { + t.Fatalf("free tier defaults changed: %+v %+v", cfg.Limits.Free, cfg.Queue) + } +} + +func TestApplyEnv(t *testing.T) { + cfg := Default() + env := map[string]string{ + "BOT_TOKEN": "123:abc", + "TELEGRAM_MODE": "webhook", + "WEBHOOK_URL": "https://bot.example.com", + "WORKER_EMBEDDED": "false", + "WORKER_CONCURRENCY": "5", + "DOWNLOAD_TIMEOUT": "45m", + "OWNER_IDS": "11, 22;33", + "DB_DRIVER": "postgres", + "LOG_LEVEL": "", + } + if err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(env)); err != nil { + t.Fatal(err) + } + if cfg.Telegram.Token != "123:abc" || cfg.Telegram.Mode != "webhook" || cfg.Worker.Embedded || + cfg.Worker.Concurrency != 5 || cfg.Worker.DownloadTimeout.D() != 45*time.Minute || + cfg.Database.Driver != "postgres" { + t.Fatalf("env not applied: %+v", cfg) + } + if !reflect.DeepEqual(cfg.Owners, []int64{11, 22, 33}) { + t.Fatalf("owners = %v", cfg.Owners) + } + if cfg.Log.Level != "info" { + t.Fatalf("an empty variable must not override the default, got %q", cfg.Log.Level) + } + if !cfg.IsOwner(22) || cfg.IsOwner(44) { + t.Fatal("IsOwner is wrong") + } + if err := applyTierEnv("FREE", &cfg.Limits.Free, lookup(map[string]string{ + "FREE_MAX_SIZE_MB": "25", "FREE_MAX_DURATION": "5m", "FREE_ACTIVE_JOBS": "2", + })); err != nil { + t.Fatal(err) + } + if cfg.Limits.Free.MaxSizeMB != 25 || cfg.Limits.Free.MaxDuration.D() != 5*time.Minute || cfg.Limits.Free.ActiveJobs != 2 { + t.Fatalf("tier env not applied: %+v", cfg.Limits.Free) + } +} + +func TestApplyEnvRejectsBadValues(t *testing.T) { + for k, v := range map[string]string{ + "WORKER_CONCURRENCY": "many", "WORKER_EMBEDDED": "maybe", "DOWNLOAD_TIMEOUT": "soon", "OWNER_IDS": "1,x", + } { + cfg := Default() + err := applyEnv(reflect.ValueOf(&cfg).Elem(), lookup(map[string]string{k: v})) + if err == nil || !strings.Contains(err.Error(), k) { + t.Errorf("%s=%s: error %v should name the variable", k, v, err) + } + } +} + +func TestValidate(t *testing.T) { + bad := []func(*Config){ + func(c *Config) { c.Telegram.Mode = "carrier-pigeon" }, + func(c *Config) { c.Telegram.Mode = "webhook" }, // no URL + func(c *Config) { c.Database.Driver = "oracle" }, + func(c *Config) { c.Storage.Backend = "tape" }, + func(c *Config) { c.Worker.Concurrency = 0 }, + func(c *Config) { c.Queue.MaxAttempts = 0 }, + func(c *Config) { c.Queue.Heartbeat = c.Queue.Lease }, + } + for i, mut := range bad { + cfg := Default() + cfg.Telegram.Token = "x" + mut(&cfg) + if err := cfg.Validate(); err == nil { + t.Errorf("case %d should not validate", i) + } + } +} + +func TestLoadFileThenEnv(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.toml") + content := ` +owners = [5, 6] + +[telegram] +token = "from-file" +max_upload_mb = 2000 + +[worker] +concurrency = 3 +download_timeout = "1h" + +[limits.free] +max_size_mb = 30 +max_duration = "7m" +active_jobs = 1 +` + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + t.Chdir(dir) // keeps a developer's real .env out of the test + t.Setenv("BOT_TOKEN", "from-env") + t.Setenv("DLBOT_CONFIG", "") + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.Telegram.Token != "from-env" { + t.Errorf("env must override the file, token = %q", cfg.Telegram.Token) + } + if cfg.Worker.Concurrency != 3 || cfg.Worker.DownloadTimeout.D() != time.Hour || + cfg.Limits.Free.MaxSizeMB != 30 || cfg.Limits.Free.MaxDuration.D() != 7*time.Minute { + t.Errorf("file values not loaded: %+v %+v", cfg.Worker, cfg.Limits.Free) + } + if cfg.MaxUploadBytes() != 2000<<20 || !reflect.DeepEqual(cfg.Owners, []int64{5, 6}) { + t.Errorf("upload cap or owners wrong: %d %v", cfg.MaxUploadBytes(), cfg.Owners) + } + if cfg.HTTP.Listen != ":8080" { + t.Errorf("unset values keep their defaults, listen = %q", cfg.HTTP.Listen) + } + if _, err := Load(filepath.Join(dir, "missing.toml")); err == nil { + t.Error("an explicit config path that does not exist must be an error") + } +} + +func TestDotEnvDoesNotOverrideRealEnv(t *testing.T) { + dir := t.TempDir() + env := "# comment\nexport DLBOT_TEST_A=from-dotenv\nDLBOT_TEST_B=\"quoted value\"\nnot a pair\n" + path := filepath.Join(dir, ".env") + if err := os.WriteFile(path, []byte(env), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("DLBOT_TEST_A", "from-real-env") + os.Unsetenv("DLBOT_TEST_B") + t.Cleanup(func() { os.Unsetenv("DLBOT_TEST_B") }) + if err := loadDotEnv(path); err != nil { + t.Fatal(err) + } + if got := os.Getenv("DLBOT_TEST_A"); got != "from-real-env" { + t.Errorf("A = %q", got) + } + if got := os.Getenv("DLBOT_TEST_B"); got != "quoted value" { + t.Errorf("B = %q", got) + } + if err := loadDotEnv(filepath.Join(dir, "absent")); err != nil { + t.Errorf("a missing .env is fine, got %v", err) + } +} diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..fd0586c --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,199 @@ +// Package db is the data layer. SQLite and Postgres share one schema and +// one set of queries; the few places where they differ go through Dialect. +package db + +import ( + "context" + "database/sql" + "embed" + "errors" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/pressly/goose/v3" + _ "modernc.org/sqlite" // registers the "sqlite" driver +) + +//go:embed migrations/*.sql +var migrationsFS embed.FS + +// Dialect names a SQL backend. +type Dialect string + +// The supported dialects. +const ( + SQLite Dialect = "sqlite" + Postgres Dialect = "postgres" +) + +// ErrNotFound is returned when a row does not exist. +var ErrNotFound = errors.New("db: not found") + +// DB is an open database. +type DB struct { + SQL *sql.DB + Dialect Dialect +} + +// Open connects to the database named by driver ("sqlite" or "postgres"). +// For sqlite the DSN is a file path. +func Open(ctx context.Context, driver, dsn string) (*DB, error) { + switch Dialect(driver) { + case SQLite: + return openSQLite(ctx, dsn) + case Postgres: + return openPostgres(ctx, dsn) + } + return nil, fmt.Errorf("db: unknown driver %q", driver) +} + +func openSQLite(ctx context.Context, path string) (*DB, error) { + if path == "" { + return nil, errors.New("db: sqlite needs a file path") + } + if dir := filepath.Dir(path); dir != "." { + if err := os.MkdirAll(dir, 0o750); err != nil { + return nil, err + } + } + q := url.Values{} + q.Add("_pragma", "busy_timeout(10000)") + q.Add("_pragma", "journal_mode(WAL)") + q.Add("_pragma", "synchronous(NORMAL)") + q.Add("_pragma", "foreign_keys(1)") + // Every transaction takes the write lock up front. This is what makes + // job claiming atomic on SQLite and avoids lock upgrade deadlocks. + q.Set("_txlock", "immediate") + sqldb, err := sql.Open("sqlite", "file:"+path+"?"+q.Encode()) + if err != nil { + return nil, err + } + sqldb.SetMaxOpenConns(4) + sqldb.SetMaxIdleConns(4) + if err := sqldb.PingContext(ctx); err != nil { + sqldb.Close() + return nil, fmt.Errorf("db: open sqlite %s: %w", path, err) + } + return &DB{SQL: sqldb, Dialect: SQLite}, nil +} + +// Close closes the pool. +func (d *DB) Close() error { return d.SQL.Close() } + +// Migrate applies all pending migrations. +func (d *DB) Migrate(ctx context.Context) error { + sub, err := fs.Sub(migrationsFS, "migrations") + if err != nil { + return err + } + dialect := goose.DialectSQLite3 + if d.Dialect == Postgres { + dialect = goose.DialectPostgres + } + p, err := goose.NewProvider(dialect, d.SQL, sub) + if err != nil { + return fmt.Errorf("db: migrations: %w", err) + } + if _, err := p.Up(ctx); err != nil { + return fmt.Errorf("db: migrate: %w", err) + } + return nil +} + +// querier is satisfied by *sql.DB and *sql.Tx. +type querier interface { + ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row +} + +// Store runs queries, either on the pool or inside a transaction. +type Store struct { + db *DB + q querier + inTx bool +} + +// Store returns a Store that runs each query on the pool. +func (d *DB) Store() *Store { return &Store{db: d, q: d.SQL} } + +// Dialect returns the dialect of the underlying database. +func (s *Store) Dialect() Dialect { return s.db.Dialect } + +// InTx runs fn in a transaction. Nested calls reuse the outer transaction. +// On SQLite the transaction holds the write lock from the start. +func (s *Store) InTx(ctx context.Context, fn func(tx *Store) error) error { + if s.inTx { + return fn(s) + } + tx, err := s.db.SQL.BeginTx(ctx, nil) + if err != nil { + return err + } + if err := fn(&Store{db: s.db, q: tx, inTx: true}); err != nil { + _ = tx.Rollback() + return err + } + return tx.Commit() +} + +// rebind turns "?" placeholders into "$1, $2, ..." for Postgres. +func (s *Store) rebind(query string) string { + if s.db.Dialect != Postgres { + return query + } + var b strings.Builder + b.Grow(len(query) + 8) + n := 0 + for i := 0; i < len(query); i++ { + if query[i] == '?' { + n++ + b.WriteByte('$') + b.WriteString(strconv.Itoa(n)) + continue + } + b.WriteByte(query[i]) + } + return b.String() +} + +func (s *Store) exec(ctx context.Context, query string, args ...any) (int64, error) { + res, err := s.q.ExecContext(ctx, s.rebind(query), args...) + if err != nil { + return 0, err + } + return res.RowsAffected() +} + +func (s *Store) row(ctx context.Context, query string, args ...any) *sql.Row { + return s.q.QueryRowContext(ctx, s.rebind(query), args...) +} + +func (s *Store) rows(ctx context.Context, query string, args ...any) (*sql.Rows, error) { + return s.q.QueryContext(ctx, s.rebind(query), args...) +} + +// NowMilli is the timestamp format used in every table. +func NowMilli() int64 { return time.Now().UnixMilli() } + +func notFound(err error) error { + if errors.Is(err, sql.ErrNoRows) { + return ErrNotFound + } + return err +} + +// in builds "?, ?, ?" and the matching argument list. +func in[T any](vals []T) (string, []any) { + args := make([]any, len(vals)) + for i, v := range vals { + args[i] = v + } + return strings.TrimSuffix(strings.Repeat("?, ", len(vals)), ", "), args +} diff --git a/internal/db/dbtest/dbtest.go b/internal/db/dbtest/dbtest.go new file mode 100644 index 0000000..6f14412 --- /dev/null +++ b/internal/db/dbtest/dbtest.go @@ -0,0 +1,25 @@ +// Package dbtest opens throwaway databases for tests. +package dbtest + +import ( + "context" + "path/filepath" + "testing" + + "github.com/noderunners/dlbot/internal/db" +) + +// Open returns a migrated database that is removed when the test ends. +func Open(t testing.TB) *db.DB { + t.Helper() + ctx := context.Background() + d, err := db.Open(ctx, "sqlite", filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("open db: %v", err) + } + t.Cleanup(func() { d.Close() }) + if err := d.Migrate(ctx); err != nil { + t.Fatalf("migrate: %v", err) + } + return d +} diff --git a/internal/db/deliveries.go b/internal/db/deliveries.go new file mode 100644 index 0000000..8175829 --- /dev/null +++ b/internal/db/deliveries.go @@ -0,0 +1,137 @@ +package db + +import ( + "context" + "database/sql" +) + +const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id, + status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id, + tg_message_id, created_at, updated_at` + +func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) { + var d Delivery + err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID, + &d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID, + &d.TgMessageID, &d.CreatedAt, &d.UpdatedAt) + if err != nil { + return nil, notFound(err) + } + return &d, nil +} + +func scanDeliveries(rows *sql.Rows, err error) ([]*Delivery, error) { + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Delivery + for rows.Next() { + d, err := scanDelivery(rows) + if err != nil { + return nil, err + } + out = append(out, d) + } + return out, rows.Err() +} + +// InsertDelivery stores a new delivery. +func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error { + if d.CreatedAt == 0 { + d.CreatedAt = NowMilli() + } + d.UpdatedAt = d.CreatedAt + _, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID, + d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID, + d.TgMessageID, d.CreatedAt, d.UpdatedAt) + return err +} + +// GetDelivery loads a delivery. +func (s *Store) GetDelivery(ctx context.Context, id string) (*Delivery, error) { + return scanDelivery(s.row(ctx, `SELECT `+deliveryCols+` FROM deliveries WHERE id = ?`, id)) +} + +// DeliveriesForJob lists the deliveries of a job in the given statuses. +func (s *Store) DeliveriesForJob(ctx context.Context, jobID string, statuses ...string) ([]*Delivery, error) { + ph, args := in(statuses) + return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries + WHERE job_id = ? AND status IN (`+ph+`) ORDER BY id`, append([]any{jobID}, args...)...)) +} + +// ActiveDeliveriesForUser lists a user's deliveries that are still waiting. +func (s *Store) ActiveDeliveriesForUser(ctx context.Context, userID int64) ([]*Delivery, error) { + return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries + WHERE user_id = ? AND status IN ('pending', 'sending') ORDER BY id`, userID)) +} + +// CountActiveDeliveries counts a user's waiting deliveries. +func (s *Store) CountActiveDeliveries(ctx context.Context, userID int64) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE user_id = ? AND status IN ('pending', 'sending')`, + userID).Scan(&n) + return n, err +} + +// CountDeliveriesInStatus counts the deliveries of a job in the statuses. +func (s *Store) CountDeliveriesInStatus(ctx context.Context, jobID string, statuses ...string) (int, error) { + ph, args := in(statuses) + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE job_id = ? AND status IN (`+ph+`)`, + append([]any{jobID}, args...)...).Scan(&n) + return n, err +} + +// TransitionDelivery moves a delivery between statuses and reports whether +// the row was in the expected status. +func (s *Store) TransitionDelivery(ctx context.Context, id, from, to, errorCode string) (bool, error) { + n, err := s.exec(ctx, `UPDATE deliveries SET status = ?, error_code = ?, updated_at = ?, + attempts = attempts + CASE WHEN ? = 'sending' THEN 1 ELSE 0 END + WHERE id = ? AND status = ?`, to, errorCode, NowMilli(), to, id, from) + return n == 1, err +} + +// MarkDeliverySent records the Telegram file and message of a delivery. +func (s *Store) MarkDeliverySent(ctx context.Context, id, fileID string, messageID int64) error { + _, err := s.exec(ctx, `UPDATE deliveries SET status = 'sent', tg_file_id = ?, tg_message_id = ?, + error_code = '', updated_at = ? WHERE id = ?`, fileID, messageID, NowMilli(), id) + return err +} + +// SetDeliveryStatusMessage records which message shows the live status. +func (s *Store) SetDeliveryStatusMessage(ctx context.Context, id string, messageID int64, isPhoto bool) error { + _, err := s.exec(ctx, `UPDATE deliveries SET status_message_id = ?, status_is_photo = ?, updated_at = ? + WHERE id = ?`, messageID, isPhoto, NowMilli(), id) + return err +} + +// StaleSendingDeliveries lists deliveries stuck in sending since before the +// cutoff, which happens when the core stops in the middle of an upload. +func (s *Store) StaleSendingDeliveries(ctx context.Context, before int64) ([]*Delivery, error) { + return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries + WHERE status = 'sending' AND updated_at < ? ORDER BY id`, before)) +} + +// PendingDeliveryJobIDs lists the jobs in a status that still have pending +// deliveries. The core uses it to resume work after a restart. +func (s *Store) PendingDeliveryJobIDs(ctx context.Context, jobStatus string, limit int) ([]string, error) { + rows, err := s.rows(ctx, `SELECT DISTINCT j.id FROM jobs j + JOIN deliveries d ON d.job_id = j.id + WHERE j.status = ? AND d.status = 'pending' ORDER BY j.id LIMIT ?`, jobStatus, limit) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + out = append(out, id) + } + return out, rows.Err() +} diff --git a/internal/db/jobs.go b/internal/db/jobs.go new file mode 100644 index 0000000..920cdb6 --- /dev/null +++ b/internal/db/jobs.go @@ -0,0 +1,215 @@ +package db + +import ( + "context" + "database/sql" + "errors" +) + +const jobCols = `id, kind, url, extractor, video_id, profile, cache_key, status, lane, priority, + required_tags, max_size, max_duration, attempts, max_attempts, worker_id, lease_expires_at, + cancel_requested, stage, progress_bytes, total_bytes, error_code, error_detail, storage_key, + file_ext, file_size, duration, width, height, title, uploader, created_at, queued_at, + started_at, finished_at` + +func scanJob(sc interface{ Scan(...any) error }) (*Job, error) { + var j Job + err := sc.Scan(&j.ID, &j.Kind, &j.URL, &j.Extractor, &j.VideoID, &j.Profile, &j.CacheKey, &j.Status, + &j.Lane, &j.Priority, &j.RequiredTags, &j.MaxSize, &j.MaxDuration, &j.Attempts, &j.MaxAttempts, + &j.WorkerID, &j.LeaseExpiresAt, &j.CancelRequested, &j.Stage, &j.ProgressBytes, &j.TotalBytes, + &j.ErrorCode, &j.ErrorDetail, &j.StorageKey, &j.FileExt, &j.FileSize, &j.Duration, &j.Width, + &j.Height, &j.Title, &j.Uploader, &j.CreatedAt, &j.QueuedAt, &j.StartedAt, &j.FinishedAt) + if err != nil { + return nil, notFound(err) + } + return &j, nil +} + +func scanJobs(rows *sql.Rows, err error) ([]*Job, error) { + if err != nil { + return nil, err + } + defer rows.Close() + var out []*Job + for rows.Next() { + j, err := scanJob(rows) + if err != nil { + return nil, err + } + out = append(out, j) + } + return out, rows.Err() +} + +// InsertJob stores a new job. +func (s *Store) InsertJob(ctx context.Context, j *Job) error { + _, err := s.exec(ctx, `INSERT INTO jobs (`+jobCols+`) VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + j.ID, j.Kind, j.URL, j.Extractor, j.VideoID, j.Profile, j.CacheKey, j.Status, j.Lane, j.Priority, + j.RequiredTags, j.MaxSize, j.MaxDuration, j.Attempts, j.MaxAttempts, j.WorkerID, j.LeaseExpiresAt, + j.CancelRequested, j.Stage, j.ProgressBytes, j.TotalBytes, j.ErrorCode, j.ErrorDetail, j.StorageKey, + j.FileExt, j.FileSize, j.Duration, j.Width, j.Height, j.Title, j.Uploader, j.CreatedAt, j.QueuedAt, + j.StartedAt, j.FinishedAt) + return err +} + +// GetJob loads a job. +func (s *Store) GetJob(ctx context.Context, id string) (*Job, error) { + return scanJob(s.row(ctx, `SELECT `+jobCols+` FROM jobs WHERE id = ?`, id)) +} + +// laneRank is the SQL expression that orders lanes: paid before free. +const laneRank = `CASE lane WHEN 'paid' THEN 0 ELSE 1 END` + +// queueOrder is the one ordering used for claiming and for positions. +const queueOrder = laneRank + ` ASC, priority DESC, queued_at ASC, id ASC` + +// NextQueuedJob returns the first queued job in the given lanes, locking it +// against other claimers. It must run inside a transaction. On Postgres the +// lock is FOR UPDATE SKIP LOCKED; on SQLite the immediate transaction +// already serializes writers. +func (s *Store) NextQueuedJob(ctx context.Context, lanes []string) (*Job, error) { + if !s.inTx { + return nil, errors.New("db: NextQueuedJob needs a transaction") + } + ph, args := in(lanes) + q := `SELECT ` + jobCols + ` FROM jobs WHERE status = 'queued' AND lane IN (` + ph + `) + ORDER BY ` + queueOrder + ` LIMIT 1` + if s.db.Dialect == Postgres { + q += ` FOR UPDATE SKIP LOCKED` + } + return scanJob(s.row(ctx, q, args...)) +} + +// MarkJobRunning hands a queued job to a worker. +func (s *Store) MarkJobRunning(ctx context.Context, id, workerID string, leaseUntil, now int64) (bool, error) { + n, err := s.exec(ctx, `UPDATE jobs SET status = 'running', worker_id = ?, lease_expires_at = ?, + attempts = attempts + 1, started_at = ?, stage = '', progress_bytes = 0, total_bytes = 0 + WHERE id = ? AND status = 'queued'`, workerID, leaseUntil, now, id) + return n == 1, err +} + +// HeartbeatJob extends the lease and stores progress. It reports false when +// the job is no longer owned by the worker. +func (s *Store) HeartbeatJob(ctx context.Context, id, workerID string, leaseUntil int64, stage string, done, total int64) (bool, error) { + n, err := s.exec(ctx, `UPDATE jobs SET lease_expires_at = ?, stage = ?, progress_bytes = ?, total_bytes = ? + WHERE id = ? AND worker_id = ? AND status = 'running'`, leaseUntil, stage, done, total, id, workerID) + return n == 1, err +} + +// JobResult is what a worker reports on success. +type JobResult struct { + StorageKey string + FileExt string + FileSize int64 + Duration int64 + Width int + Height int + Title string + Uploader string + Extractor string + VideoID string +} + +// CompleteJob stores the result and moves the job to delivering. +func (s *Store) CompleteJob(ctx context.Context, id, workerID string, r JobResult, now int64) (bool, error) { + n, err := s.exec(ctx, `UPDATE jobs SET status = 'delivering', storage_key = ?, file_ext = ?, file_size = ?, + duration = ?, width = ?, height = ?, + title = CASE WHEN ? <> '' THEN ? ELSE title END, + uploader = CASE WHEN ? <> '' THEN ? ELSE uploader END, + extractor = CASE WHEN ? <> '' THEN ? ELSE extractor END, + video_id = CASE WHEN ? <> '' THEN ? ELSE video_id END, + lease_expires_at = 0, stage = 'uploading', finished_at = ? + WHERE id = ? AND worker_id = ? AND status = 'running'`, + r.StorageKey, r.FileExt, r.FileSize, r.Duration, r.Width, r.Height, + r.Title, r.Title, r.Uploader, r.Uploader, r.Extractor, r.Extractor, r.VideoID, r.VideoID, + now, id, workerID) + return n == 1, err +} + +// RequeueJob puts a running job back in the queue. The original queued_at is +// kept so a retried job does not lose its place. refundAttempt gives the +// attempt back, for interruptions that were not the job's fault. +func (s *Store) RequeueJob(ctx context.Context, id, errorCode, detail string, refundAttempt bool) (bool, error) { + refund := 0 + if refundAttempt { + refund = 1 + } + n, err := s.exec(ctx, `UPDATE jobs SET status = 'queued', worker_id = '', lease_expires_at = 0, + stage = '', progress_bytes = 0, total_bytes = 0, error_code = ?, error_detail = ?, + attempts = attempts - ? + WHERE id = ? AND status = 'running'`, errorCode, detail, refund, id) + return n == 1, err +} + +// FinishJob moves a job to a terminal status from any of the given statuses. +func (s *Store) FinishJob(ctx context.Context, id, status, errorCode, detail string, from []string, now int64) (bool, error) { + ph, args := in(from) + all := append([]any{status, errorCode, detail, now, id}, args...) + n, err := s.exec(ctx, `UPDATE jobs SET status = ?, error_code = ?, error_detail = ?, lease_expires_at = 0, + finished_at = ? WHERE id = ? AND status IN (`+ph+`)`, all...) + return n == 1, err +} + +// RequestJobCancel flags a running job so the worker stops at its next +// heartbeat. +func (s *Store) RequestJobCancel(ctx context.Context, id string) error { + _, err := s.exec(ctx, `UPDATE jobs SET cancel_requested = ? WHERE id = ? AND status = 'running'`, true, id) + return err +} + +// ExpiredJobs lists running jobs whose lease ran out. +func (s *Store) ExpiredJobs(ctx context.Context, now int64) ([]*Job, error) { + return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs + WHERE status = 'running' AND lease_expires_at < ? ORDER BY id`, now)) +} + +// JobsByStatus lists jobs in a status, oldest first. +func (s *Store) JobsByStatus(ctx context.Context, status string, limit int) ([]*Job, error) { + return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status = ? ORDER BY `+queueOrder+` LIMIT ?`, + status, limit)) +} + +// CountQueued counts queued jobs in a lane. +func (s *Store) CountQueued(ctx context.Context, lane string) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND lane = ?`, lane).Scan(&n) + return n, err +} + +// QueuePosition returns how many queued jobs are ahead of j in claim order. +// Zero means j is next. +func (s *Store) QueuePosition(ctx context.Context, j *Job) (int, error) { + rank := 1 + if j.Lane == LanePaid { + rank = 0 + } + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'queued' AND id <> ? AND ( + `+laneRank+` < ? + OR (`+laneRank+` = ? AND ( + priority > ? + OR (priority = ? AND (queued_at < ? OR (queued_at = ? AND id < ?))) + )) + )`, j.ID, rank, rank, j.Priority, j.Priority, j.QueuedAt, j.QueuedAt, j.ID).Scan(&n) + return n, err +} + +// AvgJobSeconds returns the average run time of the most recent finished +// jobs, or 0 when there is no history. +func (s *Store) AvgJobSeconds(ctx context.Context, sample int) (float64, error) { + var avg sql.NullFloat64 + err := s.row(ctx, `SELECT AVG(d) FROM ( + SELECT (finished_at - started_at) / 1000.0 AS d FROM jobs + WHERE status IN ('done', 'delivering') AND started_at > 0 AND finished_at >= started_at + ORDER BY finished_at DESC LIMIT ? + ) recent`, sample).Scan(&avg) + return avg.Float64, err +} + +// CountRunning counts jobs currently held by workers. +func (s *Store) CountRunning(ctx context.Context) (int, error) { + var n int + err := s.row(ctx, `SELECT COUNT(*) FROM jobs WHERE status = 'running'`).Scan(&n) + return n, err +} diff --git a/internal/db/migrations/00001_init.sql b/internal/db/migrations/00001_init.sql new file mode 100644 index 0000000..d8c9967 --- /dev/null +++ b/internal/db/migrations/00001_init.sql @@ -0,0 +1,104 @@ +-- +goose Up +-- One schema for SQLite and Postgres. Rules that keep it portable: +-- identifiers are application generated TEXT, timestamps are unix +-- milliseconds in BIGINT, flags are BOOLEAN, no engine specific types. + +CREATE TABLE users ( + id BIGINT PRIMARY KEY, + username TEXT NOT NULL DEFAULT '', + first_name TEXT NOT NULL DEFAULT '', + lang TEXT NOT NULL DEFAULT '', + lang_override TEXT NOT NULL DEFAULT '', + banned BOOLEAN NOT NULL DEFAULT FALSE, + created_at BIGINT NOT NULL, + last_seen_at BIGINT NOT NULL +); + +-- A request is one link a user sent, shown as a card with format buttons. +CREATE TABLE requests ( + id TEXT PRIMARY KEY, + user_id BIGINT NOT NULL, + chat_id BIGINT NOT NULL, + chat_type TEXT NOT NULL DEFAULT 'private', + source_message_id BIGINT NOT NULL DEFAULT 0, + card_message_id BIGINT NOT NULL DEFAULT 0, + card_is_photo BOOLEAN NOT NULL DEFAULT FALSE, + url TEXT NOT NULL, + status TEXT NOT NULL, + info TEXT NOT NULL DEFAULT '', + lang TEXT NOT NULL DEFAULT 'en', + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX requests_user_idx ON requests (user_id, created_at); + +-- A job is one unit of work for a worker. +CREATE TABLE jobs ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL DEFAULT 'download', + url TEXT NOT NULL, + extractor TEXT NOT NULL DEFAULT '', + video_id TEXT NOT NULL DEFAULT '', + profile TEXT NOT NULL, + cache_key TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL, + lane TEXT NOT NULL DEFAULT 'free', + priority INTEGER NOT NULL DEFAULT 0, + required_tags TEXT NOT NULL DEFAULT '', + max_size BIGINT NOT NULL DEFAULT 0, + max_duration BIGINT NOT NULL DEFAULT 0, + attempts INTEGER NOT NULL DEFAULT 0, + max_attempts INTEGER NOT NULL DEFAULT 2, + worker_id TEXT NOT NULL DEFAULT '', + lease_expires_at BIGINT NOT NULL DEFAULT 0, + cancel_requested BOOLEAN NOT NULL DEFAULT FALSE, + stage TEXT NOT NULL DEFAULT '', + progress_bytes BIGINT NOT NULL DEFAULT 0, + total_bytes BIGINT NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + error_detail TEXT NOT NULL DEFAULT '', + storage_key TEXT NOT NULL DEFAULT '', + file_ext TEXT NOT NULL DEFAULT '', + file_size BIGINT NOT NULL DEFAULT 0, + duration BIGINT NOT NULL DEFAULT 0, + width INTEGER NOT NULL DEFAULT 0, + height INTEGER NOT NULL DEFAULT 0, + title TEXT NOT NULL DEFAULT '', + uploader TEXT NOT NULL DEFAULT '', + created_at BIGINT NOT NULL, + queued_at BIGINT NOT NULL, + started_at BIGINT NOT NULL DEFAULT 0, + finished_at BIGINT NOT NULL DEFAULT 0 +); +CREATE INDEX jobs_queue_idx ON jobs (status, lane, priority, queued_at); +CREATE INDEX jobs_lease_idx ON jobs (status, lease_expires_at); + +-- A delivery is one requester waiting for the result of a job. +CREATE TABLE deliveries ( + id TEXT PRIMARY KEY, + job_id TEXT NOT NULL REFERENCES jobs (id), + request_id TEXT NOT NULL DEFAULT '', + user_id BIGINT NOT NULL, + chat_id BIGINT NOT NULL, + chat_type TEXT NOT NULL DEFAULT 'private', + reply_to_message_id BIGINT NOT NULL DEFAULT 0, + status_message_id BIGINT NOT NULL DEFAULT 0, + status_is_photo BOOLEAN NOT NULL DEFAULT FALSE, + lang TEXT NOT NULL DEFAULT 'en', + status TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + error_code TEXT NOT NULL DEFAULT '', + tg_file_id TEXT NOT NULL DEFAULT '', + tg_message_id BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL +); +CREATE INDEX deliveries_job_idx ON deliveries (job_id); +CREATE INDEX deliveries_user_idx ON deliveries (user_id, status); +CREATE INDEX deliveries_status_idx ON deliveries (status, updated_at); + +-- +goose Down +DROP TABLE deliveries; +DROP TABLE jobs; +DROP TABLE requests; +DROP TABLE users; diff --git a/internal/db/models.go b/internal/db/models.go new file mode 100644 index 0000000..3d656c2 --- /dev/null +++ b/internal/db/models.go @@ -0,0 +1,132 @@ +package db + +// Request statuses. +const ( + RequestReady = "ready" // card shown, waiting for a format choice + RequestChosen = "chosen" // a format was picked and a job exists + RequestCancelled = "cancelled" // the requester dismissed the card +) + +// Job statuses. +const ( + JobQueued = "queued" + JobRunning = "running" + JobDelivering = "delivering" // file is stored, the core is sending it + JobDone = "done" + JobFailed = "failed" + JobCancelled = "cancelled" +) + +// Delivery statuses. +const ( + DeliveryPending = "pending" + DeliverySending = "sending" + DeliverySent = "sent" + DeliveryFailed = "failed" + DeliveryCancelled = "cancelled" +) + +// Queue lanes. +const ( + LanePaid = "paid" + LaneFree = "free" +) + +// Job kinds. +const ( + KindDownload = "download" +) + +// User is a Telegram user known to the bot. +type User struct { + ID int64 + Username string + FirstName string + Lang string // detected from Telegram + LangOverride string // chosen with /language + Banned bool + CreatedAt int64 + LastSeenAt int64 +} + +// Request is one link sent by a user. +type Request struct { + ID string + UserID int64 + ChatID int64 + ChatType string + SourceMessageID int64 + CardMessageID int64 + CardIsPhoto bool + URL string + Status string + Info string // JSON, see service.CardInfo + Lang string + CreatedAt int64 + UpdatedAt int64 +} + +// Job is one unit of work for a worker. +type Job struct { + ID string + Kind string + URL string + Extractor string + VideoID string + Profile string + CacheKey string + Status string + Lane string + Priority int + RequiredTags string + MaxSize int64 + MaxDuration int64 // seconds + Attempts int + MaxAttempts int + WorkerID string + LeaseExpiresAt int64 + CancelRequested bool + Stage string + ProgressBytes int64 + TotalBytes int64 + ErrorCode string + ErrorDetail string + StorageKey string + FileExt string + FileSize int64 + Duration int64 // seconds + Width int + Height int + Title string + Uploader string + CreatedAt int64 + QueuedAt int64 + StartedAt int64 + FinishedAt int64 +} + +// Active reports whether the job still needs a worker or the core. +func (j *Job) Active() bool { + return j.Status == JobQueued || j.Status == JobRunning || j.Status == JobDelivering +} + +// Delivery is one requester waiting for a job. +type Delivery struct { + ID string + JobID string + RequestID string + UserID int64 + ChatID int64 + ChatType string + ReplyToMessageID int64 + StatusMessageID int64 + StatusIsPhoto bool + Lang string + Status string + Attempts int + ErrorCode string + TgFileID string + TgMessageID int64 + CreatedAt int64 + UpdatedAt int64 +} diff --git a/internal/db/postgres.go b/internal/db/postgres.go new file mode 100644 index 0000000..4741049 --- /dev/null +++ b/internal/db/postgres.go @@ -0,0 +1,12 @@ +package db + +import ( + "context" + "errors" +) + +// openPostgres is replaced by the real implementation in Phase 4. Keeping +// the entry point here means the driver switch in Open never changes. +func openPostgres(_ context.Context, _ string) (*DB, error) { + return nil, errors.New("db: the postgres backend is not built into this version yet") +} diff --git a/internal/db/requests.go b/internal/db/requests.go new file mode 100644 index 0000000..83ecc12 --- /dev/null +++ b/internal/db/requests.go @@ -0,0 +1,50 @@ +package db + +import "context" + +const requestCols = `id, user_id, chat_id, chat_type, source_message_id, card_message_id, + card_is_photo, url, status, info, lang, created_at, updated_at` + +func scanRequest(sc interface{ Scan(...any) error }) (*Request, error) { + var r Request + err := sc.Scan(&r.ID, &r.UserID, &r.ChatID, &r.ChatType, &r.SourceMessageID, &r.CardMessageID, + &r.CardIsPhoto, &r.URL, &r.Status, &r.Info, &r.Lang, &r.CreatedAt, &r.UpdatedAt) + if err != nil { + return nil, notFound(err) + } + return &r, nil +} + +// InsertRequest stores a new request. +func (s *Store) InsertRequest(ctx context.Context, r *Request) error { + if r.CreatedAt == 0 { + r.CreatedAt = NowMilli() + } + r.UpdatedAt = r.CreatedAt + _, err := s.exec(ctx, `INSERT INTO requests (`+requestCols+`) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + r.ID, r.UserID, r.ChatID, r.ChatType, r.SourceMessageID, r.CardMessageID, + r.CardIsPhoto, r.URL, r.Status, r.Info, r.Lang, r.CreatedAt, r.UpdatedAt) + return err +} + +// GetRequest loads a request. +func (s *Store) GetRequest(ctx context.Context, id string) (*Request, error) { + return scanRequest(s.row(ctx, `SELECT `+requestCols+` FROM requests WHERE id = ?`, id)) +} + +// SetRequestCard records which message shows the card. +func (s *Store) SetRequestCard(ctx context.Context, id string, messageID int64, isPhoto bool) error { + _, err := s.exec(ctx, `UPDATE requests SET card_message_id = ?, card_is_photo = ?, updated_at = ? WHERE id = ?`, + messageID, isPhoto, NowMilli(), id) + return err +} + +// TransitionRequest moves a request from one status to another and reports +// whether the row was in the expected status. It is the guard against two +// button presses racing each other. +func (s *Store) TransitionRequest(ctx context.Context, id, from, to string) (bool, error) { + n, err := s.exec(ctx, `UPDATE requests SET status = ?, updated_at = ? WHERE id = ? AND status = ?`, + to, NowMilli(), id, from) + return n == 1, err +} diff --git a/internal/db/users.go b/internal/db/users.go new file mode 100644 index 0000000..6a1e30b --- /dev/null +++ b/internal/db/users.go @@ -0,0 +1,38 @@ +package db + +import "context" + +const userCols = `id, username, first_name, lang, lang_override, banned, created_at, last_seen_at` + +func scanUser(sc interface{ Scan(...any) error }) (*User, error) { + var u User + err := sc.Scan(&u.ID, &u.Username, &u.FirstName, &u.Lang, &u.LangOverride, &u.Banned, &u.CreatedAt, &u.LastSeenAt) + if err != nil { + return nil, notFound(err) + } + return &u, nil +} + +// UpsertUser records a sighting of a Telegram user and returns the stored +// row. The detected language follows Telegram; an override is kept. +func (s *Store) UpsertUser(ctx context.Context, id int64, username, firstName, lang string) (*User, error) { + now := NowMilli() + _, err := s.exec(ctx, ` + INSERT INTO users (id, username, first_name, lang, created_at, last_seen_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (id) DO UPDATE SET + username = excluded.username, + first_name = excluded.first_name, + lang = CASE WHEN excluded.lang <> '' THEN excluded.lang ELSE users.lang END, + last_seen_at = excluded.last_seen_at`, + id, username, firstName, lang, now, now) + if err != nil { + return nil, err + } + return s.GetUser(ctx, id) +} + +// GetUser loads a user by Telegram ID. +func (s *Store) GetUser(ctx context.Context, id int64) (*User, error) { + return scanUser(s.row(ctx, `SELECT `+userCols+` FROM users WHERE id = ?`, id)) +} diff --git a/internal/i18n/format.go b/internal/i18n/format.go new file mode 100644 index 0000000..95a86f9 --- /dev/null +++ b/internal/i18n/format.go @@ -0,0 +1,67 @@ +package i18n + +import ( + "fmt" + "time" +) + +// Size formats a byte count for humans in the user's locale, for example +// "61.9 MB" in English and "61,9 MB" in Spanish and Dutch. +func (b *Bundle) Size(lang string, bytes int64) string { + const unit = 1024 + p := b.printer(lang) + switch { + case bytes < unit: + return p.Sprintf("%d B", bytes) + case bytes < unit*unit: + return p.Sprintf("%.0f KB", float64(bytes)/unit) + case bytes < unit*unit*unit: + v := float64(bytes) / (unit * unit) + if v >= 100 { + return p.Sprintf("%.0f MB", v) + } + return p.Sprintf("%.1f MB", v) + default: + return p.Sprintf("%.2f GB", float64(bytes)/(unit*unit*unit)) + } +} + +// Clock formats a media duration as 1:02:03 or 2:03. +func Clock(seconds int64) string { + if seconds < 0 { + seconds = 0 + } + h, m, s := seconds/3600, seconds/60%60, seconds%60 + if h > 0 { + return fmt.Sprintf("%d:%02d:%02d", h, m, s) + } + return fmt.Sprintf("%d:%02d", m, s) +} + +// Span formats a length of time in words, such as "30 seconds", "5 minutes" +// or "2 hours", using the plural rules of the language. +func (b *Bundle) Span(lang string, d time.Duration) string { + switch { + case d < time.Minute: + n := int(d.Round(time.Second) / time.Second) + if n < 1 { + n = 1 + } + return b.T(lang, "unit.seconds", Args{"Count": n}) + case d < time.Hour: + return b.T(lang, "unit.minutes", Args{"Count": int(d.Round(time.Minute) / time.Minute)}) + default: + return b.T(lang, "unit.hours", Args{"Count": int(d.Round(time.Hour) / time.Hour)}) + } +} + +// Percent formats a ratio in the 0 to 1 range as a whole percentage. +func (b *Bundle) Percent(lang string, ratio float64) string { + if ratio < 0 { + ratio = 0 + } + if ratio > 1 { + ratio = 1 + } + return b.printer(lang).Sprintf("%d%%", int(ratio*100+0.5)) +} diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..be46a1e --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,196 @@ +// Package i18n wraps go-i18n. Every user-facing string of the bot is looked +// up here by message ID; handlers never contain literal text. +package i18n + +import ( + "fmt" + "html" + "io/fs" + "log/slog" + "sort" + "strings" + "sync" + + "github.com/BurntSushi/toml" + goi18n "github.com/nicksnyder/go-i18n/v2/i18n" + "golang.org/x/text/language" + "golang.org/x/text/message" +) + +// Default is the source language and the last fallback. +const Default = "en" + +// Args is the template data of a message. +type Args map[string]any + +// Raw marks a template value as already safe HTML, so HTML does not escape +// it. Use it only for text produced by this package. +type Raw string + +// Bundle holds the loaded catalogs. +type Bundle struct { + bundle *goi18n.Bundle + tags []language.Tag + names []string + matcher language.Matcher + log *slog.Logger + + mu sync.Mutex + localizers map[string]*goi18n.Localizer + printers map[string]*message.Printer +} + +// Load reads every *.toml catalog in fsys. The file name is the language +// tag, for example en.toml or es.toml. +func Load(fsys fs.FS, log *slog.Logger) (*Bundle, error) { + if log == nil { + log = slog.Default() + } + b := &Bundle{ + bundle: goi18n.NewBundle(language.English), + log: log, + localizers: map[string]*goi18n.Localizer{}, + printers: map[string]*message.Printer{}, + } + b.bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) + files, err := fs.Glob(fsys, "*.toml") + if err != nil { + return nil, err + } + sort.Strings(files) + hasDefault := false + for _, name := range files { + data, err := fs.ReadFile(fsys, name) + if err != nil { + return nil, err + } + mf, err := b.bundle.ParseMessageFileBytes(data, name) + if err != nil { + return nil, fmt.Errorf("i18n: %s: %w", name, err) + } + if mf.Tag == language.English { + hasDefault = true + } + } + if !hasDefault { + return nil, fmt.Errorf("i18n: the %s catalog is missing", Default) + } + // English first, so it is the matcher's default. + b.tags = []language.Tag{language.English} + for _, t := range b.bundle.LanguageTags() { + if t != language.English { + b.tags = append(b.tags, t) + } + } + for _, t := range b.tags { + b.names = append(b.names, t.String()) + } + b.matcher = language.NewMatcher(b.tags) + return b, nil +} + +// Langs returns the loaded language tags, English first. +func (b *Bundle) Langs() []string { return append([]string(nil), b.names...) } + +// Resolve maps any language code, such as the language_code Telegram sends, +// to the closest loaded language. Regional variants fall back to their base +// language (es-PY to es) and unknown languages to English. +func (b *Bundle) Resolve(code string) string { + if code == "" { + return Default + } + tag, err := language.Parse(code) + if err != nil { + return Default + } + _, idx, conf := b.matcher.Match(tag) + if conf == language.No { + return Default + } + return b.names[idx] +} + +func (b *Bundle) localizer(lang string) *goi18n.Localizer { + b.mu.Lock() + defer b.mu.Unlock() + if l, ok := b.localizers[lang]; ok { + return l + } + // The chain is the exact tag, its base language, then English. + chain := []string{lang} + if base, _, ok := strings.Cut(lang, "-"); ok { + chain = append(chain, base) + } + chain = append(chain, Default) + l := goi18n.NewLocalizer(b.bundle, chain...) + b.localizers[lang] = l + return l +} + +func (b *Bundle) printer(lang string) *message.Printer { + b.mu.Lock() + defer b.mu.Unlock() + if p, ok := b.printers[lang]; ok { + return p + } + tag, err := language.Parse(lang) + if err != nil { + tag = language.English + } + p := message.NewPrinter(tag) + b.printers[lang] = p + return p +} + +// T returns the plain text of a message. Use it for button labels, callback +// answers and anything else Telegram does not parse as HTML. A "Count" +// argument selects the plural form. +func (b *Bundle) T(lang, id string, args Args) string { + cfg := &goi18n.LocalizeConfig{MessageID: id, TemplateData: map[string]any(args)} + if args != nil { + if c, ok := args["Count"]; ok { + cfg.PluralCount = c + } + } + out, err := b.localizer(lang).Localize(cfg) + if err != nil && out == "" { + // A missing key is a bug caught by the catalog test. At runtime we + // show the ID so the gap is visible and searchable. + b.log.Error("i18n: missing message", "id", id, "lang", lang, "err", err) + return id + } + return out +} + +// HTML returns a message for parse_mode HTML. String arguments are escaped, +// so titles and names coming from the web cannot inject markup. +func (b *Bundle) HTML(lang, id string, args Args) string { + if len(args) == 0 { + return b.T(lang, id, args) + } + safe := make(Args, len(args)) + for k, v := range args { + switch x := v.(type) { + case Raw: + safe[k] = string(x) + case string: + safe[k] = html.EscapeString(x) + default: + safe[k] = v + } + } + return b.T(lang, id, safe) +} + +// Has reports whether the message exists in the given language itself, not +// through fallback. +func (b *Bundle) Has(lang, id string) bool { + tag, err := language.Parse(lang) + if err != nil { + return false + } + _, gotTag, err := goi18n.NewLocalizer(b.bundle, lang).LocalizeWithTag(&goi18n.LocalizeConfig{ + MessageID: id, PluralCount: 2, TemplateData: map[string]any{}, + }) + return err == nil && gotTag == tag +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go new file mode 100644 index 0000000..8abba50 --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,146 @@ +package i18n_test + +import ( + "strings" + "testing" + "testing/fstest" + "time" + + "github.com/noderunners/dlbot/internal/i18n" + "github.com/noderunners/dlbot/internal/ytdlp" + "github.com/noderunners/dlbot/locales" +) + +func load(t *testing.T) *i18n.Bundle { + t.Helper() + b, err := i18n.Load(locales.FS, nil) + if err != nil { + t.Fatal(err) + } + return b +} + +func TestEveryErrorCodeHasAMessage(t *testing.T) { + b := load(t) + for _, code := range ytdlp.KnownCodes { + if !b.Has("en", "error."+string(code)) { + t.Errorf("the en catalog has no message for error.%s", code) + } + } +} + +func TestPluralsAndArgs(t *testing.T) { + b := load(t) + if got := b.T("en", "unit.minutes", i18n.Args{"Count": 1}); got != "1 minute" { + t.Errorf("one = %q", got) + } + if got := b.T("en", "unit.minutes", i18n.Args{"Count": 5}); got != "5 minutes" { + t.Errorf("other = %q", got) + } + if got := b.T("en", "btn.res", i18n.Args{"Height": 720}); got != "720p" { + t.Errorf("btn.res = %q", got) + } +} + +func TestHTMLEscapesArguments(t *testing.T) { + b := load(t) + got := b.HTML("en", "start.private", i18n.Args{"Name": ""}) + if strings.Contains(got, "