package bot
import (
"html"
"strings"
"unicode"
"unicode/utf8"
"github.com/noderunners/dlbot/internal/db"
"github.com/noderunners/dlbot/internal/i18n"
"github.com/noderunners/dlbot/internal/media"
)
// clip shortens s to at most max bytes without cutting a rune, and without
// leaving an HTML entity or tag half open at the end.
func clip(s string, max int) string {
if len(s) <= max {
return s
}
cut := max - 1
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
out := s[:cut]
if i := strings.LastIndexAny(out, "<&"); i >= 0 && !strings.ContainsAny(out[i:], ">;") {
out = out[:i]
}
return out + "…"
}
// shorten cuts plain text to a number of runes, adding an ellipsis.
func shorten(s string, runes int) string {
s = strings.TrimSpace(s)
if utf8.RuneCountInString(s) <= runes {
return s
}
r := []rune(s)
return strings.TrimSpace(string(r[:runes-1])) + "…"
}
// titleLine is the bold, escaped title used at the top of cards and
// status messages.
func titleLine(title string) string {
return "" + html.EscapeString(shorten(title, 120)) + ""
}
// fileName builds the name a delivered file gets in Telegram.
func fileName(title, ext string) string {
var sb strings.Builder
for _, r := range title {
switch {
case r == '/' || r == '\\' || r == ':' || r == '*' || r == '?' || r == '"' || r == '<' || r == '>' || r == '|':
sb.WriteRune(' ')
case unicode.IsControl(r):
default:
sb.WriteRune(r)
}
}
name := strings.Join(strings.Fields(sb.String()), " ")
name = strings.Trim(shorten(name, 80), ". ")
if name == "" {
name = "media"
}
if ext == "" {
return name
}
return name + "." + ext
}
// bar renders a ten segment progress bar. It has no words, so it needs no
// translation.
func bar(ratio float64) string {
if ratio < 0 {
ratio = 0
}
if ratio > 1 {
ratio = 1
}
filled := int(ratio*10 + 0.5)
return strings.Repeat("▰", filled) + strings.Repeat("▱", 10-filled)
}
// profileLabel is the human name of a profile, as used on buttons.
func (b *Bot) profileLabel(lang string, p media.Profile) string {
switch {
case p == media.Best:
return b.tr.T(lang, "btn.best", nil)
case p == media.MP3:
return b.tr.T(lang, "btn.mp3", nil)
case p == media.M4A:
return b.tr.T(lang, "btn.m4a", nil)
case p == media.Thumb:
return b.tr.T(lang, "btn.thumb", nil)
case p.Kind() == media.KindSubs:
return b.tr.T(lang, "btn.subs", i18n.Args{"Lang": p.SubLang()})
default:
return b.tr.T(lang, "btn.res", i18n.Args{"Height": p.Height()})
}
}
func jobProfile(j *db.Job) media.Profile {
p, err := media.Parse(j.Profile)
if err != nil {
return media.Best
}
return p
}