Files
MichilisandClaude Opus 5.5 123cede7f3 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>
2026-11-18 20:46:13 +00:00

249 lines
8.8 KiB
Go

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
}