- One message per job: the status message is deleted once the file is
sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
throttled to one per 2.5 s per message; a state that arrives too soon
is shown later instead of dropped. The wait estimate is 0 with a free
slot.
- Caption with title (uploader and date when generic), uploader,
duration, a short source link without tracking parameters and an
optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
fallback to English is logged as a bug; a test walks every screen in
Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
"best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
"already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
language.
- Personal /settings in private chats with an "Add me to a group"
button.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
204 lines
8.0 KiB
Go
204 lines
8.0 KiB
Go
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, source, wallet_id, charge_sats, quota_day, released,
|
|
max_size, max_duration`
|
|
|
|
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)
|
|
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
|
|
if d.Source == "" {
|
|
d.Source = "free"
|
|
}
|
|
_, 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, d.Source, d.WalletID, d.ChargeSats, d.QuotaDay, d.Released,
|
|
d.MaxSize, d.MaxDuration)
|
|
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()
|
|
}
|
|
|
|
// MarkDeliveryReleased flags a delivery as refunded and reports whether
|
|
// this call was the one that flagged it. It is the idempotency guard for
|
|
// giving back a charge and a quota slot.
|
|
func (s *Store) MarkDeliveryReleased(ctx context.Context, id string) (bool, error) {
|
|
n, err := s.exec(ctx, `UPDATE deliveries SET released = ?, updated_at = ? WHERE id = ? AND released = ?`,
|
|
true, NowMilli(), id, false)
|
|
return n == 1, err
|
|
}
|
|
|
|
// UnreleasedDeliveries lists deliveries that ended without a file and have
|
|
// not been refunded yet. It is the safety net behind the refund events.
|
|
func (s *Store) UnreleasedDeliveries(ctx context.Context, limit int) ([]*Delivery, error) {
|
|
return scanDeliveries(s.rows(ctx, `SELECT `+deliveryCols+` FROM deliveries
|
|
WHERE status IN ('failed', 'cancelled') AND released = ?
|
|
AND (charge_sats > 0 OR quota_day > 0) ORDER BY id LIMIT ?`, false, limit))
|
|
}
|
|
|
|
// CountDeliveriesForRequest counts the deliveries created from a request.
|
|
func (s *Store) CountDeliveriesForRequest(ctx context.Context, requestID string) (int, error) {
|
|
var n int
|
|
err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE request_id = ?`, requestID).Scan(&n)
|
|
return n, err
|
|
}
|
|
|
|
// 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))
|
|
}
|
|
|
|
// RecentDelivery is a file a user got lately, with the link it came from.
|
|
type RecentDelivery struct {
|
|
DeliveryID string
|
|
URL string
|
|
Title string
|
|
}
|
|
|
|
// RecentSent lists the files a user was sent in a chat since a moment,
|
|
// newest first, with the link of the request each one answered.
|
|
func (s *Store) RecentSent(ctx context.Context, userID, chatID, since int64, limit int) ([]RecentDelivery, error) {
|
|
rows, err := s.rows(ctx, `SELECT d.id, r.url, j.title FROM deliveries d
|
|
JOIN requests r ON r.id = d.request_id
|
|
JOIN jobs j ON j.id = d.job_id
|
|
WHERE d.user_id = ? AND d.chat_id = ? AND d.status = 'sent' AND d.updated_at >= ?
|
|
ORDER BY d.updated_at DESC, d.id DESC LIMIT ?`, userID, chatID, since, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []RecentDelivery
|
|
for rows.Next() {
|
|
var r RecentDelivery
|
|
if err := rows.Scan(&r.DeliveryID, &r.URL, &r.Title); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, r)
|
|
}
|
|
return out, rows.Err()
|
|
}
|