package bot import ( "context" "errors" "html" "strconv" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/billing" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/ids" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/service" "github.com/noderunners/dlbot/internal/ytdlp" ) // This file is the bot's side of the Mini App. The app is another way to // press the same buttons: every operation here goes through the same // service calls as a chat message, so limits, prices and refunds are // decided in one place. Files and status always arrive in the user's // private chat with the bot. // AppJob is one active download as the Mini App shows it. type AppJob struct { ID string `json:"id"` Title string `json:"title"` Profile string `json:"profile"` Status string `json:"status"` Stage string `json:"stage,omitempty"` Position int `json:"position,omitempty"` WaitSeconds int `json:"wait_seconds,omitempty"` Progress float64 `json:"progress"` CanCancel bool `json:"can_cancel"` CanPrioritize bool `json:"can_prioritize"` SkipPrice int64 `json:"skip_price,omitempty"` } // AppQueue lists a user's active downloads. func (b *Bot) AppQueue(ctx context.Context, userID int64) ([]AppJob, error) { dels, err := b.store.ActiveDeliveriesForUser(ctx, userID) if err != nil { return nil, err } out := []AppJob{} for _, d := range dels { job, err := b.store.GetJob(ctx, d.JobID) if err != nil { continue } j := AppJob{ ID: d.ID, Title: job.Title, Profile: job.Profile, Status: job.Status, Stage: job.Stage, CanCancel: d.Status == db.DeliveryPending, } switch job.Status { case db.JobQueued: if pos, err := b.sched.Position(ctx, job, b.slots()); err == nil { j.Position, j.WaitSeconds = pos.Ahead+1, int(pos.Wait.Seconds()) } if job.Lane == db.LaneFree && b.bill.Enabled() && b.cfg.Prices.SkipQueue > 0 { j.CanPrioritize, j.SkipPrice = true, b.cfg.Prices.SkipQueue } case db.JobRunning: if job.TotalBytes > 0 { j.Progress = float64(job.ProgressBytes) / float64(job.TotalBytes) } case db.JobDelivering: j.Progress, j.Stage = 1, ytdlp.StageUploading } out = append(out, j) } return out, nil } // AppProbe looks a link up for the paste box, after the same gate a chat // message passes. func (b *Bot) AppProbe(ctx context.Context, user *db.User, url string) (*service.CardInfo, error) { who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} if err := b.svc.Gate(ctx, who); err != nil { return nil, err } if !b.rate.allow("u:"+itoa(user.ID), b.cfg.Rate.UserPerMinute, time.Minute) { return nil, ErrRateLimited } return b.svc.Probe(ctx, url) } // ErrRateLimited is returned when a user sends links too fast. var ErrRateLimited = errors.New("bot: rate limited") // AppDownload starts a download from the Mini App. The status message and // the file go to the user's private chat. func (b *Bot) AppDownload(ctx context.Context, user *db.User, lang, url string, profile media.Profile) error { who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} if err := b.svc.Gate(ctx, who); err != nil { return err } if !b.appStartAllowed(user.ID) { return ErrRateLimited } info, err := b.svc.Probe(ctx, url) if err != nil { return err } return b.startInChat(ctx, user, lang, url, info, profile) } // appStartAllowed bounds how fast the app may start downloads for a user. // It is its own budget, twice the one for links: a lookup followed by a // start is one download, and both are HTTP calls anyone can script. func (b *Bot) appStartAllowed(userID int64) bool { return b.rate.allow("as:"+itoa(userID), 2*b.cfg.Rate.UserPerMinute, time.Minute) } // startInChat creates a request for a known link and starts it, with a // fresh status message in the user's private chat. func (b *Bot) startInChat(ctx context.Context, user *db.User, lang, url string, info *service.CardInfo, profile media.Profile) error { who := service.Who{UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate} // Refuse before a message is sent, so a refusal leaves nothing behind. if err := b.svc.Preview(ctx, who, url, info, profile); err != nil { return err } msg, err := b.send(ctx, user.ID, 0, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil) if err != nil { return err } req := &db.Request{ ID: ids.New(), UserID: user.ID, ChatID: user.ID, ChatType: telego.ChatTypePrivate, URL: url, CardMessageID: int64(msg.MessageID), Status: db.RequestReady, Info: info.JSON(), Lang: lang, } if err := b.store.InsertRequest(ctx, req); err != nil { return err } if err := b.startFromRequest(ctx, req, info, profile, nil); err != nil { _ = b.edit(ctx, user.ID, req.CardMessageID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) return err } return nil } // AppResend sends a past download again. It is a new download with the // usual limits; the cache usually makes it instant. func (b *Bot) AppResend(ctx context.Context, user *db.User, lang, deliveryID string) error { old, err := b.store.GetDelivery(ctx, deliveryID) if err != nil || old.UserID != user.ID || old.Status != db.DeliverySent { return db.ErrNotFound } job, err := b.store.GetJob(ctx, old.JobID) if err != nil { return db.ErrNotFound } orig, err := b.store.GetRequest(ctx, old.RequestID) if err != nil { return db.ErrNotFound } info, ierr := service.ParseCardInfo(orig.Info) profile, perr := media.Parse(job.Profile) if ierr != nil || perr != nil { return db.ErrNotFound } info.Fresh = false if !b.appStartAllowed(user.ID) { return ErrRateLimited } return b.startInChat(ctx, user, lang, orig.URL, info, profile) } // AppCancel cancels one of the user's downloads. func (b *Bot) AppCancel(ctx context.Context, userID int64, deliveryID string) error { err := b.cancelDelivery(ctx, deliveryID, userID) if errors.Is(err, sched.ErrNotOwner) { return db.ErrNotFound } return err } // AppSkip moves a waiting download to the priority lane. With enough // credits it is done at once. Otherwise an invoice is created and // returned, and the promotion happens when it is paid. func (b *Bot) AppSkip(ctx context.Context, user *db.User, lang, deliveryID string) (done bool, purchase *db.Purchase, err error) { d, err := b.store.GetDelivery(ctx, deliveryID) if err != nil || d.UserID != user.ID { return false, nil, db.ErrNotFound } job, err := b.store.GetJob(ctx, d.JobID) if err != nil || job.Status != db.JobQueued || job.Lane != db.LaneFree { return false, nil, sched.ErrTooLate } if b.skipWithCredits(ctx, actor{user: user, lang: lang}, d, job, b.cfg.Prices.SkipQueue) { b.refreshStatus(ctx, job.ID) return true, nil, nil } p, err := b.AppPurchase(ctx, user, lang, 0, billing.ProductSkipQueue, 0, d.ID) return false, p, err } // AppPurchase creates an invoice from the Mini App. groupID 0 targets the // user's own wallet, anything else that group's wallet. func (b *Bot) AppPurchase(ctx context.Context, user *db.User, lang string, groupID int64, product string, amount int64, deliveryID string) (*db.Purchase, error) { if !billing.ValidProduct(product) { return nil, billing.ErrBadProduct } // Every invoice is a call to the payment backend. A person needs a // few per minute at most. if !b.rate.allow("ap:"+itoa(user.ID), 10, time.Minute) { return nil, ErrRateLimited } ownerType, ownerID := db.OwnerUser, user.ID if groupID != 0 { g, err := b.store.GetGroup(ctx, groupID) if err != nil || !g.Present() { return nil, db.ErrNotFound } ownerType, ownerID = db.OwnerGroup, groupID } w, err := b.bill.Wallet(ctx, ownerType, ownerID) if err != nil { return nil, err } return b.bill.CreatePurchase(ctx, billing.NewPurchase{ UserID: user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, DeliveryID: deliveryID, Memo: b.tr.T(lang, "invoice.memo", map[string]any{"Title": b.productTitle(lang, product)}), }) } // AppStarsPurchase creates a Stars purchase from the Mini App and an // invoice link for WebApp.openInvoice. Payments made inside the Mini App // are the ones Telegram's affiliate program counts. func (b *Bot) AppStarsPurchase(ctx context.Context, user *db.User, lang string, groupID int64, product string, amount int64) (*db.Purchase, string, error) { if !billing.ValidProduct(product) { return nil, "", billing.ErrBadProduct } if !b.rate.allow("ap:"+itoa(user.ID), 10, time.Minute) { return nil, "", ErrRateLimited } ownerType, ownerID := db.OwnerUser, user.ID if groupID != 0 { g, err := b.store.GetGroup(ctx, groupID) if err != nil || !g.Present() { return nil, "", db.ErrNotFound } ownerType, ownerID = db.OwnerGroup, groupID } w, err := b.bill.Wallet(ctx, ownerType, ownerID) if err != nil { return nil, "", err } p, err := b.bill.CreateStarsPurchase(ctx, billing.NewPurchase{ UserID: user.ID, WalletID: w.ID, Product: product, Amount: amount, Lang: lang, }) if err != nil { return nil, "", err } link, err := b.StarsInvoiceLink(ctx, p) if err != nil { _, _ = b.bill.Cancel(context.WithoutCancel(ctx), p.ID, user.ID) return nil, "", err } return p, link, nil } // Explain turns an error from the operations above into a stable code and // a message in the user's language. func (b *Bot) Explain(lang string, err error) (code, message string, upgradable bool) { var le *service.LimitError var ye *ytdlp.Error switch { case errors.As(err, &le): return "limit." + le.Code, b.limitText(lang, le), le.Upgradable case errors.Is(err, service.ErrPlaylist): return "error.playlist", b.tr.T(lang, "error.playlist", nil), false case errors.As(err, &ye): return "error." + string(ye.Code), b.tr.T(lang, "error."+string(ye.Code), nil), false case errors.Is(err, ErrRateLimited): return "rate_limited", b.tr.T(lang, "notice.rate_limited", nil), false case errors.Is(err, sched.ErrTooLate): return "too_late", b.tr.T(lang, "notice.skip_too_late", nil), false case errors.Is(err, db.ErrNotFound): return "not_found", b.tr.T(lang, "notice.expired", nil), false case errors.Is(err, billing.ErrDisabled): return "payments_off", b.tr.T(lang, "buy.unavailable", nil), false case errors.Is(err, billing.ErrLightningDown): return "payments_down", b.tr.T(lang, "buy.backend_down_short", nil), false case errors.Is(err, billing.ErrBadAmount), errors.Is(err, billing.ErrBadProduct), errors.Is(err, billing.ErrNotForStars), errors.Is(err, billing.ErrStarsOff): return "bad_amount", b.tr.T(lang, "buy.bad_amount", nil), false } b.log.Error("mini app operation failed", "err", err) return "internal", b.tr.T(lang, "error.internal", nil), false } func itoa(n int64) string { return strconv.FormatInt(n, 10) }