package bot import ( "context" "errors" "html" "strings" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/db" "github.com/noderunners/dlbot/internal/i18n" "github.com/noderunners/dlbot/internal/ids" "github.com/noderunners/dlbot/internal/links" "github.com/noderunners/dlbot/internal/media" "github.com/noderunners/dlbot/internal/service" "github.com/noderunners/dlbot/internal/ytdlp" ) func secondsDuration(s int64) time.Duration { return time.Duration(s) * time.Second } // linkRequest is one link a user asked about. type linkRequest struct { chatID int64 chatType string // sourceID is the message that holds the link. The card and the file // are sent as replies to it. sourceID int64 act actor url string // preset skips the card and starts this profile right away. preset media.Profile } // startLink runs the link flow in the background so a slow metadata lookup // never blocks other updates of the chat. func (b *Bot) startLink(ctx context.Context, lr linkRequest) { b.goBG("link", func() { b.linkFlow(ctx, lr) }) } func (b *Bot) linkFlow(ctx context.Context, lr linkRequest) { lang := lr.act.lang log := b.log.With("user_id", lr.act.user.ID, "chat_id", lr.chatID, "url", links.Redact(lr.url)) placeholder, err := b.send(ctx, lr.chatID, lr.sourceID, b.tr.HTML(lang, "card.looking", nil), nil) if err != nil { return } phID := int64(placeholder.MessageID) info, err := b.svc.Probe(ctx, lr.url) if err != nil { if ctx.Err() == nil { _ = b.edit(ctx, lr.chatID, phID, false, b.probeErrorText(lang, err), nil) } return } req := &db.Request{ ID: ids.New(), UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType, SourceMessageID: lr.sourceID, CardMessageID: phID, URL: lr.url, Status: db.RequestReady, Info: info.JSON(), Lang: lang, } if lr.preset != "" { req.Status = db.RequestChosen } if err := b.store.InsertRequest(ctx, req); err != nil { log.Error("insert request", "err", err) _ = b.edit(ctx, lr.chatID, phID, false, b.tr.HTML(lang, "error.internal", nil), nil) return } log = log.With("request_id", req.ID) if lr.preset != "" { job, _, err := b.svc.Start(ctx, service.StartParams{ Request: req, Info: info, Profile: lr.preset, StatusMessageID: phID, ReplyToMessageID: lr.sourceID, }) if err != nil { _ = b.edit(ctx, lr.chatID, phID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil) return } b.refreshStatus(ctx, job.ID) return } text := b.cardText(lang, info, true) kb := b.cardKeyboard(lang, req.ID, info) if info.Thumbnail != "" { msg, err := b.api.SendPhoto(ctx, &telego.SendPhotoParams{ ChatID: chatID(lr.chatID), Photo: telego.InputFile{URL: info.Thumbnail}, Caption: clip(text, 1024), ParseMode: telego.ModeHTML, ReplyParameters: replyParams(lr.sourceID), ReplyMarkup: kb, }) if err == nil { if err := b.store.SetRequestCard(ctx, req.ID, int64(msg.MessageID), true); err != nil { log.Error("save card", "err", err) } b.deleteMessage(ctx, lr.chatID, phID) return } // Telegram could not fetch the thumbnail. The text card still works. log.Debug("photo card failed, using text card", "err", err) } _ = b.edit(ctx, lr.chatID, phID, false, text, kb) } // cardText renders the card: title, a line of facts and, for cards with // buttons, the prompt to pick a format. func (b *Bot) cardText(lang string, info *service.CardInfo, withPrompt bool) string { var facts []string if info.Uploader != "" { facts = append(facts, html.EscapeString(shorten(info.Uploader, 40))) } if info.Duration > 0 { facts = append(facts, i18n.Clock(info.Duration)) } if info.Site != "" { facts = append(facts, html.EscapeString(info.Site)) } var sb strings.Builder sb.WriteString(titleLine(info.Title)) if len(facts) > 0 { sb.WriteString("\n") sb.WriteString(strings.Join(facts, " ยท ")) } if withPrompt { sb.WriteString("\n\n") sb.WriteString(b.tr.HTML(lang, "card.pick", nil)) } return sb.String() } // probeErrorText maps a lookup failure to a friendly message. Raw yt-dlp // output never reaches the user. func (b *Bot) probeErrorText(lang string, err error) string { if errors.Is(err, service.ErrPlaylist) { return b.tr.HTML(lang, "error.playlist", nil) } return b.tr.HTML(lang, "error."+string(ytdlp.CodeOf(err)), nil) } // startErrorText maps a refused or failed start to plain text. func (b *Bot) startErrorText(lang string, err error) string { var le *service.LimitError if errors.As(err, &le) { return b.limitText(lang, le) } b.log.Error("start download", "err", err) return b.tr.T(lang, "error.internal", nil) } // cbDownload handles a format button on a card. func (b *Bot) cbDownload(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) { req, err := b.store.GetRequest(ctx, requestID) if err != nil { b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) return } if req.UserID != act.user.ID { b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) return } profile, perr := media.Parse(profileArg) info, ierr := service.ParseCardInfo(req.Info) if perr != nil || ierr != nil { b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) return } // Taking the request first makes a double tap start only one job. took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen) if err != nil { b.log.Error("take request", "request_id", req.ID, "err", err) b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true) return } if !took { b.answer(ctx, q, b.tr.T(act.lang, "notice.already_chosen", nil), false) return } cardID, cardIsPhoto := cardMessage(q, req) job, _, err := b.svc.Start(ctx, service.StartParams{ Request: req, Info: info, Profile: profile, StatusMessageID: cardID, StatusIsPhoto: cardIsPhoto, ReplyToMessageID: req.SourceMessageID, }) if err != nil { // Give the card back so another format can be picked. if _, rerr := b.store.TransitionRequest(ctx, req.ID, db.RequestChosen, db.RequestReady); rerr != nil { b.log.Error("release request", "request_id", req.ID, "err", rerr) } b.answer(ctx, q, b.startErrorText(act.lang, err), true) return } b.answer(ctx, q, "", false) b.refreshStatus(ctx, job.ID) } // cbCancelCard handles the Cancel button on a card that has no job yet. func (b *Bot) cbCancelCard(ctx context.Context, q *telego.CallbackQuery, act actor, requestID string) { req, err := b.store.GetRequest(ctx, requestID) if err != nil { b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false) return } if req.UserID != act.user.ID { b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false) return } took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestCancelled) if err != nil || !took { b.answer(ctx, q, b.tr.T(act.lang, "notice.too_late", nil), false) return } b.answer(ctx, q, b.tr.T(act.lang, "notice.cancelled", nil), false) cardID, cardIsPhoto := cardMessage(q, req) if err := b.api.DeleteMessage(ctx, &telego.DeleteMessageParams{ ChatID: chatID(req.ChatID), MessageID: int(cardID), }); err != nil { _ = b.edit(ctx, req.ChatID, cardID, cardIsPhoto, b.tr.HTML(req.Lang, "card.cancelled", nil), nil) } } // cardMessage identifies the message a card button was pressed on. The // callback itself is the source of truth: a press can arrive before the // card's message ID has been saved with the request. func cardMessage(q *telego.CallbackQuery, req *db.Request) (id int64, isPhoto bool) { if q.Message == nil || q.Message.GetMessageID() == 0 { return req.CardMessageID, req.CardIsPhoto } id = int64(q.Message.GetMessageID()) if m := q.Message.Message(); m != nil && q.Message.IsAccessible() { return id, len(m.Photo) > 0 } if id == req.CardMessageID { return id, req.CardIsPhoto } return id, false }