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
+48
View File
@@ -980,3 +980,51 @@ the affiliate program. What was found and planned is in
friends, Open app, and "Add me to a group"
(`https://t.me/<bot>?startgroup=settings`). The bot username comes from
`getMe`.
### Phase 2: command screens
- **/help** is an introduction (how to send a link, the user's default
format and how to switch to "Ask every time", the limits on one line)
with the buttons Commands, Account, Groups, Open app and Upgrade. Each
button edits the same message, and each section has Back. Upgrade is
left out for paying users. In a private chat the Groups section names
no group command; it explains groups and has "Add me to a group". In a
group it lists the group commands. Anyone in a group may switch
sections: the message is help, not a personal setting.
- **/quality** lists Ask every time, Best that fits my limit, Best, 1080p,
720p, 480p and Audio only (MP3), with a check on the active one. A user
who never chose sees "Best that fits my limit" checked, since that is
what they get. Free users see a warning sign on the qualities that a
video as long as their duration limit would push over their size limit.
This uses typical bitrates: Best 6 Mbit/s, 1080p 4.5, 720p 2.5, 480p
1.2, MP3 192 kbit/s. A note explains the sign. Paying users get no
signs.
- **Best that fits my limit.** With no size estimate at all, Best is
picked and the worker's `--max-filesize` guards the real file. The
720p choice means "the best up to 720p", so on a source without a
720p format it is the 480p format and its size.
- **/history rows.** Migration 00007 adds `extractor`, `title`,
`uploader`, `profile` and `hidden` to `deliveries`, the rows history is
built from (they already have `created_at`). The columns are filled
from the job when a delivery is sent, and backfilled for old sent rows
on both databases with correlated subqueries.
- **/history list.** Pages of five. Each download is one button,
"site · title · format · when", for example "Instagram · nasa · 720p ·
today". A generic title becomes the uploader. "When" is today,
yesterday, N days ago, then the date. Site names come from the
extractor; yt-dlp's generic extractor shows the host. The separate
text list is gone; the message only has a header with the count and
page.
- **Thumbnails** are not listed as downloads. Tapping a video shows it
with Send again, Thumbnail (when the source has one), Remove from
history and Back.
- **Removing** from history hides the row and does not delete it, because
deliveries also hold usage and billing facts. Clear history asks first
and hides every row. The Mini App's history follows the same rules.
- Send again from history is a new download through the same path as
every other one, so limits, quota and price apply. A cache hit still
counts as a download.
- **Screens for review.** `docs/SCREENS.md` shows every screen of a
scripted walk through the bot in English, Spanish and Dutch. It is
generated by the language test
(`DLBOT_SCREENS=$PWD/docs/SCREENS.md go test ./internal/app -run TestEveryScreen`).
+2583
View File
File diff suppressed because it is too large Load Diff
+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)
}
}
}
+71 -30
View File
@@ -21,25 +21,17 @@ group = """
Use /dl with a link, or reply /dl to a message that has a link."""
[help]
text = """
<b>How to use me</b>
In a private chat, just send a link. I show a card and you pick the format.
In a group, use /dl with a link, or reply /dl to a message that has a link.
<b>Commands</b>
/dl link - download a video
/audio link - download the audio as MP3
/thumb link - get the thumbnail
/subs link - get the subtitles
/info link - show formats and sizes without downloading
/fresh link - download again instead of using a saved copy
/history - your past downloads, with one tap to get them again
/queue - your running downloads
/cancel - cancel your downloads
/quality - your default format
/language - change my language
groups_group = """
<b>This group</b>
/groupwallet - the group's balance and top up
/grouppass - buy a pass for the whole group
/settings - group settings, for admins
/grouplang - the bot's language here, for admins
/autodetect - fetch pasted links without a command, for admins"""
groups_private = """
<b>Groups</b>
Add me to a group and everyone there can download with /dl. A group can have its own wallet and pass, and its admins get settings of their own. Those commands show up in the group."""
account = """
<b>Account</b>
/account - your pass, balance and usage
/limits - the limits that apply to you
@@ -48,13 +40,34 @@ In a group, use /dl with a link, or reply /dl to a message that has a link.
/redeem code - use a gift code
/referral - invite friends and earn sats
/donate - send a tip
<b>In groups</b>
/groupwallet and /grouppass - the group's balance and pass
/settings - group settings, for admins
<b>Your limits</b>
Up to {{.MaxSize}} and {{.MaxDuration}} per download."""
/settings - your settings in one place"""
commands_group = """
<b>Commands in this group</b>
/dl link - download, or reply /dl to a message with a link
/audio link - the audio as MP3
/thumb link - the thumbnail
/info link - formats and sizes
/queue - your running downloads
/cancel - cancel them"""
commands = """
<b>Commands</b>
/dl link - download, in your default format
/audio link - the audio as MP3
/thumb link - the thumbnail
/subs link - the subtitles
/info link - formats and sizes, without downloading
/fresh link - download again instead of using a saved copy
/queue - your running downloads
/cancel - cancel them
/history - past downloads, one tap to get them again
/quality - your default format
/language - my language"""
limits = "Your limits: {{.MaxSize}} and {{.MaxDuration}} per download, {{.Daily}} downloads a day."
format_group = "Format in this group: <b>{{.Quality}}</b>. Admins change it in /settings."
format = "Your default format: <b>{{.Quality}}</b>. With a default I start right away. To pick a format for every link, choose <i>Ask every time</i> in /quality."
intro = """
<b>How to use me</b>
Send me a link to a video or a song and I send the file back. In a group, use /dl with a link, or reply /dl to a message that has one."""
[cmd]
unknown = "I do not know that command. Try /help."
@@ -143,6 +156,15 @@ pick = "Pick a format:"
cancelled = "Cancelled."
[btn]
maybe_over = "{{.Label}} ⚠"
remove_from_history = "Remove from history"
clear_yes = "Yes, clear it"
clear_history = "Clear history"
older = "Older ›"
newer = "‹ Newer"
help_groups = "Groups"
help_account = "Account"
help_commands = "Commands"
checked = "✓ {{.Label}}"
back = "Back"
add_to_group = "Add me to a group"
@@ -173,7 +195,6 @@ check_payment = "Check payment"
this_file = "This file only"
buy_for_me = "Buy for me"
subs_auto = "{{.Lang}} (auto)"
resend = "{{.N}}. {{.Title}}"
[status]
sent = "Sent."
@@ -190,6 +211,7 @@ failed = "That did not work. {{.Reason}}"
refunded = "{{.Amount}} went back to your balance."
[notice]
removed = "Removed."
cannot_delete = "Telegram only lets me delete messages from the last 48 hours."
group_only = "This command works in groups."
admins_only = "Only admins of this group can do that."
@@ -421,9 +443,14 @@ pick = "Pick a subtitle language:"
none = "This video has no subtitles."
[history]
cleared = "Your history is empty now."
yesterday = "yesterday"
today = "today"
item = "{{.Site}} · {{.Title}} · {{.Format}} · {{.When}}"
empty = "You have no past downloads yet."
header = "<b>Your past downloads</b>\nTap one to get it again."
line = "{{.N}}. {{.Title}} · {{.Label}}"
header = """
<b>Your past downloads</b> · {{.Count}}
Page {{.Page}} of {{.Pages}}. Tap one to see it and get it again."""
# --- Owner commands ---------------------------------------------------------
@@ -559,6 +586,7 @@ off = "off"
none = "none"
[settings]
format = "Default format"
language = "Language"
ask = "Ask every time"
audio_only = "Audio only"
@@ -606,10 +634,15 @@ Send these in the group, as an admin:
/spending rule - who may spend group credits"""
[quality]
over_note = "⚠ Can be over your limit of {{.MaxSize}} for longer videos. I then offer a smaller quality or an upgrade."
audio_only = "Audio only (MP3)"
fit = "Best that fits my limit"
ask = "Ask every time"
pick = "Pick your default format. I will then start right away instead of asking."
pick = """
<b>Your default format</b>
<i>Ask every time</i>: I show the formats for each link.
<i>Best that fits my limit</i>: I start at once with the best quality within your size limit.
A quality or MP3: I start at once in that format."""
set = "Default format: {{.Quality}}"
[language]
@@ -871,3 +904,11 @@ via = "via @{{.Bot}}"
[dup]
already_sent = "I sent you this a moment ago, it is just above. Tap below to get it again."
[history.days_ago]
one = "{{.Count}} day ago"
other = "{{.Count}} days ago"
[history.clear_confirm]
one = "Remove {{.Count}} download from your history? Files already in this chat stay where they are."
other = "Remove all {{.Count}} downloads from your history? Files already in this chat stay where they are."
+75 -34
View File
@@ -20,40 +20,53 @@ group = """
Usa /dl con un enlace, o responde /dl a un mensaje que tenga un enlace."""
[help]
text = """
<b>Cómo usarme</b>
En un chat privado, solo envía un enlace. Te muestro una tarjeta y eliges el formato.
En un grupo, usa /dl con un enlace, o responde /dl a un mensaje que tenga un enlace.
<b>Comandos</b>
/dl enlace - descargar un video
/audio enlace - descargar el audio en MP3
/thumb enlace - obtener la miniatura
/subs enlace - obtener los subtítulos
/info enlace - ver formatos y tamaños sin descargar
/fresh enlace - descargar de nuevo en vez de usar una copia guardada
/history - tus descargas anteriores, para pedirlas otra vez con un toque
/queue - tus descargas en curso
/cancel - cancelar tus descargas
/quality - tu formato por defecto
/language - cambiar mi idioma
groups_group = """
<b>Este grupo</b>
/groupwallet - el saldo del grupo y recargar
/grouppass - comprar un pase para todo el grupo
/settings - ajustes del grupo, para administradores
/grouplang - el idioma del bot aquí, para administradores
/autodetect - bajar enlaces pegados sin comando, para administradores"""
groups_private = """
<b>Grupos</b>
Añádeme a un grupo y todos allí podrán descargar con /dl. Un grupo puede tener su propio monedero y pase, y sus administradores tienen ajustes propios. Esos comandos aparecen en el grupo."""
account = """
<b>Cuenta</b>
/account - tu pase, saldo y uso
/limits - los límites que tienes
/buy - comprar un pase o créditos
/credits - tu saldo y cargar más
/limits - los límites que se te aplican
/buy - conseguir un pase o créditos
/credits - tu saldo y recargar
/redeem código - usar un código de regalo
/referral - invitar amigos y ganar sats
/referral - invita a amigos y gana sats
/donate - dejar una propina
<b>En grupos</b>
/groupwallet y /grouppass - el saldo y el pase del grupo
/settings - ajustes del grupo, para administradores
<b>Tus límites</b>
Hasta {{.MaxSize}} y {{.MaxDuration}} por descarga."""
/settings - tus ajustes en un solo lugar"""
commands_group = """
<b>Comandos en este grupo</b>
/dl enlace - descargar, o responde /dl a un mensaje con un enlace
/audio enlace - el audio en MP3
/thumb enlace - la miniatura
/info enlace - formatos y tamaños
/queue - tus descargas en curso
/cancel - cancelarlas"""
commands = """
<b>Comandos</b>
/dl enlace - descargar, en tu formato por defecto
/audio enlace - el audio en MP3
/thumb enlace - la miniatura
/subs enlace - los subtítulos
/info enlace - formatos y tamaños, sin descargar
/fresh enlace - descargar de nuevo en vez de usar una copia guardada
/queue - tus descargas en curso
/cancel - cancelarlas
/history - descargas anteriores, recíbelas otra vez con un toque
/quality - tu formato por defecto
/language - mi idioma"""
limits = "Tus límites: {{.MaxSize}} y {{.MaxDuration}} por descarga, {{.Daily}} descargas al día."
format_group = "Formato en este grupo: <b>{{.Quality}}</b>. Los administradores lo cambian en /settings."
format = "Tu formato por defecto: <b>{{.Quality}}</b>. Con un formato por defecto empiezo enseguida. Para elegir el formato en cada enlace, escoge <i>Preguntar siempre</i> en /quality."
intro = """
<b>Cómo usarme</b>
Envíame el enlace de un video o una canción y te devuelvo el archivo. En un grupo, usa /dl con un enlace, o responde /dl a un mensaje que tenga uno."""
[cmd]
unknown = "No conozco ese comando. Prueba con /help."
@@ -134,6 +147,15 @@ pick = "Elige un formato:"
cancelled = "Cancelado."
[btn]
maybe_over = "{{.Label}} ⚠"
remove_from_history = "Quitar del historial"
clear_yes = "Sí, borrarlo"
clear_history = "Borrar historial"
older = "Anteriores ›"
newer = "‹ Más recientes"
help_groups = "Grupos"
help_account = "Cuenta"
help_commands = "Comandos"
checked = "✓ {{.Label}}"
back = "Volver"
add_to_group = "Añádeme a un grupo"
@@ -164,7 +186,6 @@ check_payment = "Verificar el pago"
this_file = "Solo este archivo"
buy_for_me = "Comprar para mí"
subs_auto = "{{.Lang}} (automático)"
resend = "{{.N}}. {{.Title}}"
[status]
sent = "Enviado."
@@ -181,6 +202,7 @@ failed = "No funcionó. {{.Reason}}"
refunded = "Se devolvieron {{.Amount}} a tu saldo."
[notice]
removed = "Quitado."
cannot_delete = "Telegram solo me deja borrar mensajes de las últimas 48 horas."
group_only = "Este comando funciona en grupos."
admins_only = "Solo los administradores del grupo pueden hacer eso."
@@ -405,9 +427,14 @@ pick = "Elige el idioma de los subtítulos:"
none = "Este video no tiene subtítulos."
[history]
cleared = "Tu historial está vacío ahora."
yesterday = "ayer"
today = "hoy"
item = "{{.Site}} · {{.Title}} · {{.Format}} · {{.When}}"
empty = "Todavía no tienes descargas anteriores."
header = "<b>Tus descargas anteriores</b>\nToca una para recibirla otra vez."
line = "{{.N}}. {{.Title}} · {{.Label}}"
header = """
<b>Tus descargas anteriores</b> · {{.Count}}
Página {{.Page}} de {{.Pages}}. Toca una para verla y recibirla otra vez."""
[owner]
books_ok = "el libro mayor y los saldos coinciden"
@@ -539,6 +566,7 @@ off = "desactivado"
none = "ninguno"
[settings]
format = "Formato por defecto"
language = "Idioma"
ask = "Preguntar siempre"
audio_only = "Solo audio"
@@ -586,10 +614,15 @@ Envía esto en el grupo, como administrador:
/spending regla - quién puede gastar créditos del grupo"""
[quality]
over_note = "⚠ Puede pasar de tu límite de {{.MaxSize}} en videos largos. Entonces te ofrezco una calidad menor o mejorar tu plan."
audio_only = "Solo audio (MP3)"
fit = "La mejor que cabe en mi límite"
ask = "Preguntar siempre"
pick = "Elige tu formato por defecto. Así empiezo enseguida en vez de preguntarte."
pick = """
<b>Tu formato por defecto</b>
<i>Preguntar siempre</i>: te muestro los formatos en cada enlace.
<i>La mejor que cabe en mi límite</i>: empiezo enseguida con la mejor calidad dentro de tu límite de tamaño.
Una calidad o MP3: empiezo enseguida en ese formato."""
set = "Formato por defecto: {{.Quality}}"
[language]
@@ -844,3 +877,11 @@ via = "vía @{{.Bot}}"
[dup]
already_sent = "Te lo envié hace un momento, está justo arriba. Toca abajo para recibirlo otra vez."
[history.days_ago]
one = "hace {{.Count}} día"
other = "hace {{.Count}} días"
[history.clear_confirm]
one = "Quitar {{.Count}} descarga de tu historial? Los archivos que ya están en este chat se quedan donde están."
other = "Quitar las {{.Count}} descargas de tu historial? Los archivos que ya están en este chat se quedan donde están."
+71 -30
View File
@@ -19,25 +19,17 @@ group = """
Gebruik /dl met een link, of antwoord /dl op een bericht met een link."""
[help]
text = """
<b>Zo gebruik je me</b>
Stuur in een privéchat gewoon een link. Ik laat een kaart zien en jij kiest het formaat.
Gebruik in een groep /dl met een link, of antwoord /dl op een bericht met een link.
<b>Commando's</b>
/dl link - een video downloaden
/audio link - de audio als MP3 downloaden
/thumb link - de miniatuur ophalen
/subs link - de ondertitels ophalen
/info link - formaten en groottes bekijken zonder te downloaden
/fresh link - opnieuw downloaden in plaats van een bewaarde kopie te gebruiken
/history - je eerdere downloads, met één tik opnieuw op te halen
/queue - je lopende downloads
/cancel - je downloads annuleren
/quality - je standaardformaat
/language - mijn taal wijzigen
groups_group = """
<b>Deze groep</b>
/groupwallet - het saldo van de groep en opwaarderen
/grouppass - een pas voor de hele groep kopen
/settings - groepsinstellingen, voor beheerders
/grouplang - de taal van de bot hier, voor beheerders
/autodetect - geplakte links zonder commando ophalen, voor beheerders"""
groups_private = """
<b>Groepen</b>
Voeg me toe aan een groep en iedereen daar kan downloaden met /dl. Een groep kan een eigen portemonnee en pas hebben, en de beheerders krijgen eigen instellingen. Die commando's verschijnen in de groep."""
account = """
<b>Account</b>
/account - je pas, saldo en gebruik
/limits - de limieten die voor jou gelden
@@ -46,13 +38,34 @@ Gebruik in een groep /dl met een link, of antwoord /dl op een bericht met een li
/redeem code - een cadeaucode gebruiken
/referral - vrienden uitnodigen en sats verdienen
/donate - een fooi geven
<b>In groepen</b>
/groupwallet en /grouppass - het saldo en de pas van de groep
/settings - groepsinstellingen, voor beheerders
<b>Jouw limieten</b>
Tot {{.MaxSize}} en {{.MaxDuration}} per download."""
/settings - je instellingen op één plek"""
commands_group = """
<b>Commando's in deze groep</b>
/dl link - downloaden, of antwoord /dl op een bericht met een link
/audio link - de audio als MP3
/thumb link - de miniatuur
/info link - formaten en groottes
/queue - je lopende downloads
/cancel - ze annuleren"""
commands = """
<b>Commando's</b>
/dl link - downloaden, in je standaardformaat
/audio link - de audio als MP3
/thumb link - de miniatuur
/subs link - de ondertitels
/info link - formaten en groottes, zonder te downloaden
/fresh link - opnieuw downloaden in plaats van een bewaarde kopie
/queue - je lopende downloads
/cancel - ze annuleren
/history - eerdere downloads, met één tik opnieuw
/quality - je standaardformaat
/language - mijn taal"""
limits = "Je limieten: {{.MaxSize}} en {{.MaxDuration}} per download, {{.Daily}} downloads per dag."
format_group = "Formaat in deze groep: <b>{{.Quality}}</b>. Beheerders wijzigen het in /settings."
format = "Je standaardformaat: <b>{{.Quality}}</b>. Met een standaard begin ik meteen. Wil je bij elke link zelf kiezen, kies dan <i>Elke keer vragen</i> in /quality."
intro = """
<b>Zo gebruik je me</b>
Stuur me een link naar een video of een nummer en ik stuur het bestand terug. Gebruik in een groep /dl met een link, of antwoord /dl op een bericht met een link."""
[cmd]
unknown = "Dat commando ken ik niet. Probeer /help."
@@ -133,6 +146,15 @@ pick = "Kies een formaat:"
cancelled = "Geannuleerd."
[btn]
maybe_over = "{{.Label}} ⚠"
remove_from_history = "Uit geschiedenis halen"
clear_yes = "Ja, wissen"
clear_history = "Geschiedenis wissen"
older = "Ouder ›"
newer = "‹ Nieuwer"
help_groups = "Groepen"
help_account = "Account"
help_commands = "Commando's"
checked = "✓ {{.Label}}"
back = "Terug"
add_to_group = "Voeg me toe aan een groep"
@@ -163,7 +185,6 @@ check_payment = "Betaling controleren"
this_file = "Alleen dit bestand"
buy_for_me = "Voor mij kopen"
subs_auto = "{{.Lang}} (automatisch)"
resend = "{{.N}}. {{.Title}}"
[status]
sent = "Verstuurd."
@@ -180,6 +201,7 @@ failed = "Dat lukte niet. {{.Reason}}"
refunded = "{{.Amount}} is teruggezet op je saldo."
[notice]
removed = "Verwijderd."
cannot_delete = "Telegram laat me alleen berichten van de afgelopen 48 uur verwijderen."
group_only = "Dit commando werkt in groepen."
admins_only = "Alleen beheerders van deze groep kunnen dat."
@@ -404,9 +426,14 @@ pick = "Kies een taal voor de ondertitels:"
none = "Deze video heeft geen ondertitels."
[history]
cleared = "Je geschiedenis is nu leeg."
yesterday = "gisteren"
today = "vandaag"
item = "{{.Site}} · {{.Title}} · {{.Format}} · {{.When}}"
empty = "Je hebt nog geen eerdere downloads."
header = "<b>Je eerdere downloads</b>\nTik op een download om hem opnieuw te krijgen."
line = "{{.N}}. {{.Title}} · {{.Label}}"
header = """
<b>Je eerdere downloads</b> · {{.Count}}
Pagina {{.Page}} van {{.Pages}}. Tik op een download om hem te bekijken en opnieuw te krijgen."""
[owner]
books_ok = "grootboek en saldi kloppen"
@@ -538,6 +565,7 @@ off = "uit"
none = "geen"
[settings]
format = "Standaardformaat"
language = "Taal"
ask = "Elke keer vragen"
audio_only = "Alleen audio"
@@ -585,10 +613,15 @@ Stuur deze in de groep, als beheerder:
/spending regel - wie groepstegoed mag uitgeven"""
[quality]
over_note = "⚠ Kan bij langere video's boven je limiet van {{.MaxSize}} uitkomen. Dan bied ik een lagere kwaliteit of een upgrade aan."
audio_only = "Alleen audio (MP3)"
fit = "Beste die binnen mijn limiet past"
ask = "Elke keer vragen"
pick = "Kies je standaardformaat. Dan begin ik meteen in plaats van te vragen."
pick = """
<b>Je standaardformaat</b>
<i>Elke keer vragen</i>: ik laat bij elke link de formaten zien.
<i>Beste die binnen mijn limiet past</i>: ik begin meteen met de beste kwaliteit binnen je groottelimiet.
Een kwaliteit of MP3: ik begin meteen in dat formaat."""
set = "Standaardformaat: {{.Quality}}"
[language]
@@ -843,3 +876,11 @@ via = "via @{{.Bot}}"
[dup]
already_sent = "Dit heb ik je net gestuurd, het staat hierboven. Tik hieronder om het opnieuw te krijgen."
[history.days_ago]
one = "{{.Count}} dag geleden"
other = "{{.Count}} dagen geleden"
[history.clear_confirm]
one = "{{.Count}} download uit je geschiedenis halen? Bestanden die al in deze chat staan blijven staan."
other = "Alle {{.Count}} downloads uit je geschiedenis halen? Bestanden die al in deze chat staan blijven staan."