package db import ( "context" "database/sql" "errors" "strings" ) // Group is a chat the bot was added to. type Group struct { ChatID int64 Title string Type string BotStatus string // member, administrator, left, kicked AddedBy int64 CreatedAt int64 UpdatedAt int64 } // Present reports whether the bot is still in the group. func (g *Group) Present() bool { return g.BotStatus == "member" || g.BotStatus == "administrator" || g.BotStatus == "creator" || g.BotStatus == "restricted" } // Who may use the bot in a group. const ( UseEveryone = "everyone" UsePassHolders = "pass_holders" UseAdmins = "admins" ) // Who may spend the group's credits. const ( SpendAnyone = "anyone" SpendAdmins = "admins" SpendCapped = "capped" // anyone, up to a number of sats per person per day ) // GroupSettings are the per-group options admins control. type GroupSettings struct { ChatID int64 Enabled bool AutoDetect bool Allowed string // comma separated hosts; empty allows every site Blocked string // comma separated hosts WhoCanUse string MaxSizeMB int64 // 0 means "whatever the tier allows" MaxDuration int64 // seconds, 0 likewise SpendRule string SpendCap int64 // sats per person per day, for SpendCapped DailyCap int64 // sats per day for the whole group, 0 for no cap DeleteCmds bool Quality string // default profile, "" shows the card Lang string // "" follows each requester UpdatedAt int64 } // DefaultGroupSettings are the settings of a group nobody configured. func DefaultGroupSettings(chatID int64) *GroupSettings { return &GroupSettings{ChatID: chatID, Enabled: true, WhoCanUse: UseEveryone, SpendRule: SpendAdmins} } // Sites splits a comma separated host list. func Sites(list string) []string { var out []string for _, s := range strings.Split(list, ",") { if s = strings.ToLower(strings.TrimSpace(s)); s != "" { out = append(out, s) } } return out } // UpsertGroup records a group and the bot's status in it. func (s *Store) UpsertGroup(ctx context.Context, g *Group) error { now := NowMilli() _, err := s.exec(ctx, `INSERT INTO groups (chat_id, title, type, bot_status, added_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (chat_id) DO UPDATE SET title = CASE WHEN excluded.title <> '' THEN excluded.title ELSE groups.title END, type = excluded.type, bot_status = excluded.bot_status, updated_at = excluded.updated_at`, g.ChatID, g.Title, g.Type, g.BotStatus, g.AddedBy, now, now) return err } // GetGroup loads a group. func (s *Store) GetGroup(ctx context.Context, chatID int64) (*Group, error) { var g Group err := s.row(ctx, `SELECT chat_id, title, type, bot_status, added_by, created_at, updated_at FROM groups WHERE chat_id = ?`, chatID).Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy, &g.CreatedAt, &g.UpdatedAt) if err != nil { return nil, notFound(err) } return &g, nil } // GetGroupSettings loads a group's settings, or the defaults. func (s *Store) GetGroupSettings(ctx context.Context, chatID int64) (*GroupSettings, error) { g := DefaultGroupSettings(chatID) err := s.row(ctx, `SELECT enabled, auto_detect, allowed_sites, blocked_sites, who_can_use, max_size_mb, max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands, default_quality, lang, updated_at FROM group_settings WHERE chat_id = ?`, chatID).Scan(&g.Enabled, &g.AutoDetect, &g.Allowed, &g.Blocked, &g.WhoCanUse, &g.MaxSizeMB, &g.MaxDuration, &g.SpendRule, &g.SpendCap, &g.DailyCap, &g.DeleteCmds, &g.Quality, &g.Lang, &g.UpdatedAt) if errors.Is(err, sql.ErrNoRows) { return g, nil } return g, err } // SaveGroupSettings stores a group's settings. func (s *Store) SaveGroupSettings(ctx context.Context, g *GroupSettings) error { g.UpdatedAt = NowMilli() _, err := s.exec(ctx, `INSERT INTO group_settings (chat_id, enabled, auto_detect, allowed_sites, blocked_sites, who_can_use, max_size_mb, max_duration_s, spend_rule, spend_cap_sats, daily_cap_sats, delete_commands, default_quality, lang, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (chat_id) DO UPDATE SET enabled = excluded.enabled, auto_detect = excluded.auto_detect, allowed_sites = excluded.allowed_sites, blocked_sites = excluded.blocked_sites, who_can_use = excluded.who_can_use, max_size_mb = excluded.max_size_mb, max_duration_s = excluded.max_duration_s, spend_rule = excluded.spend_rule, spend_cap_sats = excluded.spend_cap_sats, daily_cap_sats = excluded.daily_cap_sats, delete_commands = excluded.delete_commands, default_quality = excluded.default_quality, lang = excluded.lang, updated_at = excluded.updated_at`, g.ChatID, g.Enabled, g.AutoDetect, g.Allowed, g.Blocked, g.WhoCanUse, g.MaxSizeMB, g.MaxDuration, g.SpendRule, g.SpendCap, g.DailyCap, g.DeleteCmds, g.Quality, g.Lang, g.UpdatedAt) return err } // AddGroupUsage adds to a member's counters in a group for a day. Negative // values give back. func (s *Store) AddGroupUsage(ctx context.Context, chatID, userID int64, day, downloads int, sats, bytes int64) error { _, err := s.exec(ctx, `INSERT INTO group_usage_daily (chat_id, user_id, day, downloads, sats, bytes) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (chat_id, user_id, day) DO UPDATE SET downloads = group_usage_daily.downloads + excluded.downloads, sats = group_usage_daily.sats + excluded.sats, bytes = group_usage_daily.bytes + excluded.bytes`, chatID, userID, day, downloads, sats, bytes) return err } // GroupSpent returns the group credits spent on a day: by one member and // by everyone. func (s *Store) GroupSpent(ctx context.Context, chatID, userID int64, day int) (member, total int64, err error) { var m, t sql.NullInt64 err = s.row(ctx, `SELECT SUM(CASE WHEN user_id = ? THEN sats ELSE 0 END), SUM(sats) FROM group_usage_daily WHERE chat_id = ? AND day = ?`, userID, chatID, day).Scan(&m, &t) return m.Int64, t.Int64, err } // MemberUsage is one member's use of a group over a period. type MemberUsage struct { UserID int64 Name string Downloads int64 Sats int64 Bytes int64 } // GroupUsage sums usage per member since a day, biggest first. func (s *Store) GroupUsage(ctx context.Context, chatID int64, sinceDay, limit int) ([]MemberUsage, error) { rows, err := s.rows(ctx, `SELECT g.user_id, COALESCE(u.first_name, ''), SUM(g.downloads), SUM(g.sats), SUM(g.bytes) FROM group_usage_daily g LEFT JOIN users u ON u.id = g.user_id WHERE g.chat_id = ? AND g.day >= ? GROUP BY g.user_id, u.first_name ORDER BY SUM(g.downloads) DESC, g.user_id LIMIT ?`, chatID, sinceDay, limit) if err != nil { return nil, err } defer rows.Close() var out []MemberUsage for rows.Next() { var m MemberUsage if err := rows.Scan(&m.UserID, &m.Name, &m.Downloads, &m.Sats, &m.Bytes); err != nil { return nil, err } out = append(out, m) } return out, rows.Err() } // SeeGroupUser records that a user was active in a group. func (s *Store) SeeGroupUser(ctx context.Context, chatID, userID int64) error { _, err := s.exec(ctx, `INSERT INTO group_users (chat_id, user_id, last_seen_at) VALUES (?, ?, ?) ON CONFLICT (chat_id, user_id) DO UPDATE SET last_seen_at = excluded.last_seen_at`, chatID, userID, NowMilli()) return err } // GroupsOfUser lists the groups a user was seen in where the bot still is. func (s *Store) GroupsOfUser(ctx context.Context, userID int64, limit int) ([]*Group, error) { rows, err := s.rows(ctx, `SELECT g.chat_id, g.title, g.type, g.bot_status, g.added_by, g.created_at, g.updated_at FROM groups g JOIN group_users gu ON gu.chat_id = g.chat_id WHERE gu.user_id = ? AND g.bot_status IN ('member', 'administrator', 'restricted') ORDER BY gu.last_seen_at DESC LIMIT ?`, userID, limit) if err != nil { return nil, err } defer rows.Close() var out []*Group for rows.Next() { var g Group if err := rows.Scan(&g.ChatID, &g.Title, &g.Type, &g.BotStatus, &g.AddedBy, &g.CreatedAt, &g.UpdatedAt); err != nil { return nil, err } out = append(out, &g) } return out, rows.Err() } // --- key-value ------------------------------------------------------------- // GetKV reads a value, or "" when the key is not set. func (s *Store) GetKV(ctx context.Context, key string) (string, error) { var v string err := s.row(ctx, `SELECT v FROM kv WHERE k = ?`, key).Scan(&v) if errors.Is(err, sql.ErrNoRows) { return "", nil } return v, err } // SetKV stores a value. func (s *Store) SetKV(ctx context.Context, key, value string) error { _, err := s.exec(ctx, `INSERT INTO kv (k, v) VALUES (?, ?) ON CONFLICT (k) DO UPDATE SET v = excluded.v`, key, value) return err } // --- users, extended ------------------------------------------------------- // SetUserQuality stores a user's default format. func (s *Store) SetUserQuality(ctx context.Context, userID int64, quality string) error { _, err := s.exec(ctx, `UPDATE users SET default_quality = ? WHERE id = ?`, quality, userID) return err } // SetUserLang stores the language a user chose, "" to follow Telegram. func (s *Store) SetUserLang(ctx context.Context, userID int64, lang string) error { _, err := s.exec(ctx, `UPDATE users SET lang_override = ? WHERE id = ?`, lang, userID) return err } // SetUserBanned bans or unbans a user and reports whether the user exists. func (s *Store) SetUserBanned(ctx context.Context, userID int64, banned bool) (bool, error) { n, err := s.exec(ctx, `UPDATE users SET banned = ? WHERE id = ?`, banned, userID) return n == 1, err } // CountUsers counts known users. func (s *Store) CountUsers(ctx context.Context) (int64, error) { var n int64 err := s.row(ctx, `SELECT COUNT(*) FROM users`).Scan(&n) return n, err } // UserIDs lists users for a broadcast, in ID order after a cursor. func (s *Store) UserIDs(ctx context.Context, after int64, limit int) ([]int64, error) { rows, err := s.rows(ctx, `SELECT id FROM users WHERE id > ? AND banned = ? ORDER BY id LIMIT ?`, after, false, limit) if err != nil { return nil, err } defer rows.Close() var out []int64 for rows.Next() { var id int64 if err := rows.Scan(&id); err != nil { return nil, err } out = append(out, id) } return out, rows.Err() } // JobCounts counts jobs by status that were created since a time. func (s *Store) JobCounts(ctx context.Context, since int64) (map[string]int64, error) { rows, err := s.rows(ctx, `SELECT status, COUNT(*) FROM jobs WHERE created_at >= ? GROUP BY status`, since) if err != nil { return nil, err } defer rows.Close() out := map[string]int64{} for rows.Next() { var st string var n int64 if err := rows.Scan(&st, &n); err != nil { return nil, err } out[st] = n } return out, rows.Err() } // ActiveJobs lists queued and running jobs in claim order. func (s *Store) ActiveJobs(ctx context.Context, limit int) ([]*Job, error) { return scanJobs(s.rows(ctx, `SELECT `+jobCols+` FROM jobs WHERE status IN ('queued', 'running') ORDER BY CASE status WHEN 'running' THEN 0 ELSE 1 END, `+queueOrder+` LIMIT ?`, limit)) } // SatsReceived sums purchases paid over Lightning. func (s *Store) SatsReceived(ctx context.Context) (int64, error) { var n sql.NullInt64 err := s.row(ctx, `SELECT SUM(amount_sats) FROM purchases WHERE status = 'paid' AND payment_method = 'lightning'`).Scan(&n) return n.Int64, err }