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 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+226
View File
@@ -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)
}