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 } // A cache hit starts with a file_id. Otherwise the first upload yields // one that later requesters reuse, so the file crosses the wire once. for _, d := range dels { if ctx.Err() != nil { return } if stop := b.deliverOne(ctx, job, d); stop { return // the job went back to the queue for a fresh download } } b.finishIfServed(ctx, job) } // sentFile describes a file Telegram accepted. type sentFile struct { ID string UniqueID string MessageID int64 } // deliverOne sends the file to one requester. It updates job.TgFileID // when an upload produced a file_id. stop is true when the cached file // turned out to be unusable and the job was queued for a fresh download. func (b *Bot) deliverOne(ctx context.Context, job *db.Job, d *db.Delivery) (stop bool) { 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 false } saveCtx := context.WithoutCancel(ctx) // Requesters who share a job keep their own caps. The file somebody // with a pass asked for can be too big for a free user waiting on the // same job; that user is refused here, like on a download of their own. if code := overCap(job, d); code != "" { _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryFailed, code) b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, code)+b.release(ctx, d)) return false } 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)) sent, err := b.sendFile(sendCtx, job, d, job.TgFileID) if err != nil && job.TgFileID != "" && tg.IsBadFileID(err) { sent, err, stop = b.heal(sendCtx, job, d, err) } stopAction() if stop { _, _ = b.store.TransitionDelivery(saveCtx, d.ID, db.DeliverySending, db.DeliveryPending, "") return true } if err != nil { 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") b.release(ctx, d) 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")+b.release(ctx, d)) 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")+b.release(ctx, d)) } return false } if sent.ID != "" && sent.ID != job.TgFileID { job.TgFileID = sent.ID if err := b.store.SetJobFileID(saveCtx, job.ID, sent.ID); err != nil { log.Error("save file id", "err", err) } // The result enters the cache as soon as it exists, before the // requester is told "done". The next request for it, even one that // arrives in this instant, is then a cache hit. b.cacheResult(saveCtx, job, sent.UniqueID) } if err := b.store.MarkDeliverySent(saveCtx, d.ID, sent.ID, sent.MessageID); err != nil { log.Error("mark delivery sent", "err", err) } if err := b.svc.RecordDelivered(saveCtx, d, job.FileSize); err != nil { log.Error("record usage", "err", err) } log.Info("file delivered", "size", job.FileSize, "profile", job.Profile, "cache_hit", job.CacheHit) b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.done", nil)) return false } // overCap checks a finished file against one requester's own caps. func overCap(job *db.Job, d *db.Delivery) string { kind := jobProfile(job).Kind() if kind == media.KindThumb || kind == media.KindSubs { return "" } if d.MaxSize > 0 && job.FileSize > d.MaxSize { return "too_large" } if d.MaxDuration > 0 && job.Duration > d.MaxDuration+1 { return "too_long" } return "" } // heal is the cache repairing itself after Telegram refused a file_id. // The file_id layer is dropped first. Then the stored copy is uploaded // again, which yields a fresh file_id that is written back to the entry. // Without a usable stored copy the job is queued for a fresh download and // stop is true. Either way the requester gets the file, and the entry is // correct for the next one. func (b *Bot) heal(ctx context.Context, job *db.Job, d *db.Delivery, cause error) (sent sentFile, err error, stop bool) { log := b.log.With("job_id", job.ID, "extractor", job.Extractor, "video_id", job.VideoID, "profile", job.Profile) log.Warn("cached file_id rejected, healing", "err", cause) bg := context.WithoutCancel(ctx) // The entry to repair is the one this job was served from, which for // an alias hit is a higher profile than the job's own. entry := b.cache.ProfileServing(bg, job) if err := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, "", ""); err != nil { log.Error("clear cached file id", "err", err) } job.TgFileID = "" _ = b.store.SetJobFileID(bg, job.ID, "") if job.StorageKey != "" { if _, serr := b.storage.Stat(ctx, job.StorageKey); serr == nil { sent, err = b.sendFile(ctx, job, d, "") if err == nil { if cerr := b.cache.SetFileID(bg, job.Extractor, job.VideoID, entry, sent.ID, sent.UniqueID); cerr != nil { log.Error("save healed file id", "err", cerr) } log.Info("healed from the stored copy") } return sent, err, false } // The entry points at a file that is gone. if derr := b.cache.DropStored(bg, job.Extractor, job.VideoID, entry); derr != nil { log.Error("drop missing stored copy", "err", derr) } } // Nothing left to serve from: forget the entry and download again. The // request was already admitted and charged, so this costs nothing more. if ferr := b.cache.Forget(bg, job.Extractor, job.VideoID, entry); ferr != nil { log.Error("forget cache entry", "err", ferr) } requeued, rerr := b.sched.Redownload(bg, job.ID) if rerr != nil || !requeued { return sentFile{}, cause, false } log.Info("no stored copy, downloading again") return sentFile{}, nil, true } // 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) (sentFile, 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" } sent, 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 sent, err } func (b *Bot) sendAs(ctx context.Context, mode string, job *db.Job, d *db.Delivery, reuseFileID string) (sentFile, error) { var input telego.InputFile if reuseFileID != "" { input = telego.InputFile{FileID: reuseFileID} } else { if job.StorageKey == "" { return sentFile{}, 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 sentFile{}, errors.New("bot: stored file is missing") } return sentFile{}, 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 sentFile{}, err } if msg.Video != nil { return sentFile{msg.Video.FileID, msg.Video.FileUniqueID, int64(msg.MessageID)}, nil } if msg.Document != nil { // Telegram may store odd videos as documents return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil } return sentFile{MessageID: 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 sentFile{}, err } if msg.Audio != nil { return sentFile{msg.Audio.FileID, msg.Audio.FileUniqueID, int64(msg.MessageID)}, nil } return sentFile{MessageID: 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 sentFile{}, err } if n := len(msg.Photo); n > 0 { return sentFile{msg.Photo[n-1].FileID, msg.Photo[n-1].FileUniqueID, int64(msg.MessageID)}, nil } return sentFile{MessageID: 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 sentFile{}, err } if msg.Document != nil { return sentFile{msg.Document.FileID, msg.Document.FileUniqueID, int64(msg.MessageID)}, nil } return sentFile{MessageID: int64(msg.MessageID)}, nil } } // finishIfServed closes a delivering job once nobody waits for it, and // decides what happens to the stored file: it enters the cache when the // result is cacheable, and is deleted otherwise. 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 } cur, err := b.store.GetJob(ctx, job.ID) if err != nil || cur.Status != db.JobDelivering { return } if err := b.sched.FinishDelivered(ctx, cur.ID); err != nil { b.log.Error("finish job", "job_id", cur.ID, "err", err) return } b.pumpSoon() if cur.CacheHit { return // the file belongs to the cache entry it was served from } // Usually the result was cached at the first successful send. When no // send succeeded (everyone cancelled or was unreachable) the download // itself still worked, so the file is kept for the next request. if b.cacheResult(ctx, cur, "") { return } b.removeStored(ctx, cur) } // cacheResult puts a finished job's file in the cache and reports whether // the cache now owns that file. It is safe to call more than once. func (b *Bot) cacheResult(ctx context.Context, job *db.Job, uniqueID string) bool { if job.CacheHit || !job.Cacheable || !b.cache.Enabled() || job.StorageKey == "" { return false } if e, err := b.cache.Lookup(ctx, job.Extractor, job.VideoID, jobProfile(job)); err == nil && e != nil && e.StorageKey == job.StorageKey && (e.TgFileID != "" || job.TgFileID == "") { return true // already in, with everything this job knows } if err := b.cache.Put(ctx, job, job.TgFileID, uniqueID); err != nil { b.log.Debug("result not cached", "job_id", job.ID, "err", err) return false } return true } 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 } // The automatic retry is spent: give back what the download cost. b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.failureText(d.Lang, job.ErrorCode)+b.release(ctx, d)) } 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)+b.release(ctx, d)) } } // 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: } }