Remote workers, Postgres and S3, all chosen by configuration. - Pull-based worker protocol over HTTP: claim (long poll), heartbeat, complete, fail, upload, source, probe. Workers need no inbound ports - cmd/worker: standalone stateless worker with health endpoint and scheduled yt-dlp self-update - Per-worker bearer tokens, stored hashed, revocable; identity always taken from the token; actions only on jobs the worker holds a lease for - Tags: site_tags routes a site's jobs and lookups to workers that carry the required tags - Drain, /workers, /ytdlp update, and "core worker add|revoke|list" - Link lookups can run on remote workers (PROBE_MODE), so the core needs no yt-dlp and no residential address - Postgres backend with pgx, same schema and queries; per-user advisory lock and job row lock where SQLite's serial writes were relied on - The whole test suite runs on SQLite and on Postgres - S3 storage backend with presigned worker uploads, sharing a conformance suite with the local backend - Dockerfile with core, worker and faketelegram targets, docker-compose with optional Postgres and local Bot API server, systemd units - deploy/acceptance/kill-worker.sh: kills a worker mid-job and checks that the other one delivers the file - Fixes found on the way: /cancel could let the next playlist item start; a refund note could be missing when the sweep refunded first Docker was not available on the build machine: the compose files were validated with "docker compose config" only. The acceptance scenario was run with real processes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
553 lines
19 KiB
Go
553 lines
19 KiB
Go
package bot
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"html"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/mymmrac/telego"
|
|
|
|
"github.com/noderunners/dlbot/internal/cache"
|
|
"github.com/noderunners/dlbot/internal/db"
|
|
"github.com/noderunners/dlbot/internal/i18n"
|
|
"github.com/noderunners/dlbot/internal/ids"
|
|
"github.com/noderunners/dlbot/internal/media"
|
|
"github.com/noderunners/dlbot/internal/service"
|
|
"github.com/noderunners/dlbot/internal/workerproto"
|
|
)
|
|
|
|
const (
|
|
cbPlaylist = "pl" // pl:<request id>:<profile>
|
|
cbResend = "rs" // rs:<delivery id>
|
|
)
|
|
|
|
// --- playlists ---------------------------------------------------------------
|
|
|
|
// playlistCard shows a playlist link: how many items it has, how many of
|
|
// them this requester's limits allow, and the format buttons.
|
|
func (b *Bot) playlistCard(ctx context.Context, lr linkRequest, messageID int64, pl *service.Playlist) {
|
|
lang := lr.act.lang
|
|
if len(pl.Entries) == 0 {
|
|
_ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "playlist.empty", nil), nil)
|
|
return
|
|
}
|
|
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType}, false)
|
|
if err != nil {
|
|
_ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "error.internal", nil), nil)
|
|
return
|
|
}
|
|
take := playlistTake(len(pl.Entries), dec.Limits.PlaylistItems)
|
|
req := &db.Request{
|
|
ID: ids.New(), UserID: lr.act.user.ID, ChatID: lr.chatID, ChatType: lr.chatType,
|
|
SourceMessageID: lr.sourceID, CardMessageID: messageID, URL: lr.url,
|
|
Status: db.RequestReady, Info: pl.JSON(), Lang: lang,
|
|
}
|
|
if err := b.store.InsertRequest(ctx, req); err != nil {
|
|
b.log.Error("insert playlist request", "err", err)
|
|
_ = b.edit(ctx, lr.chatID, messageID, false, b.tr.HTML(lang, "error.internal", nil), nil)
|
|
return
|
|
}
|
|
text := b.tr.HTML(lang, "playlist.card", i18n.Args{
|
|
"Title": shorten(pl.Title, 120), "Count": len(pl.Entries), "Take": take,
|
|
})
|
|
var row []telego.InlineKeyboardButton
|
|
for _, p := range []media.Profile{media.Best, media.P720, media.P480, media.MP3} {
|
|
row = append(row, button(b.profileLabel(lang, p), cbData(cbPlaylist, req.ID, string(p))))
|
|
}
|
|
kb := keyboard(row, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, req.ID))})
|
|
_ = b.edit(ctx, lr.chatID, messageID, false, text, kb)
|
|
}
|
|
|
|
func playlistTake(entries, cap int) int {
|
|
if cap > 0 && entries > cap {
|
|
return cap
|
|
}
|
|
return entries
|
|
}
|
|
|
|
// cbPlaylistStart turns the chosen playlist into waiting items. Each item
|
|
// becomes its own request, job and cache entry, and they start one after
|
|
// another as the requester's job slots free up.
|
|
func (b *Bot) cbPlaylistStart(ctx context.Context, q *telego.CallbackQuery, act actor, requestID, profileArg string) {
|
|
req, err := b.store.GetRequest(ctx, requestID)
|
|
if err != nil {
|
|
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
|
return
|
|
}
|
|
if req.UserID != act.user.ID {
|
|
b.answer(ctx, q, b.tr.T(act.lang, "notice.not_yours", nil), false)
|
|
return
|
|
}
|
|
profile, perr := media.Parse(profileArg)
|
|
pl, plerr := service.ParsePlaylist(req.Info)
|
|
if perr != nil || plerr != nil || len(pl.Entries) == 0 {
|
|
b.answer(ctx, q, b.tr.T(act.lang, "notice.expired", nil), false)
|
|
return
|
|
}
|
|
dec, err := b.svc.Entitlement(ctx, service.Who{UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType}, false)
|
|
if err != nil {
|
|
b.answer(ctx, q, b.tr.T(act.lang, "error.internal", nil), true)
|
|
return
|
|
}
|
|
took, err := b.store.TransitionRequest(ctx, req.ID, db.RequestReady, db.RequestChosen)
|
|
if err != nil || !took {
|
|
b.answer(ctx, q, b.tr.T(act.lang, "notice.already_chosen", nil), false)
|
|
return
|
|
}
|
|
take := playlistTake(len(pl.Entries), dec.Limits.PlaylistItems)
|
|
base := time.Now()
|
|
for i, e := range pl.Entries[:take] {
|
|
item := &db.Request{
|
|
// Increasing timestamps keep the items in playlist order.
|
|
ID: ids.NewAt(base.Add(time.Duration(i) * time.Millisecond)),
|
|
UserID: req.UserID, ChatID: req.ChatID, ChatType: req.ChatType,
|
|
SourceMessageID: req.SourceMessageID, URL: e.URL, Status: db.RequestWaiting,
|
|
Lang: req.Lang, ParentID: req.ID, Profile: string(profile),
|
|
}
|
|
if err := b.store.InsertRequest(ctx, item); err != nil {
|
|
b.log.Error("insert playlist item", "err", err)
|
|
}
|
|
}
|
|
b.answer(ctx, q, "", false)
|
|
cardID, isPhoto := cardMessage(q, req)
|
|
_ = b.edit(ctx, req.ChatID, cardID, isPhoto, b.tr.HTML(req.Lang, "playlist.queued", i18n.Args{
|
|
"Title": shorten(pl.Title, 120), "Count": take,
|
|
}), nil)
|
|
b.pumpSoon()
|
|
}
|
|
|
|
// pumpSoon asks the event loop to look for playlist items that can start.
|
|
func (b *Bot) pumpSoon() {
|
|
select {
|
|
case b.pump <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
|
|
// pumpPlaylists starts waiting playlist items for users who have a free
|
|
// job slot. It looks at one item per user, so one long playlist cannot
|
|
// hold up others.
|
|
func (b *Bot) pumpPlaylists(ctx context.Context) {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
items, err := b.store.WaitingRequests(ctx, 50)
|
|
if err != nil {
|
|
b.log.Error("list waiting playlist items", "err", err)
|
|
return
|
|
}
|
|
for _, item := range items {
|
|
b.statusMu.Lock()
|
|
busy := b.pumping[item.UserID]
|
|
if !busy {
|
|
b.pumping[item.UserID] = true
|
|
}
|
|
b.statusMu.Unlock()
|
|
if busy {
|
|
continue
|
|
}
|
|
item := item
|
|
b.goBG("playlist-item", func() {
|
|
defer func() {
|
|
b.statusMu.Lock()
|
|
delete(b.pumping, item.UserID)
|
|
b.statusMu.Unlock()
|
|
}()
|
|
if b.startPlaylistItem(ctx, item) {
|
|
b.pumpSoon() // maybe the next one fits too
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// startPlaylistItem tries to start one item. It reports whether the item
|
|
// left the waiting state, in which case the next one may be tried.
|
|
func (b *Bot) startPlaylistItem(ctx context.Context, item *db.Request) bool {
|
|
who := service.Who{UserID: item.UserID, ChatID: item.ChatID, ChatType: item.ChatType}
|
|
dec, err := b.svc.Entitlement(ctx, who, false)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if dec.Limits.ActiveJobs > 0 {
|
|
n, err := b.store.CountActiveDeliveries(ctx, item.UserID)
|
|
if err != nil || n >= dec.Limits.ActiveJobs {
|
|
return false // no free slot yet: stay in line
|
|
}
|
|
}
|
|
began := time.Now()
|
|
took, err := b.store.TransitionRequest(ctx, item.ID, db.RequestWaiting, db.RequestChosen)
|
|
if err != nil || !took {
|
|
return false
|
|
}
|
|
// cancelledSince reports a /cancel that arrived while this item was
|
|
// being prepared. The item was no longer "waiting", so the command
|
|
// could not see it.
|
|
cancelledSince := func() bool {
|
|
b.statusMu.Lock()
|
|
defer b.statusMu.Unlock()
|
|
return b.cancelledAt[item.UserID].After(began)
|
|
}
|
|
lang := item.Lang
|
|
fail := func(title, reason string) bool {
|
|
if _, err := b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestFailed); err != nil {
|
|
b.log.Error("fail playlist item", "err", err)
|
|
}
|
|
_, _ = b.send(ctx, item.ChatID, item.SourceMessageID, b.tr.HTML(lang, "playlist.item_failed", i18n.Args{
|
|
"Title": shorten(title, 80), "Reason": reason,
|
|
}), nil)
|
|
return true
|
|
}
|
|
profile, perr := media.Parse(item.Profile)
|
|
probed, err := b.svc.ProbeAny(ctx, item.URL)
|
|
switch {
|
|
case ctx.Err() != nil:
|
|
// Shutting down: put it back for the next start.
|
|
_, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestWaiting)
|
|
return false
|
|
case perr != nil:
|
|
return fail(item.URL, b.tr.T(lang, "error.internal", nil))
|
|
case err != nil:
|
|
return fail(item.URL, html.UnescapeString(b.probeErrorText(lang, err)))
|
|
case probed.Info == nil:
|
|
return fail(item.URL, b.tr.T(lang, "error.playlist_nested", nil))
|
|
}
|
|
if cancelledSince() {
|
|
_, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestCancelled)
|
|
return false
|
|
}
|
|
info := probed.Info
|
|
if err := b.store.SetRequestInfo(ctx, item.ID, info.JSON()); err != nil {
|
|
b.log.Error("save playlist item info", "err", err)
|
|
}
|
|
item.Info = info.JSON()
|
|
msg, err := b.send(ctx, item.ChatID, item.SourceMessageID, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "status.preparing", nil), nil)
|
|
if err != nil {
|
|
return fail(info.Title, b.tr.T(lang, "error.internal", nil))
|
|
}
|
|
job, _, err := b.svc.Start(ctx, service.StartParams{
|
|
Request: item, Info: info, Profile: profile,
|
|
StatusMessageID: int64(msg.MessageID), ReplyToMessageID: item.SourceMessageID,
|
|
})
|
|
if err != nil {
|
|
var le *service.LimitError
|
|
if errors.As(err, &le) && le.Code == service.LimitActiveJobs {
|
|
// Lost the slot to another download: wait for the next one.
|
|
b.deleteMessage(ctx, item.ChatID, int64(msg.MessageID))
|
|
_, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestWaiting)
|
|
return false
|
|
}
|
|
_, _ = b.store.TransitionRequest(context.WithoutCancel(ctx), item.ID, db.RequestChosen, db.RequestFailed)
|
|
_ = b.edit(ctx, item.ChatID, int64(msg.MessageID), false,
|
|
titleLine(info.Title)+"\n"+html.EscapeString(b.startErrorText(lang, err)), nil)
|
|
return true
|
|
}
|
|
b.refreshStatus(ctx, job.ID)
|
|
return true
|
|
}
|
|
|
|
// --- subtitles ---------------------------------------------------------------
|
|
|
|
// subsCard lists the subtitle languages of a video as buttons, with the
|
|
// requester's own language first.
|
|
func (b *Bot) subsCard(ctx context.Context, lr linkRequest, messageID int64, req *db.Request, info *service.CardInfo) {
|
|
lang := lr.act.lang
|
|
type entry struct {
|
|
code string
|
|
auto bool
|
|
}
|
|
var all []entry
|
|
for _, c := range info.SubLangs {
|
|
all = append(all, entry{c, false})
|
|
}
|
|
for _, c := range info.AutoSubLangs {
|
|
all = append(all, entry{c, true})
|
|
}
|
|
if len(all) == 0 {
|
|
_ = b.edit(ctx, lr.chatID, messageID, false, titleLine(info.Title)+"\n"+b.tr.HTML(lang, "subs.none", nil), nil)
|
|
return
|
|
}
|
|
// The requester's language goes first, written before automatic.
|
|
mine := strings.ToLower(strings.SplitN(lang, "-", 2)[0])
|
|
isMine := func(code string) bool {
|
|
return strings.ToLower(strings.SplitN(code, "-", 2)[0]) == mine
|
|
}
|
|
var first, rest []entry
|
|
for _, e := range all {
|
|
if isMine(e.code) {
|
|
first = append(first, e)
|
|
} else {
|
|
rest = append(rest, e)
|
|
}
|
|
}
|
|
ordered := append(first, rest...)
|
|
const maxLangs = 24
|
|
if len(ordered) > maxLangs {
|
|
ordered = ordered[:maxLangs]
|
|
}
|
|
var rows [][]telego.InlineKeyboardButton
|
|
var row []telego.InlineKeyboardButton
|
|
for _, e := range ordered {
|
|
p := media.Subs(e.code)
|
|
if _, err := media.Parse(string(p)); err != nil {
|
|
continue // a language code that is not safe to pass on
|
|
}
|
|
label := e.code
|
|
if e.auto {
|
|
label = b.tr.T(lang, "btn.subs_auto", i18n.Args{"Lang": e.code})
|
|
}
|
|
if isMine(e.code) {
|
|
label = "✓ " + label
|
|
}
|
|
row = append(row, button(label, cbData(cbDownload, req.ID, string(p))))
|
|
if len(row) == 3 {
|
|
rows = append(rows, row)
|
|
row = nil
|
|
}
|
|
}
|
|
rows = append(rows, row, []telego.InlineKeyboardButton{button(b.tr.T(lang, "btn.cancel", nil), cbData(cbCancelCard, req.ID))})
|
|
_ = 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.
|
|
func (b *Bot) cbResendFile(ctx context.Context, q *telego.CallbackQuery, act actor, deliveryID string) {
|
|
lang := act.lang
|
|
old, err := b.store.GetDelivery(ctx, deliveryID)
|
|
if err != nil || old.UserID != act.user.ID {
|
|
b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false)
|
|
return
|
|
}
|
|
job, jerr := b.store.GetJob(ctx, old.JobID)
|
|
orig, rerr := b.store.GetRequest(ctx, old.RequestID)
|
|
if jerr != nil || rerr != nil {
|
|
b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false)
|
|
return
|
|
}
|
|
info, ierr := service.ParseCardInfo(orig.Info)
|
|
profile, perr := media.Parse(job.Profile)
|
|
if ierr != nil || perr != nil {
|
|
b.answer(ctx, q, b.tr.T(lang, "notice.expired", nil), false)
|
|
return
|
|
}
|
|
chat, chatType := act.user.ID, telego.ChatTypePrivate
|
|
if q.Message != nil {
|
|
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)
|
|
}
|
|
}
|
|
|
|
// --- owner: cache ------------------------------------------------------------
|
|
|
|
// isOwner reports whether a message is an owner command: sent by a
|
|
// configured owner, in a private chat.
|
|
func (b *Bot) isOwner(m *telego.Message) bool {
|
|
return m.From != nil && isPrivate(m.Chat.Type) && b.cfg.IsOwner(m.From.ID)
|
|
}
|
|
|
|
// cmdPurge is the takedown command: /purge <link> or /purge extractor:id.
|
|
func (b *Bot) cmdPurge(ctx context.Context, m *telego.Message, act actor) {
|
|
lang := act.lang
|
|
arg := commandArgs(m)
|
|
if arg == "" {
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purge_usage", nil), nil)
|
|
return
|
|
}
|
|
target, reason, _ := strings.Cut(arg, " ")
|
|
b.goBG("purge", func() {
|
|
var extractor, videoID string
|
|
if urls := messageLinks(m); len(urls) > 0 {
|
|
info, err := b.svc.Probe(ctx, urls[0])
|
|
if err != nil {
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.probeErrorText(lang, err), nil)
|
|
return
|
|
}
|
|
extractor, videoID = cache.Canonical(info.Extractor, info.VideoID, urls[0])
|
|
b.cache.MetaDrop(urls[0])
|
|
} else {
|
|
var ok bool
|
|
if extractor, videoID, ok = strings.Cut(target, ":"); !ok || extractor == "" || videoID == "" {
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purge_usage", nil), nil)
|
|
return
|
|
}
|
|
}
|
|
n, err := b.cache.Purge(ctx, extractor, videoID, strings.TrimSpace(reason), act.user.ID)
|
|
if err != nil {
|
|
b.internalError(ctx, m.Chat.ID, act, err)
|
|
return
|
|
}
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.purged", i18n.Args{
|
|
"Key": extractor + ":" + videoID, "Count": n,
|
|
}), nil)
|
|
})
|
|
}
|
|
|
|
func (b *Bot) cmdCache(ctx context.Context, m *telego.Message, act actor) {
|
|
lang := act.lang
|
|
sum, err := b.cache.Summary(ctx)
|
|
if err != nil {
|
|
b.internalError(ctx, m.Chat.ID, act, err)
|
|
return
|
|
}
|
|
st := b.cache.Stats()
|
|
rate := "0%"
|
|
if total := st.Hits + st.Misses; total > 0 {
|
|
rate = b.tr.Percent(lang, float64(st.Hits)/float64(total))
|
|
}
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.cache", i18n.Args{
|
|
"Entries": b.tr.Number(lang, sum.Entries),
|
|
"Stored": b.tr.Number(lang, sum.Stored),
|
|
"Size": b.tr.Size(lang, sum.Bytes),
|
|
"Budget": b.capSize(lang, b.cfg.Cache.BudgetMB<<20),
|
|
"Hits": b.tr.Number(lang, sum.Hits),
|
|
"Blocked": b.tr.Number(lang, sum.Blocked),
|
|
"Rate": rate,
|
|
"Saved": b.tr.Size(lang, st.BytesSaved),
|
|
"Since": strconv.FormatInt(st.Hits+st.Misses, 10),
|
|
}), nil)
|
|
}
|
|
|
|
// --- owner: workers ----------------------------------------------------------
|
|
|
|
func (b *Bot) cmdWorkers(ctx context.Context, m *telego.Message, act actor) {
|
|
lang := act.lang
|
|
ws, err := b.store.ListWorkers(ctx)
|
|
if err != nil {
|
|
b.internalError(ctx, m.Chat.ID, act, err)
|
|
return
|
|
}
|
|
running, _ := b.store.RunningByWorker(ctx)
|
|
var sb strings.Builder
|
|
sb.WriteString(b.tr.HTML(lang, "owner.workers_header", i18n.Args{
|
|
"Slots": b.sched.Capacity(), "Count": len(ws),
|
|
}))
|
|
if b.cfg.Worker.Embedded {
|
|
sb.WriteString("\n")
|
|
sb.WriteString(b.tr.HTML(lang, "owner.worker_embedded", i18n.Args{
|
|
"Capacity": b.cfg.Worker.Concurrency, "Running": running["embedded"],
|
|
}))
|
|
}
|
|
now := time.Now()
|
|
for _, w := range ws {
|
|
state := "owner.state_active"
|
|
switch {
|
|
case w.Revoked:
|
|
state = "owner.state_revoked"
|
|
case w.Draining:
|
|
state = "owner.state_draining"
|
|
case w.LastSeenAt == 0 || now.Sub(time.UnixMilli(w.LastSeenAt)) > 2*time.Minute:
|
|
state = "owner.state_offline"
|
|
}
|
|
seen := b.tr.T(lang, "owner.never", nil)
|
|
if w.LastSeenAt > 0 {
|
|
seen = b.tr.Span(lang, now.Sub(time.UnixMilli(w.LastSeenAt)))
|
|
}
|
|
tags := w.Tags
|
|
if tags == "" {
|
|
tags = "-"
|
|
}
|
|
sb.WriteString("\n")
|
|
sb.WriteString(b.tr.HTML(lang, "owner.worker_line", i18n.Args{
|
|
"Name": w.ID, "State": b.tr.T(lang, state, nil), "Running": running[w.ID], "Capacity": w.Capacity,
|
|
"Seen": seen, "Tags": tags, "Version": w.Version,
|
|
}))
|
|
}
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, sb.String(), nil)
|
|
}
|
|
|
|
// cmdDrain handles /drain <worker> and /drain <worker> off. A draining
|
|
// worker finishes its jobs and is given no new ones.
|
|
func (b *Bot) cmdDrain(ctx context.Context, m *telego.Message, act actor) {
|
|
lang := act.lang
|
|
fields := strings.Fields(commandArgs(m))
|
|
if len(fields) == 0 || len(fields) > 2 || (len(fields) == 2 && fields[1] != "off" && fields[1] != "on") {
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.drain_usage", nil), nil)
|
|
return
|
|
}
|
|
drain := len(fields) == 1 || fields[1] == "on"
|
|
ok, err := b.store.SetWorkerDraining(ctx, fields[0], drain)
|
|
if err != nil {
|
|
b.internalError(ctx, m.Chat.ID, act, err)
|
|
return
|
|
}
|
|
key := "owner.drain_on"
|
|
switch {
|
|
case !ok:
|
|
key = "owner.worker_unknown"
|
|
case !drain:
|
|
key = "owner.drain_off"
|
|
}
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, key, i18n.Args{"Name": fields[0]}), nil)
|
|
}
|
|
|
|
// cmdYtDlp handles /ytdlp update: every live worker updates yt-dlp when
|
|
// it next asks for work.
|
|
func (b *Bot) cmdYtDlp(ctx context.Context, m *telego.Message, act actor) {
|
|
lang := act.lang
|
|
if strings.TrimSpace(commandArgs(m)) != "update" {
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.ytdlp_usage", nil), nil)
|
|
return
|
|
}
|
|
n := b.sched.Command(workerproto.CommandUpdateYtDlp)
|
|
_, _ = b.send(ctx, m.Chat.ID, 0, b.tr.HTML(lang, "owner.ytdlp_update", i18n.Args{"Count": n}), nil)
|
|
}
|