- One message per job: the status message is deleted once the file is
sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
throttled to one per 2.5 s per message; a state that arrives too soon
is shown later instead of dropped. The wait estimate is 0 with a free
slot.
- Caption with title (uploader and date when generic), uploader,
duration, a short source link without tracking parameters and an
optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
fallback to English is logged as a bug; a test walks every screen in
Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
"best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
"already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
language.
- Personal /settings in private chats with an "Add me to a group"
button.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
377 lines
12 KiB
Go
377 lines
12 KiB
Go
package bot
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"time"
|
|
|
|
"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/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
|
|
buttons string
|
|
phase string
|
|
at time.Time
|
|
// pending is the newest state that arrived too soon after the last
|
|
// edit. timer shows it once the gap is over.
|
|
pending *pendingStatus
|
|
timer *time.Timer
|
|
}
|
|
|
|
type pendingStatus struct {
|
|
d *db.Delivery
|
|
text string
|
|
kb *telego.InlineKeyboardMarkup
|
|
phase string
|
|
}
|
|
|
|
// keyboardSignature identifies a keyboard by the callback data and links
|
|
// of its buttons.
|
|
func keyboardSignature(kb *telego.InlineKeyboardMarkup) string {
|
|
if kb == nil {
|
|
return ""
|
|
}
|
|
var sb strings.Builder
|
|
for _, row := range kb.InlineKeyboard {
|
|
for _, btn := range row {
|
|
sb.WriteString(btn.CallbackData)
|
|
sb.WriteString(btn.URL)
|
|
sb.WriteByte('|')
|
|
}
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
// 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 ev := <-b.payEvents:
|
|
b.safely("payment", func() { b.handlePayEvent(ctx, ev) })
|
|
case <-b.pump:
|
|
b.safely("playlist", func() { b.pumpPlaylists(ctx) })
|
|
case <-t.C:
|
|
b.safely("reconcile", func() { b.reconcile(ctx) })
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *Bot) handleEvent(ctx context.Context, ev sched.Event) {
|
|
b.observe(ctx, ev)
|
|
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)
|
|
b.pumpSoon()
|
|
case sched.EventCancelled:
|
|
b.cleanupCancelled(ctx, ev.JobID)
|
|
b.pumpSoon()
|
|
}
|
|
}
|
|
|
|
// 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) })
|
|
|
|
// Refunds and paid follow-ups that an interruption left undone.
|
|
b.svc.ReleasePending(ctx)
|
|
b.fulfilPending(ctx)
|
|
b.pumpPlaylists(ctx)
|
|
|
|
// 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)
|
|
}
|
|
if b.quietQueue(pos) {
|
|
// About to start: the queue is not worth mentioning.
|
|
return head + b.tr.HTML(lang, "status.downloading", nil), cancel, "queued"
|
|
}
|
|
kb := cancel
|
|
if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 {
|
|
kb = b.queuedKeyboard(lang, d.ID)
|
|
}
|
|
return head + b.tr.HTML(lang, "status.queued", i18n.Args{
|
|
"Position": pos.Ahead + 1,
|
|
"Wait": b.tr.Span(lang, pos.Wait),
|
|
}), kb, "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)})
|
|
}
|
|
|
|
// quietQueue reports whether a queued job is about to start: first in
|
|
// line and a short expected wait. Its status then just says it is
|
|
// downloading, without a position.
|
|
func (b *Bot) quietQueue(pos sched.Position) bool {
|
|
return pos.Ahead == 0 && pos.Wait <= time.Duration(b.cfg.QueueNoticeThresholdSeconds)*time.Second
|
|
}
|
|
|
|
// setStatus edits the status message unless nothing changed. A message is
|
|
// edited at most once per statusMinGap: Telegram limits how often a
|
|
// message may be edited, and a stream of edits only makes it flicker. A
|
|
// state that arrives too soon is not lost; the newest one is shown when
|
|
// the gap is over.
|
|
func (b *Bot) setStatus(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup, phase string, _ bool) {
|
|
if d.StatusMessageID == 0 {
|
|
return
|
|
}
|
|
now := time.Now()
|
|
// What the message shows is its text and its buttons. A change in
|
|
// either is worth an edit, for example "Skip the queue" disappearing.
|
|
sig := keyboardSignature(kb)
|
|
shown := text + "\x00" + sig
|
|
b.statusMu.Lock()
|
|
st := b.statuses[d.ID]
|
|
if st == nil {
|
|
st = &statusState{}
|
|
b.statuses[d.ID] = st
|
|
}
|
|
if st.text == shown {
|
|
st.pending = nil
|
|
b.statusMu.Unlock()
|
|
return
|
|
}
|
|
if wait := b.statusMinGap - now.Sub(st.at); !st.at.IsZero() && wait > 0 {
|
|
st.pending = &pendingStatus{d: d, text: text, kb: kb, phase: phase}
|
|
if st.timer == nil {
|
|
st.timer = time.AfterFunc(wait, func() { b.flushStatus(ctx, d.ID, st) })
|
|
}
|
|
b.statusMu.Unlock()
|
|
return
|
|
}
|
|
st.text, st.buttons, st.phase, st.at, st.pending = shown, sig, phase, now, nil
|
|
b.statusMu.Unlock()
|
|
|
|
if b.liveStatus(ctx, d, kb) {
|
|
return
|
|
}
|
|
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()
|
|
}
|
|
}
|
|
}
|
|
|
|
// flushStatus shows the state that waited for the edit gap, unless the
|
|
// delivery ended in the meantime.
|
|
func (b *Bot) flushStatus(ctx context.Context, deliveryID string, st *statusState) {
|
|
b.statusMu.Lock()
|
|
if b.statuses[deliveryID] != st {
|
|
b.statusMu.Unlock()
|
|
return
|
|
}
|
|
p := st.pending
|
|
st.pending, st.timer = nil, nil
|
|
b.statusMu.Unlock()
|
|
if p == nil || ctx.Err() != nil {
|
|
return
|
|
}
|
|
b.safely("status", func() { b.setStatus(ctx, p.d, p.text, p.kb, p.phase, false) })
|
|
}
|
|
|
|
// forgetStatus drops the throttling state of a delivery that ended.
|
|
func (b *Bot) forgetStatus(deliveryID string) {
|
|
b.statusMu.Lock()
|
|
if st := b.statuses[deliveryID]; st != nil && st.timer != nil {
|
|
st.timer.Stop()
|
|
}
|
|
delete(b.statuses, deliveryID)
|
|
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.finalStatusKB(ctx, d, text, nil)
|
|
}
|
|
|
|
// finalStatusKB is finalStatus with buttons under the outcome, such as
|
|
// "Try again" under a failure.
|
|
func (b *Bot) finalStatusKB(ctx context.Context, d *db.Delivery, text string, kb *telego.InlineKeyboardMarkup) {
|
|
b.forgetStatus(d.ID)
|
|
if b.liveFinal(ctx, d, text, kb) {
|
|
return
|
|
}
|
|
if d.StatusMessageID != 0 {
|
|
err := b.edit(ctx, d.ChatID, d.StatusMessageID, d.StatusIsPhoto, text, kb)
|
|
if err == nil || !tg.IsMessageGone(err) {
|
|
return
|
|
}
|
|
}
|
|
_, _ = b.send(ctx, d.ChatID, d.ReplyToMessageID, text, kb)
|
|
}
|
|
|
|
// failureKeyboard offers the next step under a failed delivery.
|
|
func (b *Bot) failureKeyboard(ctx context.Context, d *db.Delivery, job *db.Job, code string) *telego.InlineKeyboardMarkup {
|
|
req, err := b.store.GetRequest(ctx, d.RequestID)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return b.errorKeyboard(d.Lang, req, jobProfile(job), code)
|
|
}
|
|
|
|
// observe feeds the metrics from job events.
|
|
func (b *Bot) observe(ctx context.Context, ev sched.Event) {
|
|
if b.metrics == nil {
|
|
return
|
|
}
|
|
switch ev.Type {
|
|
case sched.EventStarted, sched.EventStored, sched.EventFailed, sched.EventCancelled:
|
|
default:
|
|
return
|
|
}
|
|
job, err := b.store.GetJob(ctx, ev.JobID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
switch ev.Type {
|
|
case sched.EventStarted:
|
|
if job.QueuedAt > 0 && job.StartedAt >= job.QueuedAt {
|
|
b.metrics.QueueWait(time.Duration(job.StartedAt-job.QueuedAt) * time.Millisecond)
|
|
}
|
|
case sched.EventStored:
|
|
b.metrics.JobFinished("done", job.Lane)
|
|
case sched.EventFailed:
|
|
b.metrics.JobFinished("failed", job.Lane)
|
|
b.metrics.DownloadError(links.Site(job.URL), job.ErrorCode)
|
|
case sched.EventCancelled:
|
|
b.metrics.JobFinished("cancelled", job.Lane)
|
|
}
|
|
}
|