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, extractor, title, uploader, profile, hidden` 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, &d.Extractor, &d.Title, &d.Uploader, &d.Profile, &d.Hidden) 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, d.Extractor, d.Title, d.Uploader, d.Profile, d.Hidden) 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 { // What history shows is copied from the job now, when it is final. _, err := s.exec(ctx, `UPDATE deliveries SET status = 'sent', tg_file_id = ?, tg_message_id = ?, error_code = '', updated_at = ?, extractor = COALESCE((SELECT j.extractor FROM jobs j WHERE j.id = deliveries.job_id), ''), title = COALESCE((SELECT j.title FROM jobs j WHERE j.id = deliveries.job_id), ''), uploader = COALESCE((SELECT j.uploader FROM jobs j WHERE j.id = deliveries.job_id), ''), profile = COALESCE((SELECT j.profile FROM jobs j WHERE j.id = deliveries.job_id), '') 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 `+historyWhere+` ORDER BY created_at DESC, id DESC LIMIT ?`, userID, limit)) } // historyWhere selects the downloads history lists for a user: sent, not // removed from history, and not thumbnails, which are offered under their // video instead of as downloads of their own. const historyWhere = `user_id = ? AND status = 'sent' AND hidden = FALSE AND profile <> 'thumb'` // HistoryRow is one past download as /history lists it. type HistoryRow struct { DeliveryID string RequestID string Extractor string Title string Uploader string Profile string URL string Size int64 CreatedAt int64 } // HistoryPage returns one page of a user's history, newest first, and how // many downloads the history holds in all. func (s *Store) HistoryPage(ctx context.Context, userID int64, offset, limit int) ([]HistoryRow, int, error) { var total int if err := s.row(ctx, `SELECT COUNT(*) FROM deliveries WHERE `+historyWhere, userID).Scan(&total); err != nil { return nil, 0, err } rows, err := s.rows(ctx, `SELECT d.id, d.request_id, d.extractor, d.title, d.uploader, d.profile, COALESCE(j.url, ''), COALESCE(j.file_size, 0), d.created_at FROM deliveries d LEFT JOIN jobs j ON j.id = d.job_id WHERE d.user_id = ? AND d.status = 'sent' AND d.hidden = FALSE AND d.profile <> 'thumb' ORDER BY d.created_at DESC, d.id DESC LIMIT ? OFFSET ?`, userID, limit, offset) if err != nil { return nil, 0, err } defer rows.Close() var out []HistoryRow for rows.Next() { var r HistoryRow if err := rows.Scan(&r.DeliveryID, &r.RequestID, &r.Extractor, &r.Title, &r.Uploader, &r.Profile, &r.URL, &r.Size, &r.CreatedAt); err != nil { return nil, 0, err } out = append(out, r) } return out, total, rows.Err() } // HideFromHistory removes one download from a user's history. It reports // whether the download was there. func (s *Store) HideFromHistory(ctx context.Context, userID int64, deliveryID string) (bool, error) { n, err := s.exec(ctx, `UPDATE deliveries SET hidden = TRUE WHERE id = ? AND user_id = ? AND hidden = FALSE`, deliveryID, userID) return n == 1, err } // ClearHistory removes every download from a user's history and returns // how many there were. func (s *Store) ClearHistory(ctx context.Context, userID int64) (int64, error) { return s.exec(ctx, `UPDATE deliveries SET hidden = TRUE WHERE user_id = ? AND status = 'sent' AND hidden = FALSE`, userID) } // 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() }