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>
350 lines
11 KiB
Go
350 lines
11 KiB
Go
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:
|
|
}
|
|
}
|