Phase 1: core bot

Link in, card, download, send, in private chats and groups.

- cmd/core with an embedded download worker
- Telegram front end on telego v1.13.0 (Bot API 10.4): link card with
  thumbnail and format buttons, one live status message, /dl /audio /thumb
  /info /queue /cancel, group support with requester-only buttons
- Database backed queue: paid and free lanes, leases with heartbeats, one
  automatic retry, cancel, queue position and wait estimate
- yt-dlp and ffprobe behind a Runner interface with classified, redacted
  errors mapped to friendly messages
- SQLite via modernc with goose migrations, portable schema
- Local file storage behind a Storage interface
- go-i18n with an English catalog, no literal text in handlers
- Free tier limits enforced before queueing and again on the real file
- Bot token and webhook secret are stripped from all log output
- Tests: URL parsing, job lifecycle, worker, yt-dlp wrapper, and end to end
  flows against a fake Bot API server; opt-in test with the real yt-dlp

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 07:33:32 +00:00
co-authored by Claude Fable 5.2
commit 3b361c17a1
63 changed files with 10715 additions and 0 deletions
+137
View File
@@ -0,0 +1,137 @@
package db
import (
"context"
"database/sql"
)
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`
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)
if err != nil {
return nil, notFound(err)
}
return &d, nil
}
func scanDeliveries(rows *sql.Rows, err error) ([]*Delivery, error) {
if err != nil {
return nil, err
}
defer rows.Close()
var out []*Delivery
for rows.Next() {
d, err := scanDelivery(rows)
if err != nil {
return nil, err
}
out = append(out, d)
}
return out, rows.Err()
}
// InsertDelivery stores a new delivery.
func (s *Store) InsertDelivery(ctx context.Context, d *Delivery) error {
if d.CreatedAt == 0 {
d.CreatedAt = NowMilli()
}
d.UpdatedAt = d.CreatedAt
_, err := s.exec(ctx, `INSERT INTO deliveries (`+deliveryCols+`)
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)
return err
}
// GetDelivery loads a delivery.
func (s *Store) GetDelivery(ctx context.Context, id string) (*Delivery, error) {
return scanDelivery(s.row(ctx, `SELECT `+deliveryCols+` FROM deliveries WHERE id = ?`, id))
}
// DeliveriesForJob lists the deliveries of a job in the given statuses.
func (s *Store) DeliveriesForJob(ctx context.Context, jobID string, statuses ...string) ([]*Delivery, error) {
ph, args := in(statuses)
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE job_id = ? AND status IN (`+ph+`) ORDER BY id`, append([]any{jobID}, args...)...))
}
// ActiveDeliveriesForUser lists a user's deliveries that are still waiting.
func (s *Store) ActiveDeliveriesForUser(ctx context.Context, userID int64) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE user_id = ? AND status IN ('pending', 'sending') ORDER BY id`, userID))
}
// CountActiveDeliveries counts a user's waiting deliveries.
func (s *Store) CountActiveDeliveries(ctx context.Context, userID int64) (int, error) {
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE user_id = ? AND status IN ('pending', 'sending')`,
userID).Scan(&n)
return n, err
}
// CountDeliveriesInStatus counts the deliveries of a job in the statuses.
func (s *Store) CountDeliveriesInStatus(ctx context.Context, jobID string, statuses ...string) (int, error) {
ph, args := in(statuses)
var n int
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE job_id = ? AND status IN (`+ph+`)`,
append([]any{jobID}, args...)...).Scan(&n)
return n, err
}
// TransitionDelivery moves a delivery between statuses and reports whether
// the row was in the expected status.
func (s *Store) TransitionDelivery(ctx context.Context, id, from, to, errorCode string) (bool, error) {
n, err := s.exec(ctx, `UPDATE deliveries SET status = ?, error_code = ?, updated_at = ?,
attempts = attempts + CASE WHEN ? = 'sending' THEN 1 ELSE 0 END
WHERE id = ? AND status = ?`, to, errorCode, NowMilli(), to, id, from)
return n == 1, err
}
// MarkDeliverySent records the Telegram file and message of a delivery.
func (s *Store) MarkDeliverySent(ctx context.Context, id, fileID string, messageID int64) error {
_, 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)
return err
}
// SetDeliveryStatusMessage records which message shows the live status.
func (s *Store) SetDeliveryStatusMessage(ctx context.Context, id string, messageID int64, isPhoto bool) error {
_, err := s.exec(ctx, `UPDATE deliveries SET status_message_id = ?, status_is_photo = ?, updated_at = ?
WHERE id = ?`, messageID, isPhoto, NowMilli(), id)
return err
}
// StaleSendingDeliveries lists deliveries stuck in sending since before the
// cutoff, which happens when the core stops in the middle of an upload.
func (s *Store) StaleSendingDeliveries(ctx context.Context, before int64) ([]*Delivery, error) {
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
WHERE status = 'sending' AND updated_at < ? ORDER BY id`, before))
}
// PendingDeliveryJobIDs lists the jobs in a status that still have pending
// deliveries. The core uses it to resume work after a restart.
func (s *Store) PendingDeliveryJobIDs(ctx context.Context, jobStatus string, limit int) ([]string, error) {
rows, err := s.rows(ctx, `SELECT DISTINCT j.id FROM jobs j
JOIN deliveries d ON d.job_id = j.id
WHERE j.status = ? AND d.status = 'pending' ORDER BY j.id LIMIT ?`, jobStatus, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, err
}
out = append(out, id)
}
return out, rows.Err()
}