Phase 2: command screens

- /help: a short introduction with the user's default format, how to be
  asked every time and the limits on one line, plus buttons Commands,
  Account, Groups, Open app and Upgrade that switch the same message to
  a section. Group commands are hidden in private chats; "Add me to a
  group" takes their place.
- /quality: Ask every time, Best that fits my limit, Best, 1080p, 720p,
  480p and Audio only, with the active one checked. Free users see which
  qualities may go over their limit.
- /history: pages of five compact buttons (site, title, format, when),
  a view per download with Send again, Thumbnail, Remove from history,
  and Clear history with a confirmation. Thumbnails are grouped under
  their video. Migration 00007 stores extractor, title, uploader and
  profile on deliveries and adds a hidden flag.
- docs/SCREENS.md shows every screen in en, es and nl, generated by the
  language test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 20:46:13 +00:00
co-authored by Claude Opus 5.5
parent 6843053582
commit 123cede7f3
21 changed files with 3758 additions and 183 deletions
+5 -2
View File
@@ -219,7 +219,7 @@ const fileMethods = "sendVideo|sendAudio|sendDocument|sendPhoto"
func isResult(chat int64) func(fakeserver.Call) bool {
return func(c fakeserver.Call) bool {
_, ok := c.Button("fx:")
return ok && (chat == 0 || c.ChatID() == chat)
return ok && !c.Failed && (chat == 0 || c.ChatID() == chat)
}
}
@@ -843,7 +843,10 @@ func TestStartHelpAndHints(t *testing.T) {
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/help")
h.wait(seq, "sendMessage", textHas("Up to 50 MB and 10 minutes per download"))
help := h.wait(seq, "sendMessage", textHas("Your limits: 50 MB and 10 minutes per download, 5 downloads a day."))
if !strings.Contains(help.Text(), "Your default format: <b>Best that fits my limit</b>") {
t.Fatalf("help = %q", help.Text())
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "hello bot")
+5 -3
View File
@@ -780,15 +780,17 @@ func TestHistoryResendsFromTheCache(t *testing.T) {
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/history")
list := h.wait(seq, "sendMessage", textHas("Your past downloads"))
if !strings.Contains(list.Text(), "1. Test Video · Best") || labels(list) != "1. Test Video" {
if labels(list) != "example.com · Test Video · Best · today | Clear history" {
t.Fatalf("history = %q buttons=%q", list.Text(), labels(list))
}
seq = h.press(alice, alice, list, "hv:")
item := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == list.MessageID })
// Bob cannot resend from Alice's history.
seq = h.press(alice, bob, list, "rs:")
seq = h.press(alice, bob, item, "rs:")
h.wait(seq, "answerCallbackQuery", nil)
h.never(seq, "sendVideo", nil)
seq = h.press(alice, alice, list, "rs:")
seq = h.press(alice, alice, item, "rs:")
again := h.wait(seq, "sendVideo", nil)
if uploaded(again, "video") || len(h.fake.Downloads()) != 1 {
t.Fatal("a resend should come from the cache")
+91 -1
View File
@@ -2,8 +2,10 @@ package app_test
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"regexp"
"sort"
"strings"
@@ -198,6 +200,24 @@ func tour(t *testing.T, h *moneyHarness, user int64, lang string) {
seq = send(cmd)
h.wait(seq, "sendMessage", inChat)
}
// Help sections and the history screens.
seq = send("/help")
help := h.wait(seq, "sendMessage", inChat)
for _, key := range []string{"hp:cmds", "hp:acct", "hp:groups", "hp:home"} {
seq = h.srv.Seq()
h.srv.PushCallback(user, user, help.MessageID, key)
h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == help.MessageID })
}
seq = send("/history")
hist := h.wait(seq, "sendMessage", inChat)
editedHist := func(seq int) fakeserver.Call {
return h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == hist.MessageID })
}
item := editedHist(pressOn(hist, "hv:"))
back := editedHist(pressOn(item, "hd:"))
ask := editedHist(pressOn(back, "hc:"))
editedHist(pressOn(ask, "hy"))
// An invoice.
seq = send("/buy")
buy := h.wait(seq, "sendMessage", inChat)
@@ -224,15 +244,34 @@ func tourFake() *ytdlptest.Fake {
}
}
// TestEveryScreenInSpanishAndDutch walks every screen in Spanish and in
// Dutch. With DLBOT_SCREENS=<file> it also walks them in English and
// writes what each screen shows, in all three languages, to that file for
// review: DLBOT_SCREENS=$PWD/docs/SCREENS.md go test ./internal/app -run TestEveryScreen
func TestEveryScreenInSpanishAndDutch(t *testing.T) {
foreign := englishOnly(t)
for _, lang := range []string{"es", "nl"} {
langs := []string{"es", "nl"}
out := os.Getenv("DLBOT_SCREENS")
if out != "" {
langs = []string{"en", "es", "nl"}
}
var dump strings.Builder
dump.WriteString("# Screens\n\nWhat the bot shows on every screen of a scripted walk through it, in each\n" +
"language, in order. Generated by TestEveryScreenInSpanishAndDutch with\n" +
"DLBOT_SCREENS set; do not edit by hand. Buttons are in brackets.\n")
for _, lang := range langs {
t.Run(lang, func(t *testing.T) {
// A missing message or a fallback to English is logged as a bug,
// which fails the test (see guardHandler).
h := startApp(t, tourFake(), nil)
const user = int64(501)
tour(t, h, user, lang)
if out != "" {
writeScreens(&dump, h.harness, user, lang)
}
if lang == "en" {
return
}
var leaks []string
for text, where := range shownTo(h.harness, user) {
@@ -249,6 +288,57 @@ func TestEveryScreenInSpanishAndDutch(t *testing.T) {
}
})
}
if out != "" {
if err := os.WriteFile(out, []byte(dump.String()), 0o644); err != nil {
t.Fatal(err)
}
}
}
// writeScreens appends what a chat showed, call by call, to a review file.
func writeScreens(sb *strings.Builder, h *harness, chat int64, lang string) {
fmt.Fprintf(sb, "\n## %s\n", lang)
last := ""
for _, c := range h.srv.Calls("") {
if c.Failed {
continue
}
text := c.Text()
switch {
case c.Method == "answerCallbackQuery":
text = c.Params["text"]
if text == "" {
continue
}
case c.ChatID() != chat || text == "" || strings.HasPrefix(c.Method, "get") || strings.HasPrefix(c.Method, "set"):
continue
}
// One line per keyboard row, as Telegram shows them.
var markup struct {
Rows [][]struct {
Text string `json:"text"`
} `json:"inline_keyboard"`
}
_ = json.Unmarshal([]byte(c.Params["reply_markup"]), &markup)
var btns []string
for _, row := range markup.Rows {
var line []string
for _, b := range row {
line = append(line, "["+b.Text+"]")
}
btns = append(btns, strings.Join(line, " "))
}
entry := text + "\n" + strings.Join(btns, "\n")
if entry == last {
continue
}
last = entry
fmt.Fprintf(sb, "\n%s\n\n```\n%s\n", c.Method, text)
if len(btns) > 0 {
fmt.Fprintf(sb, "%s\n", strings.Join(btns, "\n"))
}
sb.WriteString("```\n")
}
}
// --- language resolution -----------------------------------------------------
+2 -2
View File
@@ -457,9 +457,9 @@ func TestUserDefaultQualityAndLanguageAndStaticPages(t *testing.T) {
h := startMoney(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/quality")
menu := h.wait(seq, "sendMessage", textHas("Pick your default format"))
menu := h.wait(seq, "sendMessage", textHas("Your default format"))
// Somebody who never chose gets "best that fits my limit".
if labels(menu) != "Ask every time | ✓ Best that fits my limit | Best | 1080p | 720p | 480p | Audio only (MP3)" {
if labels(menu) != "Ask every time | ✓ Best that fits my limit | Best ⚠ | 1080p ⚠ | 720p ⚠ | 480p ⚠ | Audio only (MP3)" {
t.Fatalf("quality buttons = %q", labels(menu))
}
seq = h.press(alice, alice, menu, "ql:720")
+214
View File
@@ -0,0 +1,214 @@
package app_test
import (
"fmt"
"strings"
"testing"
"github.com/noderunners/dlbot/internal/config"
"github.com/noderunners/dlbot/internal/tg/fakeserver"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
// --- /help -------------------------------------------------------------------
func TestHelpIsShortWithSections(t *testing.T) {
h := startApp(t, nil, nil)
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/help")
help := h.wait(seq, "sendMessage", textHas("How to use me"))
if got := labels(help); got != "Commands | Account | Groups | Open app | Upgrade" {
t.Fatalf("help buttons = %q", got)
}
// The default format and how to be asked every time are explained, and
// the limits are one line.
for _, want := range []string{"Your default format: <b>Best that fits my limit</b>", "Ask every time", "Your limits: 50 MB"} {
if !strings.Contains(help.Text(), want) {
t.Fatalf("help lacks %q: %q", want, help.Text())
}
}
section := func(prefix string) fakeserver.Call {
t.Helper()
seq := h.press(alice, alice, help, prefix)
return h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == help.MessageID })
}
if cmds := section("hp:cmds"); !strings.Contains(cmds.Text(), "/audio") || !strings.Contains(cmds.Text(), "/history") {
t.Fatalf("commands = %q", cmds.Text())
}
if acct := section("hp:acct"); !strings.Contains(acct.Text(), "/buy") || !strings.Contains(acct.Text(), "/referral") {
t.Fatalf("account = %q", acct.Text())
}
// In a private chat the group commands are hidden; "Add me to a group"
// takes their place.
grp := section("hp:groups")
for _, cmd := range []string{"/groupwallet", "/grouppass", "/settings"} {
if strings.Contains(grp.Text(), cmd) {
t.Fatalf("private help names %s: %q", cmd, grp.Text())
}
}
add, ok := grp.Button("")
if !ok || !strings.Contains(add.URL, "?startgroup=") {
t.Fatalf("groups section buttons = %+v", grp.Buttons())
}
seq = h.press(alice, alice, grp, "hp:home")
if home := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == help.MessageID }); !strings.Contains(home.Text(), "How to use me") {
t.Fatalf("back = %q", home.Text())
}
// In a group the group commands are listed.
h.meetGroup(alice)
seq = h.srv.Seq()
h.srv.PushMessage(group, alice, "/help")
ghelp := h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { return c.ChatID() == group })
if !strings.Contains(ghelp.Text(), "Format in this group") {
t.Fatalf("group help = %q", ghelp.Text())
}
seq = h.press(group, alice, ghelp, "hp:groups")
gg := h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == ghelp.MessageID })
if !strings.Contains(gg.Text(), "/groupwallet") || !strings.Contains(gg.Text(), "/grouppass") {
t.Fatalf("group section in a group = %q", gg.Text())
}
}
// --- /quality ------------------------------------------------------------------
func TestQualityMarksTheActiveModeAndWarnsFreeUsers(t *testing.T) {
h := startMoney(t, nil, nil)
open := func() fakeserver.Call {
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/quality")
return h.wait(seq, "sendMessage", textHas("Your default format"))
}
menu := open()
// 50 MB and 10 minutes: every video quality can go over, MP3 cannot.
want := "Ask every time | ✓ Best that fits my limit | Best ⚠ | 1080p ⚠ | 720p ⚠ | 480p ⚠ | Audio only (MP3)"
if got := labels(menu); got != want {
t.Fatalf("free user's choices = %q, want %q", got, want)
}
if !strings.Contains(menu.Text(), "over your limit of 50 MB") {
t.Fatalf("no explanation of the warning: %q", menu.Text())
}
// "Ask every time" is checked when it is the choice.
seq := h.press(alice, alice, menu, "ql:ask")
h.wait(seq, "editMessageText", textHas("Default format: Ask every time"))
if got := labels(open()); !strings.HasPrefix(got, "✓ Ask every time | Best that fits my limit") {
t.Fatalf("after choosing ask = %q", got)
}
// Paying users get no warnings.
h.grant(alice, 10_000)
menu = open()
if strings.Contains(labels(menu), "⚠") || strings.Contains(menu.Text(), "over your limit") {
t.Fatalf("a paying user is warned: %q %q", labels(menu), menu.Text())
}
}
func TestBestThatFitsPicksTheQualityUnderTheLimit(t *testing.T) {
big := "https://example.com/big-but-720-fits"
huge := "https://example.com/nothing-fits"
mb := func(n int) ytdlp.Int { return ytdlp.Int(n << 20) }
info := func(url string, v1080, v720, v480 int) *ytdlp.Info {
i := ytdlptest.DefaultInfo(url)
i.Formats = []ytdlp.Format{
{FormatID: "a", Ext: "m4a", VCodec: "none", ACodec: "mp4a", Filesize: mb(3)},
{FormatID: "v480", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 480, Filesize: mb(v480)},
{FormatID: "v720", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 720, Filesize: mb(v720)},
{FormatID: "v1080", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: 1080, FilesizeAprx: mb(v1080)},
}
return i
}
h := startMoney(t, &ytdlptest.Fake{Infos: map[string]*ytdlp.Info{
big: info(big, 120, 40, 15), huge: info(huge, 900, 400, 200),
}}, nil)
h.askEveryTime(alice)
if err := h.app.Store.SetUserQuality(t.Context(), alice, "fit"); err != nil {
t.Fatal(err)
}
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, big)
h.finished(seq, alice)
if dl := h.fake.Downloads(); len(dl) != 1 || string(dl[0].Profile) != "720" {
t.Fatalf("downloads = %+v, want 720p", dl)
}
// Even 480p is over 50 MB: the over-limit offer, nothing downloaded.
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, huge)
h.wait(seq, "sendMessage", func(c fakeserver.Call) bool { _, ok := c.Button("ob:"); return ok })
if n := len(h.fake.Downloads()); n != 1 {
t.Fatalf("%d downloads, the over-limit file must wait for payment", n)
}
}
// --- /history ------------------------------------------------------------------
func TestHistoryPagesThroughDownloads(t *testing.T) {
h := start(t, nil, func(c *config.Config) { c.Limits.Free.DailyDownloads = 50 })
for i := 1; i <= 7; i++ {
h.fetch(alice, fmt.Sprintf("https://example.com/v%d", i))
}
// A thumbnail is not a download of its own in the list.
seq := h.srv.Seq()
h.srv.PushMessage(alice, alice, "/thumb https://example.com/v7")
h.finished(seq, alice)
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/history")
list := h.wait(seq, "sendMessage", textHas("Your past downloads"))
items := func(c fakeserver.Call) int {
n := 0
for _, b := range c.Buttons() {
if strings.HasPrefix(b.Data, "hv:") {
n++
if b.Text != "example.com · Test Video · Best · today" {
t.Errorf("label = %q", b.Text)
}
}
}
return n
}
if n := items(list); n != 5 || !strings.Contains(list.Text(), "· 7") || !strings.Contains(list.Text(), "Page 1 of 2") {
t.Fatalf("first page: %d items, %q", n, list.Text())
}
if !strings.Contains(labels(list), "Older ›") || strings.Contains(labels(list), "Newer") {
t.Fatalf("first page buttons = %q", labels(list))
}
edited := func(seq int) fakeserver.Call {
return h.wait(seq, "editMessageText", func(c fakeserver.Call) bool { return c.MessageID == list.MessageID })
}
page2 := edited(h.press(alice, alice, list, "hi:1"))
if n := items(page2); n != 2 || !strings.Contains(labels(page2), "‹ Newer") || strings.Contains(labels(page2), "Older") {
t.Fatalf("second page: %d items, buttons %q", n, labels(page2))
}
// One download, with the thumbnail as an action under it.
item := edited(h.press(alice, alice, page2, "hv:"))
if got := labels(item); got != "Send again | Thumbnail | Remove from history | Back" {
t.Fatalf("item buttons = %q", got)
}
back := edited(h.press(alice, alice, item, "hd:"))
if !strings.Contains(back.Text(), "· 6") {
t.Fatalf("after removing one = %q", back.Text())
}
// Clearing asks first.
ask := edited(h.press(alice, alice, back, "hc:"))
if !strings.Contains(ask.Text(), "Remove all 6 downloads") {
t.Fatalf("confirm = %q", ask.Text())
}
cancel := edited(h.press(alice, alice, ask, "hi:"))
if !strings.Contains(cancel.Text(), "· 6") {
t.Fatalf("cancel = %q", cancel.Text())
}
ask = edited(h.press(alice, alice, cancel, "hc:"))
cleared := edited(h.press(alice, alice, ask, "hy"))
if !strings.Contains(cleared.Text(), "empty") {
t.Fatalf("cleared = %q", cleared.Text())
}
seq = h.srv.Seq()
h.srv.PushMessage(alice, alice, "/history")
h.wait(seq, "sendMessage", textHas("no past downloads"))
// The rows stay for usage and billing; only the history forgets them.
if u := h.usage(alice); u.Downloads != 8 {
t.Fatalf("usage = %+v", u)
}
}
+4 -12
View File
@@ -319,18 +319,6 @@ func (b *Bot) cmdStart(ctx context.Context, m *telego.Message, act actor) {
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "start.private", i18n.Args{"Name": act.user.FirstName}), kb)
}
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: m.Chat.ID, ChatType: m.Chat.Type}, false)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(act.lang, "help.text", i18n.Args{
"MaxSize": b.tr.Size(act.lang, dec.Limits.MaxSize),
"MaxDuration": b.tr.Span(act.lang, secondsDuration(dec.Limits.MaxDuration)),
}), nil)
}
// 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.
@@ -522,6 +510,10 @@ func (b *Bot) handleCallback(ctx context.Context, q *telego.CallbackQuery) {
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:
+1 -56
View File
@@ -311,39 +311,6 @@ func (b *Bot) subsCard(ctx context.Context, lr linkRequest, messageID int64, req
_ = b.edit(ctx, lr.chatID, messageID, false, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "subs.pick", nil), keyboard(rows...))
}
// --- history -----------------------------------------------------------------
func (b *Bot) cmdHistory(ctx context.Context, m *telego.Message, act actor) {
lang := act.lang
dels, err := b.store.History(ctx, act.user.ID, 10)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
if len(dels) == 0 {
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(lang, "history.empty", nil), nil)
return
}
var sb strings.Builder
sb.WriteString(b.tr.HTML(lang, "history.header", nil))
var rows [][]telego.InlineKeyboardButton
n := 0
for _, d := range dels {
job, err := b.store.GetJob(ctx, d.JobID)
if err != nil {
continue
}
n++
label := b.profileLabel(lang, jobProfile(job))
sb.WriteString("\n")
sb.WriteString(b.tr.HTML(lang, "history.line", i18n.Args{"N": n, "Title": shorten(job.Title, 60), "Label": label}))
rows = append(rows, []telego.InlineKeyboardButton{
button(b.tr.T(lang, "btn.resend", i18n.Args{"N": n, "Title": shorten(job.Title, 28)}), cbData(cbResend, d.ID)),
})
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), sb.String(), keyboard(rows...))
}
// cbResendFile sends a past download again. It is a new request like any
// other: same limits, same quota, same price. The cache usually makes it
// instant.
@@ -371,29 +338,7 @@ func (b *Bot) cbResendFile(ctx context.Context, q *telego.CallbackQuery, act act
chat, chatType = q.Message.GetChat().ID, q.Message.GetChat().Type
}
b.answer(ctx, q, "", false)
info.Fresh = false
req := &db.Request{
ID: ids.New(), UserID: act.user.ID, ChatID: chat, ChatType: chatType, URL: orig.URL,
Status: db.RequestReady, Info: info.JSON(), Lang: lang,
}
msg, err := b.send(ctx, chat, 0, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil)
if err != nil {
return
}
req.CardMessageID = int64(msg.MessageID)
if err := b.store.InsertRequest(ctx, req); err != nil {
b.internalError(ctx, chat, act, err)
return
}
err = b.startFromRequest(ctx, req, info, profile, nil)
var le *service.LimitError
switch {
case err == nil:
case errors.As(err, &le) && le.Upgradable:
b.offerUpgrade(ctx, chat, req.CardMessageID, lang, req, profile, le, isPrivate(chatType))
default:
_ = b.edit(ctx, chat, req.CardMessageID, false, titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil)
}
b.startAgain(ctx, act, chat, chatType, 0, orig, info, profile)
}
// --- owner: cache ------------------------------------------------------------
+3 -2
View File
@@ -526,8 +526,9 @@ func (b *Bot) cbGroupBuyProduct(ctx context.Context, q *telego.CallbackQuery, ac
// --- personal preferences ---------------------------------------------------
func (b *Bot) cmdQuality(ctx context.Context, m *telego.Message, act actor) {
kb := b.qualityKeyboard(act, func(v string) string { return cbData(cbQuality, v) }, false)
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.tr.HTML(act.lang, "quality.pick", nil), kb)
risky, maxSize := b.riskyQualities(ctx, act)
kb := b.qualityKeyboard(act, risky, func(v string) string { return cbData(cbQuality, v) }, false)
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), b.qualityText(act.lang, risky, maxSize), kb)
}
func (b *Bot) cbSetQuality(ctx context.Context, q *telego.CallbackQuery, act actor, value string) {
+118
View File
@@ -0,0 +1,118 @@
package bot
import (
"context"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/groups"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/service"
)
// /help is a short introduction with buttons that turn the same message
// into one section at a time: commands, account, groups.
// cbHelp switches the help message to a section: hp:<section>.
const cbHelp = "hp"
// Help sections.
const (
helpHome = "home"
helpCommands = "cmds"
helpAccount = "acct"
helpGroups = "groups"
)
// helpView renders one section of the help for a chat.
func (b *Bot) helpView(ctx context.Context, act actor, chat int64, chatType, section string) (string, *telego.InlineKeyboardMarkup, error) {
lang := act.lang
private := isPrivate(chatType)
back := keyboard([]telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.back", nil), cbData(cbHelp, helpHome))})
switch section {
case helpCommands:
if private {
return b.tr.HTML(lang, "help.commands", nil), back, nil
}
return b.tr.HTML(lang, "help.commands_group", nil), back, nil
case helpAccount:
return b.tr.HTML(lang, "help.account", nil), back, nil
case helpGroups:
if private {
// Group commands mean nothing here: how to get the bot into a
// group instead.
return b.tr.HTML(lang, "help.groups_private", nil), keyboard(
[]telego.InlineKeyboardButton{b.addToGroupButton(lang)},
back.InlineKeyboard[0],
), nil
}
return b.tr.HTML(lang, "help.groups_group", nil), back, nil
}
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: chat, ChatType: chatType}, false)
if err != nil {
return "", nil, err
}
l := dec.Limits
var format string
if private {
format = b.tr.HTML(lang, "help.format", i18n.Args{"Quality": b.userQualityName(lang, act.user.Quality)})
} else {
q := ""
if act.group != nil {
q = act.group.Quality
}
format = b.tr.HTML(lang, "help.format_group", i18n.Args{"Quality": b.qualityName(lang, q)})
}
text := b.tr.HTML(lang, "help.intro", nil) + "\n\n" + format + "\n\n" +
b.tr.HTML(lang, "help.limits", i18n.Args{
"MaxSize": b.capSize(lang, min64(l.MaxSize, b.cfg.MaxUploadBytes())),
"MaxDuration": b.tr.Span(lang, secondsDuration(l.MaxDuration)),
"Daily": b.capNumber(lang, int64(l.DailyDownloads)),
})
rows := [][]telego.InlineKeyboardButton{
{
button(b.tr.T(lang, "btn.help_commands", nil), cbData(cbHelp, helpCommands)),
button(b.tr.T(lang, "btn.help_account", nil), cbData(cbHelp, helpAccount)),
},
{button(b.tr.T(lang, "btn.help_groups", nil), cbData(cbHelp, helpGroups))},
}
var last []telego.InlineKeyboardButton
if btn, ok := b.appButton(lang, private, ""); ok {
last = append(last, btn)
}
if !dec.Source.Paid() {
last = append(last, b.upgradeButton(lang, private)...)
}
rows = append(rows, last)
return text, keyboard(rows...), nil
}
func (b *Bot) cmdHelp(ctx context.Context, m *telego.Message, act actor) {
text, kb, err := b.helpView(ctx, act, m.Chat.ID, m.Chat.Type, helpHome)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb)
}
// cbHelpSection turns the help message into another section.
func (b *Bot) cbHelpSection(ctx context.Context, q *telego.CallbackQuery, act actor, section string) {
if q.Message == nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
chat := q.Message.GetChat()
if groups.IsGroup(chat.Type) && act.group == nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
text, kb, err := b.helpView(ctx, act, chat.ID, chat.Type, section)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.answer(ctx, q, "", false)
_ = b.edit(ctx, chat.ID, int64(q.Message.GetMessageID()), false, text, kb)
}
+248
View File
@@ -0,0 +1,248 @@
package bot
import (
"context"
"html"
"strconv"
"strings"
"time"
"github.com/mymmrac/telego"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
// /history is one message that pages through past downloads. Each
// download is a compact button; tapping it shows the download with its
// actions. Thumbnails are not listed as downloads of their own: they are
// an action under their video.
const (
cbHistory = "hi" // hi:<page>
cbHistoryView = "hv" // hv:<delivery id>:<page>
cbHistoryDel = "hd" // hd:<delivery id>:<page>
cbHistoryClear = "hc" // hc:<page>, asks first
cbHistoryWipe = "hy" // hy, confirmed
)
// historyPageSize is how many downloads one page lists.
const historyPageSize = 5
// siteNames are the names people know sites by, keyed by yt-dlp extractor.
var siteNames = map[string]string{
"youtube": "YouTube", "instagram": "Instagram", "tiktok": "TikTok", "twitter": "X", "x": "X",
"facebook": "Facebook", "reddit": "Reddit", "vimeo": "Vimeo", "soundcloud": "SoundCloud",
"twitch": "Twitch", "dailymotion": "Dailymotion", "bandcamp": "Bandcamp", "threads": "Threads",
"bilibili": "Bilibili", "pinterest": "Pinterest", "linkedin": "LinkedIn", "rumble": "Rumble",
"archiveorg": "Internet Archive", "peertube": "PeerTube", "odysee": "Odysee", "lbry": "Odysee",
}
// siteName names the source of a download: the site's usual name for a
// known extractor, the host for yt-dlp's generic one.
func siteName(extractor, url string) string {
key := strings.ToLower(extractor)
if i := strings.IndexAny(key, ":_"); i > 0 {
key = key[:i] // youtube:tab, instagram_story
}
if name, ok := siteNames[key]; ok {
return name
}
if key == "" || key == "generic" || key == "fake" {
if host := links.Site(url); host != "" {
return host
}
}
if key == "" {
return "?"
}
return strings.ToUpper(key[:1]) + key[1:]
}
// when says how long ago something happened, in days: today, yesterday,
// 3 days ago, then the date.
func (b *Bot) when(lang string, at, now time.Time) string {
y1, m1, d1 := at.UTC().Date()
y2, m2, d2 := now.UTC().Date()
days := int(time.Date(y2, m2, d2, 0, 0, 0, 0, time.UTC).Sub(time.Date(y1, m1, d1, 0, 0, 0, 0, time.UTC)).Hours() / 24)
switch {
case days <= 0:
return b.tr.T(lang, "history.today", nil)
case days == 1:
return b.tr.T(lang, "history.yesterday", nil)
case days < 7:
return b.tr.T(lang, "history.days_ago", i18n.Args{"Count": days})
}
return b.tr.Date(lang, at)
}
// historyLabel is the button of one past download, such as
// "Instagram · nasa · 720p · today".
func (b *Bot) historyLabel(lang string, r db.HistoryRow, now time.Time) string {
title, _ := b.displayTitle(lang, &service.CardInfo{Title: r.Title, Uploader: r.Uploader, Site: siteName(r.Extractor, r.URL)})
return b.tr.T(lang, "history.item", i18n.Args{
"Site": siteName(r.Extractor, r.URL),
"Title": shorten(title, 22),
"Format": b.profileLabel(lang, profileOf(r.Profile)),
"When": b.when(lang, time.UnixMilli(r.CreatedAt), now),
})
}
func profileOf(s string) media.Profile {
p, err := media.Parse(s)
if err != nil {
return media.Best
}
return p
}
// historyPage renders one page of the list. ok is false when the history
// is empty.
func (b *Bot) historyPage(ctx context.Context, act actor, page int) (string, *telego.InlineKeyboardMarkup, error) {
lang := act.lang
if page < 0 {
page = 0
}
rows, total, err := b.store.HistoryPage(ctx, act.user.ID, page*historyPageSize, historyPageSize)
if err != nil {
return "", nil, err
}
pages := (total + historyPageSize - 1) / historyPageSize
if len(rows) == 0 && page > 0 && total > 0 {
// The page emptied (deleted items): show the last one there is.
return b.historyPage(ctx, act, pages-1)
}
if total == 0 {
return b.tr.HTML(lang, "history.empty", nil), nil, nil
}
p := strconv.Itoa(page)
now := time.Now()
var kb [][]telego.InlineKeyboardButton
for _, r := range rows {
kb = append(kb, []telego.InlineKeyboardButton{button(b.historyLabel(lang, r, now), cbData(cbHistoryView, r.DeliveryID, p))})
}
var nav []telego.InlineKeyboardButton
if page > 0 {
nav = append(nav, button(b.tr.T(lang, "btn.newer", nil), cbData(cbHistory, strconv.Itoa(page-1))))
}
if page < pages-1 {
nav = append(nav, button(b.tr.T(lang, "btn.older", nil), cbData(cbHistory, strconv.Itoa(page+1))))
}
kb = append(kb, nav, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.clear_history", nil), cbData(cbHistoryClear, p))})
text := b.tr.HTML(lang, "history.header", i18n.Args{"Page": page + 1, "Pages": pages, "Count": total})
return text, keyboard(kb...), nil
}
func (b *Bot) cmdHistory(ctx context.Context, m *telego.Message, act actor) {
text, kb, err := b.historyPage(ctx, act, 0)
if err != nil {
b.internalError(ctx, m.Chat.ID, act, err)
return
}
_, _ = b.send(ctx, m.Chat.ID, int64(m.MessageID), text, kb)
}
// cbHistoryAction handles every button of the history message. Each one
// edits the same message.
func (b *Bot) cbHistoryAction(ctx context.Context, q *telego.CallbackQuery, act actor, action, id, arg string) {
if q.Message == nil {
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
return
}
chat, msgID := q.Message.GetChat().ID, int64(q.Message.GetMessageID())
show := func(text string, kb *telego.InlineKeyboardMarkup) {
_ = b.edit(ctx, chat, msgID, false, text, kb)
}
page := func(s string) int { n, _ := strconv.Atoi(s); return n }
list := func(p int, notice string) {
text, kb, err := b.historyPage(ctx, act, p)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.answer(ctx, q, notice, false)
show(text, kb)
}
switch action {
case cbHistory:
list(page(id), "")
case cbHistoryView:
text, kb, ok := b.historyItem(ctx, act, id, arg)
if !ok {
list(page(arg), b.tr.T(act.lang, "notice.expired", nil))
return
}
b.answer(ctx, q, "", false)
show(text, kb)
case cbHistoryDel:
if _, err := b.store.HideFromHistory(ctx, act.user.ID, id); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
list(page(arg), b.tr.T(act.lang, "notice.removed", nil))
case cbHistoryClear:
_, total, err := b.store.HistoryPage(ctx, act.user.ID, 0, 1)
if err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.answer(ctx, q, "", false)
show(b.tr.HTML(act.lang, "history.clear_confirm", i18n.Args{"Count": total}), keyboard(
[]telego.InlineKeyboardButton{button(b.tr.T(act.lang, "btn.clear_yes", nil), cbHistoryWipe)},
[]telego.InlineKeyboardButton{button(b.tr.T(act.lang, "btn.cancel", nil), cbData(cbHistory, id))},
))
case cbHistoryWipe:
if _, err := b.store.ClearHistory(ctx, act.user.ID); err != nil {
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
return
}
b.answer(ctx, q, b.tr.T(act.lang, "notice.removed", nil), false)
show(b.tr.HTML(act.lang, "history.cleared", nil), nil)
}
}
// historyItem renders one past download with what can be done with it.
func (b *Bot) historyItem(ctx context.Context, act actor, deliveryID, page string) (string, *telego.InlineKeyboardMarkup, bool) {
lang := act.lang
d, err := b.store.GetDelivery(ctx, deliveryID)
if err != nil || d.UserID != act.user.ID || d.Status != db.DeliverySent || d.Hidden {
return "", nil, false
}
info := &service.CardInfo{}
url := ""
if req, err := b.store.GetRequest(ctx, d.RequestID); err == nil {
url = req.URL
if ci, err := service.ParseCardInfo(req.Info); err == nil {
info = ci
}
}
if d.Title != "" {
info.Title = d.Title
}
if d.Uploader != "" {
info.Uploader = d.Uploader
}
title, _ := b.displayTitle(lang, info)
facts := []string{html.EscapeString(siteName(d.Extractor, url)), html.EscapeString(b.profileLabel(lang, profileOf(d.Profile)))}
if job, err := b.store.GetJob(ctx, d.JobID); err == nil && job.FileSize > 0 {
facts = append(facts, b.tr.Size(lang, job.FileSize))
}
facts = append(facts, html.EscapeString(b.tr.Date(lang, time.UnixMilli(d.CreatedAt))))
text := titleLine(title) + "\n" + strings.Join(facts, " · ")
if url != "" {
clean := links.Clean(url)
text += "\n" + `<a href="` + html.EscapeString(clean) + `">` + html.EscapeString(links.Short(clean, 40)) + `</a>`
}
rows := [][]telego.InlineKeyboardButton{{button(b.tr.T(lang, "btn.send_again", nil), cbData(cbResend, d.ID))}}
if info.Thumbnail != "" && profileOf(d.Profile).Kind() == media.KindVideo {
rows[0] = append(rows[0], button(b.profileLabel(lang, media.Thumb), cbData(cbFollowThumb, d.RequestID)))
}
rows = append(rows,
[]telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.remove_from_history", nil), cbData(cbHistoryDel, d.ID, page))},
[]telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.back", nil), cbData(cbHistory, page))},
)
return text, keyboard(rows...), true
}
+47 -5
View File
@@ -9,6 +9,7 @@ import (
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/service"
)
// This file is /settings in a private chat: the person's own settings in
@@ -90,7 +91,7 @@ func (b *Bot) personalView(ctx context.Context, act actor) (string, *telego.Inli
b.tr.T(lang, "settings.button", i18n.Args{"Label": label, "Value": value}), cbData(cbPersonal, key))}
}
rows := [][]telego.InlineKeyboardButton{
row(psQuality, b.tr.T(lang, "settings.quality", nil), b.userQualityName(lang, u.Quality)),
row(psQuality, b.tr.T(lang, "settings.format", nil), b.userQualityName(lang, u.Quality)),
row(psAudio, b.tr.T(lang, "settings.audio_only", nil), b.onOff(lang, u.Quality == string(media.MP3))),
row(psAsk, b.tr.T(lang, "settings.ask", nil), b.onOff(lang, u.Quality == qualityAsk)),
row(psLanguage, b.tr.T(lang, "settings.language", nil), langName),
@@ -141,7 +142,8 @@ func (b *Bot) cbPersonalSetting(ctx context.Context, q *telego.CallbackQuery, ac
case psHome:
case psQuality:
b.answer(ctx, q, "", false)
show(b.tr.HTML(act.lang, "quality.pick", nil), b.qualityKeyboard(act, func(v string) string {
risky, maxSize := b.riskyQualities(ctx, act)
show(b.qualityText(act.lang, risky, maxSize), b.qualityKeyboard(act, risky, func(v string) string {
return cbData(cbPersonal, psSetQ, v)
}, true))
return
@@ -207,9 +209,46 @@ func (b *Bot) cbPersonalSetting(ctx context.Context, q *telego.CallbackQuery, ac
show(b.personalView(ctx, act))
}
// qualityKeyboard lists the default formats with the active one checked.
// data builds the callback data of a choice.
func (b *Bot) qualityKeyboard(act actor, data func(v string) string, back bool) *telego.InlineKeyboardMarkup {
// typicalBitrate is a usual total bitrate per quality, in bits per
// second, for warning free users before they pick a default.
var typicalBitrate = map[media.Profile]int64{
media.Best: 6_000_000, media.P1080: 4_500_000, media.P720: 2_500_000, media.P480: 1_200_000, media.MP3: 192_000,
}
// riskyQualities are the defaults that are likely to go over a free
// user's size limit on a video as long as their duration limit allows.
// Paid users get no warning: their limits are far apart from these. The
// pick text then explains what happens in that case.
func (b *Bot) riskyQualities(ctx context.Context, act actor) (map[string]bool, int64) {
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: act.user.ID, ChatID: act.user.ID, ChatType: telego.ChatTypePrivate}, false)
if err != nil || dec.Source.Paid() {
return nil, 0
}
maxSize := min64(dec.Limits.MaxSize, b.cfg.MaxUploadBytes())
if maxSize <= 0 || dec.Limits.MaxDuration <= 0 {
return nil, 0
}
out := map[string]bool{}
for p, bps := range typicalBitrate {
if bps/8*dec.Limits.MaxDuration > maxSize {
out[string(p)] = true
}
}
return out, maxSize
}
// qualityText is the text above the quality picker.
func (b *Bot) qualityText(lang string, risky map[string]bool, maxSize int64) string {
text := b.tr.HTML(lang, "quality.pick", nil)
if len(risky) > 0 {
text += "\n\n" + b.tr.HTML(lang, "quality.over_note", i18n.Args{"MaxSize": b.tr.Size(lang, maxSize)})
}
return text
}
// qualityKeyboard lists the default formats with the active one checked,
// and the risky ones marked. data builds the callback data of a choice.
func (b *Bot) qualityKeyboard(act actor, risky map[string]bool, data func(v string) string, back bool) *telego.InlineKeyboardMarkup {
lang := act.lang
cur := act.user.Quality
if cur == qualityUnset {
@@ -217,6 +256,9 @@ func (b *Bot) qualityKeyboard(act actor, data func(v string) string, back bool)
}
opt := func(v string) telego.InlineKeyboardButton {
label := b.userQualityName(lang, v)
if risky[v] {
label = b.tr.T(lang, "btn.maybe_over", i18n.Args{"Label": label})
}
if v == cur {
label = b.tr.T(lang, "btn.checked", i18n.Args{"Label": label})
}
+32
View File
@@ -219,3 +219,35 @@ func TestStatusEditsAreThrottledButNotLost(t *testing.T) {
t.Fatalf("edits = %v, want nothing after the delivery ended", texts)
}
}
func TestHistoryLabels(t *testing.T) {
b := testBot(t, nil)
now := time.Date(2025, 5, 10, 15, 0, 0, 0, time.UTC)
at := func(daysAgo int) int64 { return now.AddDate(0, 0, -daysAgo).Add(-time.Hour).UnixMilli() }
cases := []struct {
lang string
row db.HistoryRow
want string
}{
{"en", db.HistoryRow{Extractor: "Instagram", Title: "Video by nasa", Uploader: "nasa", Profile: "720", CreatedAt: at(0)}, "Instagram · nasa · 720p · today"},
{"en", db.HistoryRow{Extractor: "youtube:tab", Title: "A very long title that goes on and on", Profile: "best", CreatedAt: at(1)}, "YouTube · A very long title tha… · Best · yesterday"},
{"es", db.HistoryRow{Extractor: "generic", URL: "https://www.example.org/x.mp4", Title: "Clip", Profile: "mp3", CreatedAt: at(3)}, "example.org · Clip · MP3 · hace 3 días"},
{"nl", db.HistoryRow{Extractor: "TikTok", Title: "Dans", Profile: "480", CreatedAt: at(30)}, "TikTok · Dans · 480p · 10 apr 2025"},
}
for _, c := range cases {
if got := b.historyLabel(c.lang, c.row, now); got != c.want {
t.Errorf("%s: label = %q, want %q", c.lang, got, c.want)
}
}
}
func TestSiteNames(t *testing.T) {
for in, want := range map[[2]string]string{
{"youtube", ""}: "YouTube", {"twitter", ""}: "X", {"instagram:story", ""}: "Instagram",
{"generic", "https://m.example.com/v"}: "example.com", {"newsite", ""}: "Newsite", {"", ""}: "?",
} {
if got := siteName(in[0], in[1]); got != want {
t.Errorf("siteName(%q, %q) = %q, want %q", in[0], in[1], got, want)
}
}
}
+72 -6
View File
@@ -8,14 +8,14 @@ import (
const deliveryCols = `id, job_id, request_id, user_id, chat_id, chat_type, reply_to_message_id,
status_message_id, status_is_photo, lang, status, attempts, error_code, tg_file_id,
tg_message_id, created_at, updated_at, source, wallet_id, charge_sats, quota_day, released,
max_size, max_duration`
max_size, max_duration, extractor, title, uploader, profile, hidden`
func scanDelivery(sc interface{ Scan(...any) error }) (*Delivery, error) {
var d Delivery
err := sc.Scan(&d.ID, &d.JobID, &d.RequestID, &d.UserID, &d.ChatID, &d.ChatType, &d.ReplyToMessageID,
&d.StatusMessageID, &d.StatusIsPhoto, &d.Lang, &d.Status, &d.Attempts, &d.ErrorCode, &d.TgFileID,
&d.TgMessageID, &d.CreatedAt, &d.UpdatedAt, &d.Source, &d.WalletID, &d.ChargeSats, &d.QuotaDay, &d.Released,
&d.MaxSize, &d.MaxDuration)
&d.MaxSize, &d.MaxDuration, &d.Extractor, &d.Title, &d.Uploader, &d.Profile, &d.Hidden)
if err != nil {
return nil, notFound(err)
}
@@ -48,11 +48,11 @@ func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error {
d.Source = "free"
}
_, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
d.ID, d.JobID, d.RequestID, d.UserID, d.ChatID, d.ChatType, d.ReplyToMessageID,
d.StatusMessageID, d.StatusIsPhoto, d.Lang, d.Status, d.Attempts, d.ErrorCode, d.TgFileID,
d.TgMessageID, d.CreatedAt, d.UpdatedAt, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released,
d.MaxSize, d.MaxDuration)
d.MaxSize, d.MaxDuration, d.Extractor, d.Title, d.Uploader, d.Profile, d.Hidden)
return err
}
@@ -102,8 +102,14 @@ func (s *Store) TransitionDelivery(ctx context.Context, id, from, to, errorCode
// MarkDeliverySent records the Telegram file and message of a delivery.
func (s *Store) MarkDeliverySent(ctx context.Context, id, fileID string, messageID int64) error {
// What history shows is copied from the job now, when it is final.
_, err := s.exec(ctx, `UPDATE deliveries SET status = 'sent', tg_file_id = ?, tg_message_id = ?,
error_code = '', updated_at = ? WHERE id = ?`, fileID, messageID, NowMilli(), id)
error_code = '', updated_at = ?,
extractor = COALESCE((SELECT j.extractor FROM jobs j WHERE j.id = deliveries.job_id), ''),
title = COALESCE((SELECT j.title FROM jobs j WHERE j.id = deliveries.job_id), ''),
uploader = COALESCE((SELECT j.uploader FROM jobs j WHERE j.id = deliveries.job_id), ''),
profile = COALESCE((SELECT j.profile FROM jobs j WHERE j.id = deliveries.job_id), '')
WHERE id = ?`, fileID, messageID, NowMilli(), id)
return err
}
@@ -169,7 +175,67 @@ func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string)
// History lists a user's delivered files, newest first.
func (s *Store) History(ctx context.Context, userID int64, limit int) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE user_id = ? AND status = 'sent' ORDER BY updated_at DESC, id DESC LIMIT ?`, userID, limit))
WHERE `+historyWhere+` ORDER BY created_at DESC, id DESC LIMIT ?`, userID, limit))
}
// historyWhere selects the downloads history lists for a user: sent, not
// removed from history, and not thumbnails, which are offered under their
// video instead of as downloads of their own.
const historyWhere = `user_id = ? AND status = 'sent' AND hidden = FALSE AND profile <> 'thumb'`
// HistoryRow is one past download as /history lists it.
type HistoryRow struct {
DeliveryID string
RequestID string
Extractor string
Title string
Uploader string
Profile string
URL string
Size int64
CreatedAt int64
}
// HistoryPage returns one page of a user's history, newest first, and how
// many downloads the history holds in all.
func (s *Store) HistoryPage(ctx context.Context, userID int64, offset, limit int) ([]HistoryRow, int, error) {
var total int
if err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE `+historyWhere, userID).Scan(&total); err != nil {
return nil, 0, err
}
rows, err := s.rows(ctx, `SELECT d.id, d.request_id, d.extractor, d.title, d.uploader, d.profile,
COALESCE(j.url, ''), COALESCE(j.file_size, 0), d.created_at
FROM deliveries d LEFT JOIN jobs j ON j.id = d.job_id
WHERE d.user_id = ? AND d.status = 'sent' AND d.hidden = FALSE AND d.profile <> 'thumb'
ORDER BY d.created_at DESC, d.id DESC LIMIT ? OFFSET ?`, userID, limit, offset)
if err != nil {
return nil, 0, err
}
defer rows.Close()
var out []HistoryRow
for rows.Next() {
var r HistoryRow
if err := rows.Scan(&r.DeliveryID, &r.RequestID, &r.Extractor, &r.Title, &r.Uploader, &r.Profile,
&r.URL, &r.Size, &r.CreatedAt); err != nil {
return nil, 0, err
}
out = append(out, r)
}
return out, total, rows.Err()
}
// HideFromHistory removes one download from a user's history. It reports
// whether the download was there.
func (s *Store) HideFromHistory(ctx context.Context, userID int64, deliveryID string) (bool, error) {
n, err := s.exec(ctx, `UPDATE deliveries SET hidden = TRUE WHERE id = ? AND user_id = ? AND hidden = FALSE`,
deliveryID, userID)
return n == 1, err
}
// ClearHistory removes every download from a user's history and returns
// how many there were.
func (s *Store) ClearHistory(ctx context.Context, userID int64) (int64, error) {
return s.exec(ctx, `UPDATE deliveries SET hidden = TRUE WHERE user_id = ? AND status = 'sent' AND hidden = FALSE`, userID)
}
// RecentDelivery is a file a user got lately, with the link it came from.
+27
View File
@@ -0,0 +1,27 @@
-- +goose Up
-- What /history shows, kept on the delivery itself so the list needs no
-- join and survives the job being cleaned up. Filled when a delivery is
-- sent. hidden is set by "delete from history"; the row stays, because
-- deliveries also carry usage and billing.
ALTER TABLE deliveries ADD COLUMN extractor TEXT NOT NULL DEFAULT '';
ALTER TABLE deliveries ADD COLUMN title TEXT NOT NULL DEFAULT '';
ALTER TABLE deliveries ADD COLUMN uploader TEXT NOT NULL DEFAULT '';
ALTER TABLE deliveries ADD COLUMN profile TEXT NOT NULL DEFAULT '';
ALTER TABLE deliveries ADD COLUMN hidden BOOLEAN NOT NULL DEFAULT FALSE;
UPDATE deliveries SET
extractor = COALESCE((SELECT j.extractor FROM jobs j WHERE j.id = deliveries.job_id), ''),
title = COALESCE((SELECT j.title FROM jobs j WHERE j.id = deliveries.job_id), ''),
uploader = COALESCE((SELECT j.uploader FROM jobs j WHERE j.id = deliveries.job_id), ''),
profile = COALESCE((SELECT j.profile FROM jobs j WHERE j.id = deliveries.job_id), '')
WHERE status = 'sent';
CREATE INDEX deliveries_history_idx ON deliveries (user_id, status, hidden, created_at);
-- +goose Down
DROP INDEX deliveries_history_idx;
ALTER TABLE deliveries DROP COLUMN hidden;
ALTER TABLE deliveries DROP COLUMN profile;
ALTER TABLE deliveries DROP COLUMN uploader;
ALTER TABLE deliveries DROP COLUMN title;
ALTER TABLE deliveries DROP COLUMN extractor;
+8
View File
@@ -177,6 +177,14 @@ type Delivery struct {
// who share a job can have different limits.
MaxSize int64
MaxDuration int64
// Extractor, Title, Uploader and Profile describe the file for
// history; they are copied from the job when the delivery is sent.
Extractor string
Title string
Uploader string
Profile string
// Hidden is set when the user removed the download from history.
Hidden bool
}
// CacheEntry is one cached result.
+33
View File
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
const mb = 1 << 20
@@ -41,3 +42,35 @@ func TestBestFit(t *testing.T) {
}
}
}
// TestBestFitFromFormatLists runs the selection on yt-dlp format lists,
// through the same size estimates the card uses.
func TestBestFitFromFormatLists(t *testing.T) {
audio := ytdlp.Format{FormatID: "a", Ext: "m4a", VCodec: "none", ACodec: "mp4a", Filesize: 3 * mb}
video := func(h int, size, approx int64, tbr float64) ytdlp.Format {
return ytdlp.Format{FormatID: "v", Ext: "mp4", VCodec: "avc1", ACodec: "none", Height: ytdlp.Int(h),
Filesize: ytdlp.Int(size), FilesizeAprx: ytdlp.Int(approx), TBR: ytdlp.Float(tbr)}
}
cases := []struct {
name string
duration float64
formats []ytdlp.Format
want media.Profile
fits bool
}{
{"filesize", 300, []ytdlp.Format{audio, video(1080, 120*mb, 0, 0), video(720, 40*mb, 0, 0), video(480, 15*mb, 0, 0)}, media.P720, true},
{"filesize_approx only", 300, []ytdlp.Format{audio, video(1080, 0, 90*mb, 0), video(720, 0, 30*mb, 0)}, media.P720, true},
// 720p means "the best up to 720p", here the 480p format.
{"bitrate times duration", 600, []ytdlp.Format{audio, video(1080, 0, 0, 2000), video(480, 0, 0, 500)}, media.P720, true},
{"bitrate, only the smallest fits", 600, []ytdlp.Format{audio, video(1080, 0, 0, 2000), video(720, 0, 0, 1200), video(480, 0, 0, 500)}, media.P480, true},
{"no size data at all", 300, []ytdlp.Format{{FormatID: "b", Ext: "mp4", VCodec: "avc1", ACodec: "mp4a", Height: 720}}, media.Best, true},
{"too big everywhere", 300, []ytdlp.Format{audio, video(720, 400*mb, 0, 0), video(480, 200*mb, 0, 0)}, media.P480, false},
}
for _, c := range cases {
info := cardInfo("https://example.com/v", &ytdlp.Info{ID: "v", Title: "T", Duration: ytdlp.Float(c.duration), Formats: c.formats})
got, fits := BestFit(info, 50*mb)
if got != c.want || fits != c.fits {
t.Errorf("%s: BestFit = %s, %v; want %s, %v (sizes %v)", c.name, got, fits, c.want, c.fits, info.Sizes)
}
}
}