package bot import ( "context" "errors" "strings" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/groups" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/links" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/sched" "github.com/noderunners/dlbot/internal/service" ) func (b *Bot) handleMessage(ctx context.Context, m *telego.Message) { act, ok := actorFrom(ctx) if !ok || act.user.Banned { return } private := isPrivate(m.Chat.Type) inGroup := groups.IsGroup(m.Chat.Type) gset := act.group if inGroup && gset == nil { return } cmd, forUs, isCmd := b.parseCommand(m) if isCmd { if !forUs { return // addressed to another bot in the group } if inGroup { b.noteGroup(ctx, m.Chat, act.user.ID) // A group that switched the bot off only hears from it when an // admin opens the settings to switch it back on. if !gset.Enabled && cmd != "settings" { return } } if private { b.syncMenuButton(ctx, act) } if b.ownerCommand(ctx, m, act, cmd) { return } b.runCommand(ctx, m, act, cmd, gset) return } urls := messageLinks(m) if inGroup { // Without a command the bot only acts when the admins turned on // link detection. It then needs to see ordinary messages, which // means group privacy mode off or the bot being an admin. if !gset.Enabled || !gset.AutoDetect || len(urls) == 0 { return } b.noteGroup(ctx, m.Chat, act.user.ID) b.startLink(ctx, linkRequest{ chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: urls[0], preset: presetFor(act, gset), }) return } if !private { return } b.syncMenuButton(ctx, act) if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "hint.send_link", nil), nil) return } if max := b.cfg.MultiLinkMax; max > 0 && len(urls) > max { urls = urls[:max] } for _, u := range urls { b.startLink(ctx, linkRequest{ chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: int64(m.MessageID), act: act, url: u, preset: presetFor(act, nil), checkRecent: true, }) } } // Personal quality settings besides a profile. Stored in users.default_quality. const ( // qualityUnset is a user who never chose. Their first link shows the // card once, and their default becomes qualityFit. qualityUnset = "" // qualityAsk shows the card for every link. qualityAsk = "ask" // qualityFit picks the best quality whose estimated size fits the // user's size limit. qualityFit = "fit" ) // presetFor returns the format to start without showing the card: the // group's default quality in a group, the user's own in a private chat. // An empty result means the card is shown. func presetFor(act actor, gset *db.GroupSettings) media.Profile { q := act.user.Quality if gset != nil { q = gset.Quality } if q == qualityFit { return presetFit } if p, err := media.Parse(q); err == nil { return p } return "" } // presetFit stands for "best that fits my limit" until the link has been // looked up and the real profile can be picked. const presetFit media.Profile = "fit" // runCommand dispatches the commands everyone can use. func (b *Bot) runCommand(ctx context.Context, m *telego.Message, act actor, cmd string, gset *db.GroupSettings) { // Commands that carry a link. In a group their message can be removed // afterwards when the admins asked for a tidy chat. tidy := func() { if gset != nil && gset.DeleteCmds { b.deleteMessage(ctx, m.Chat.ID, int64(m.MessageID)) } } switch cmd { case "start": b.cmdStart(ctx, m, act) case "help": b.cmdHelp(ctx, m, act) case "dl": b.cmdDownload(ctx, m, act, presetFor(act, gset)) tidy() case "audio": b.cmdDownload(ctx, m, act, media.MP3) tidy() case "thumb": b.cmdDownload(ctx, m, act, media.Thumb) tidy() case "fresh": b.cmdLink(ctx, m, act, linkRequest{fresh: true}) tidy() case "subs": b.cmdLink(ctx, m, act, linkRequest{subs: true}) tidy() case "info": b.cmdInfo(ctx, m, act) case "history": b.cmdHistory(ctx, m, act) case "queue": if b.isOwner(m) && strings.TrimSpace(commandArgs(m)) == "all" { b.cmdQueueAll(ctx, m, act) return } b.cmdQueue(ctx, m, act) case "cancel": b.cmdCancel(ctx, m, act) case "quality": b.cmdQuality(ctx, m, act) case "language": b.cmdLanguage(ctx, m, act) case "app": b.cmdApp(ctx, m, act) case "buy": b.cmdBuy(ctx, m, act) case "account": b.cmdAccount(ctx, m, act) case "limits": b.cmdLimits(ctx, m, act) case "credits": b.cmdCredits(ctx, m, act) case "donate": b.cmdDonate(ctx, m, act) case "redeem": b.cmdRedeem(ctx, m, act, commandArgs(m)) case "referral": b.cmdReferral(ctx, m, act) case "privacy", "terms", "support": if b.privateOnly(ctx, m, act) { b.cmdStatic(ctx, m, act, "static."+cmd) } case "settings": if isPrivate(m.Chat.Type) { b.cmdPersonalSettings(ctx, m.Chat.ID, act) return } b.cmdSettings(ctx, m, act) case "grouplang": b.cmdGroupLang(ctx, m, act) case "autodetect": b.cmdAutoDetect(ctx, m, act) case "allow": b.cmdSiteList(ctx, m, act, true) case "block": b.cmdSiteList(ctx, m, act, false) case "spending": b.cmdSpending(ctx, m, act) case "groupwallet": b.cmdGroupWallet(ctx, m, act, false) case "grouppass": b.cmdGroupWallet(ctx, m, act, true) case "groupstats": b.cmdGroupStats(ctx, m, act) default: if isPrivate(m.Chat.Type) { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "cmd.unknown", nil), nil) } } } // cmdApp points to the Mini App. In a private chat the button opens it in // place; in a group it has to be a plain link, because web app buttons do // not work there. func (b *Bot) cmdApp(ctx context.Context, m *telego.Message, act actor) { if !b.cfg.MiniAppEnabled() { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.unavailable", nil), nil) return } label := b.tr.T(act.lang, "btn.open_app", nil) btn := urlButton(label, "https://t.me/"+b.username+"?startapp") if isPrivate(m.Chat.Type) { btn = telego.InlineKeyboardButton{Text: label, WebApp: &telego.WebAppInfo{URL: b.cfg.PublicURL + "/app/"}} } _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "app.open", nil), keyboard([]telego.InlineKeyboardButton{btn})) } // commandArgs returns the text after the command of a message. func commandArgs(m *telego.Message) string { for _, e := range m.Entities { if e.Type == telego.EntityTypeBotCommand && e.Offset == 0 && e.Length <= len(m.Text) { return strings.TrimSpace(m.Text[e.Length:]) } } return "" } // parseCommand finds a bot command at the start of the message. forUs is // false when the command names a different bot (/dl@otherbot). func (b *Bot) parseCommand(m *telego.Message) (cmd string, forUs, isCmd bool) { for _, e := range m.Entities { if e.Type != telego.EntityTypeBotCommand || e.Offset != 0 { continue } // Commands are ASCII, so the UTF-16 length is also the byte length. if e.Length > len(m.Text) || e.Length < 2 { return "", false, false } full := m.Text[1:e.Length] name, target, hasTarget := strings.Cut(full, "@") if hasTarget && !strings.EqualFold(target, b.username) { return "", false, true } return strings.ToLower(name), true, true } return "", false, false } func toLinkEntities(ents []telego.MessageEntity) []links.Entity { out := make([]links.Entity, 0, len(ents)) for _, e := range ents { out = append(out, links.Entity{Type: e.Type, Offset: e.Offset, Length: e.Length, URL: e.URL}) } return out } // messageLinks extracts links from the text or the caption of a message. func messageLinks(m *telego.Message) []string { if m == nil { return nil } if urls := links.Extract(m.Text, toLinkEntities(m.Entities)); len(urls) > 0 { return urls } return links.Extract(m.Caption, toLinkEntities(m.CaptionEntities)) } func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) { if !isPrivate(m.Chat.Type) { _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.group", nil), nil) return } // Deep links arrive as "/start ". payload := commandArgs(m) switch { case strings.HasPrefix(payload, "buy_"): b.startBuyLink(ctx, m, act, strings.TrimPrefix(payload, "buy_")) return case strings.HasPrefix(payload, "skip_"): b.startSkipLink(ctx, m, act, strings.TrimPrefix(payload, "skip_")) return case strings.HasPrefix(payload, "gw_"): b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gw_"), false) return case strings.HasPrefix(payload, "gs_"): b.startGroupLink(ctx, m, act, strings.TrimPrefix(payload, "gs_"), true) return case payload == "buy": b.showBuy(ctx, m.Chat.ID, act) return default: b.applyReferral(ctx, act, payload) } // Somebody new picks a language under the welcome. It starts in the // language of their Telegram app, which is usually right. var kb *telego.InlineKeyboardMarkup if act.user.IsNew { kb = b.languageKeyboard(act, func(l string) string { return cbData(cbWelcomeLang, l) }, false) } _, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), kb) } // cmdDownload handles /dl, /audio and /thumb. The link comes from the // command itself or from the message the command replies to. The bot // answers under the message that holds the link. func (b *Bot) cmdDownload(ctx context.Context, m *telego.Message, act actor, preset media.Profile) { urls := messageLinks(m) source := int64(m.MessageID) if len(urls) == 0 && m.ReplyToMessage != nil { urls = messageLinks(m.ReplyToMessage) source = int64(m.ReplyToMessage.MessageID) } if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil) return } b.startLink(ctx, linkRequest{ chatID: m.Chat.ID, chatType: m.Chat.Type, sourceID: source, act: act, url: urls[0], preset: preset, }) } // cmdLink handles the commands that take a link and differ only in how // the link flow runs: /fresh and /subs. func (b *Bot) cmdLink(ctx context.Context, m *telego.Message, act actor, lr linkRequest) { urls := messageLinks(m) source := int64(m.MessageID) if len(urls) == 0 && m.ReplyToMessage != nil { urls = messageLinks(m.ReplyToMessage) source = int64(m.ReplyToMessage.MessageID) } if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "dl.usage", nil), nil) return } lr.chatID, lr.chatType, lr.sourceID, lr.act, lr.url = m.Chat.ID, m.Chat.Type, source, act, urls[0] b.startLink(ctx, lr) } func (b *Bot) cmdInfo(ctx context.Context, m *telego.Message, act actor) { urls := messageLinks(m) if len(urls) == 0 && m.ReplyToMessage != nil { urls = messageLinks(m.ReplyToMessage) } if len(urls) == 0 { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "info.usage", nil), nil) return } url := urls[0] b.goBG("info", func() { b.chatAction(ctx, m.Chat.ID, telego.ChatActionTyping) info, err := b.svc.Probe(ctx, url) if err != nil { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.probeErrorText(act.lang, err), nil) return } var sb strings.Builder sb.WriteString(b.cardText(act.lang, info, false)) sb.WriteString("\n") profiles := append([]media.Profile{}, media.VideoProfiles...) if info.HasAudio { profiles = append(profiles, media.MP3, media.M4A) } for _, p := range profiles { if h := p.Height(); h > 0 && info.MaxHeight > 0 && info.MaxHeight < h { continue } size := b.tr.T(act.lang, "info.size_unknown", nil) if n := info.Sizes[string(p)]; n > 0 { size = b.tr.Size(act.lang, n) } sb.WriteString("\n") sb.WriteString(b.tr.HTML(act.lang, "info.line", i18n.Args{"Label": b.profileLabel(act.lang, p), "Size": size})) } _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil) }) } func (b *Bot) cmdQueue(ctx context.Context, m *telego.Message, act actor) { dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID) if err != nil { b.log.Error("list deliveries", "err", err) return } if len(dels) == 0 { _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "queue.empty", nil), nil) return } var sb strings.Builder sb.WriteString(b.tr.HTML(act.lang, "queue.header", i18n.Args{"Count": len(dels)})) for _, d := range dels { job, err := b.store.GetJob(ctx, d.JobID) if err != nil { continue } text, _, _ := b.renderStatus(ctx, d, job) sb.WriteString("\n\n") sb.WriteString(text) } _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), nil) } func (b *Bot) cmdCancel(ctx context.Context, m *telego.Message, act actor) { n := 0 // Playlist items that have not started go first. Cancelling a running // download frees a slot, and the next waiting item would take it. b.statusMu.Lock() b.cancelledAt[act.user.ID] = time.Now() b.statusMu.Unlock() if waiting, err := b.store.CancelWaitingRequests(ctx, act.user.ID); err == nil { n += int(waiting) } dels, err := b.store.ActiveDeliveriesForUser(ctx, act.user.ID) if err != nil { b.log.Error("list deliveries", "err", err) return } for _, d := range dels { if b.cancelDelivery(ctx, d.ID, act.user.ID) == nil { n++ } } key := "cancel.done" if n == 0 { key = "cancel.nothing" } _, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, key, i18n.Args{"Count": n}), nil) } // cancelDelivery withdraws one delivery and updates its status message. func (b *Bot) cancelDelivery(ctx context.Context, deliveryID string, userID int64) error { d, err := b.sched.CancelDelivery(ctx, deliveryID, userID) if err != nil { return err } note := b.release(ctx, d) job, err := b.store.GetJob(ctx, d.JobID) if err != nil { return nil } b.finalStatus(ctx, d, titleLine(job.Title)+"\n"+b.tr.HTML(d.Lang, "status.cancelled", nil)+note) return nil } // release gives back what an undelivered download took and returns a line // to append to the status when sats were refunded. func (b *Bot) release(ctx context.Context, d *db.Delivery) string { bg := context.WithoutCancel(ctx) refunded, err := b.svc.Release(bg, d.ID) if err != nil { b.log.Error("release delivery", "delivery_id", d.ID, "err", err) return "" } if refunded <= 0 { // Another path may have released it a moment ago. refunded = b.svc.Refunded(bg, d.ID) } if refunded <= 0 { return "" } return "\n" + b.tr.HTML(d.Lang, "status.refunded", i18n.Args{"Amount": b.tr.Sats(d.Lang, refunded)}) } func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) { act, ok := actorFrom(ctx) if !ok { return } if act.user.Banned { b.answer(ctx, q, "", false) return } action, id, arg := parseCallback(q.Data) switch action { case cbGroupSetting: b.cbSetting(ctx, q, act, id) case cbGroupBuy: b.cbGroupBuyProduct(ctx, q, act, id, arg) case cbQuality: b.cbSetQuality(ctx, q, act, id) case cbLanguage: b.cbSetLanguage(ctx, q, act, id) case cbWelcomeLang: b.cbWelcomeLanguage(ctx, q, act, id) case cbBroadcast: b.cbBroadcastSend(ctx, q, act, id) case cbDownload: b.cbDownload(ctx, q, act, id, arg) case cbCancelCard: b.cbCancelCard(ctx, q, act, id) case cbPlaylist: b.cbPlaylistStart(ctx, q, act, id, arg) case cbResend: b.cbResendFile(ctx, q, act, id) case cbHistory, cbHistoryView, cbHistoryDel, cbHistoryClear, cbHistoryWipe: b.cbHistoryAction(ctx, q, act, action, id, arg) case cbHelp: b.cbHelpSection(ctx, q, act, id) case cbFollowAudio: b.cbFollow(ctx, q, act, id, media.MP3) case cbFollowThumb: b.cbFollow(ctx, q, act, id, media.Thumb) case cbFollowQuality: b.cbOtherQuality(ctx, q, act, id) case cbFollowDelete: b.cbDeleteResult(ctx, q, act, id) case cbRetry: b.cbRetryDownload(ctx, q, act, id, arg) case cbRetryLookup: b.cbRetryLookup(ctx, q, act, id) case cbUpgrade: b.cbShowUpgrade(ctx, q, act) case cbReferralQR: b.cbSendReferralQR(ctx, q, act) case cbPersonal: b.cbPersonalSetting(ctx, q, act, id, arg) case cbSkipQueue: b.cbSkip(ctx, q, act, id) case cbBuy: b.cbBuyProduct(ctx, q, act, id, arg) case cbOfferBuy: b.cbOffer(ctx, q, act, id, arg) case cbPayCheck: b.cbPayCheck(ctx, q, act, id) case cbPayCancel: b.cbPayCancel(ctx, q, act, id) case cbCancelJob: err := b.cancelDelivery(ctx, id, act.user.ID) switch { case err == nil: b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false) case errors.Is(err, sched.ErrNotOwner): b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) case errors.Is(err, sched.ErrTooLate), errors.Is(err, db.ErrNotFound): b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false) default: b.log.Error("cancel delivery", "delivery_id", id, "err", err) b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) } default: b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) } } // limitText renders a limit refusal for the user as plain text. func (b *Bot) limitText(lang string, le *service.LimitError) string { l := le.Decision.Limits count := l.ActiveJobs if le.Code == service.LimitDailyDownloads { count = l.DailyDownloads } return b.tr.T(lang, "limit."+le.Code, i18n.Args{ "MaxSize": b.tr.Size(lang, l.MaxSize), "MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)), "MaxVolume": b.tr.Size(lang, l.DailyBytes), "Count": count, }) }