Phase 5: groups

Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 09:46:32 +00:00
co-authored by Claude Fable 5.2
parent 7d4893bc3f
commit 51371da0e0
23 changed files with 3231 additions and 81 deletions
+177 -5
View File
@@ -155,8 +155,118 @@ const (
// LimitBlocked is a takedown by the owner: the video or its site is on
// the blocklist.
LimitBlocked = "blocked"
// Refusals from a group's own settings.
LimitGroupDisabled = "group_disabled"
LimitGroupAdminsOnly = "group_admins_only"
LimitGroupPassOnly = "group_pass_only"
LimitGroupSite = "group_site"
// LimitMaintenance is the owner's maintenance switch.
LimitMaintenance = "maintenance"
)
// AdminChecker says whether a user is an admin of a group chat.
type AdminChecker interface {
IsAdmin(ctx context.Context, chatID, userID int64) bool
}
// SetAdmins gives the service the means to check group admins. Until it
// is set nobody counts as an admin.
func (s *Service) SetAdmins(a AdminChecker) { s.admins = a }
// groupContext is what a request from a group is judged by.
type groupContext struct {
settings *db.GroupSettings
wallet entitle.Wallet
admin bool
// memberSpent and totalSpent are group credits spent today.
memberSpent, totalSpent int64
}
func isGroup(chatType string) bool { return chatType == "group" || chatType == "supergroup" }
func (s *Service) groupContext(ctx context.Context, who Who) (*groupContext, error) {
if !isGroup(who.ChatType) {
return nil, nil
}
gc := &groupContext{}
var err error
if gc.settings, err = s.store.GetGroupSettings(ctx, who.ChatID); err != nil {
return nil, err
}
if gc.wallet, err = s.billing.State(ctx, db.OwnerGroup, who.ChatID); err != nil {
return nil, err
}
if s.admins != nil {
gc.admin = s.admins.IsAdmin(ctx, who.ChatID, who.UserID)
}
if gc.memberSpent, gc.totalSpent, err = s.store.GroupSpent(ctx, who.ChatID, who.UserID, Day(s.now())); err != nil {
return nil, err
}
return gc, nil
}
// creditsAllowed applies the group's spending rule and caps to one more
// download by this member.
func (gc *groupContext) creditsAllowed(cost int64) bool {
st := gc.settings
if st.DailyCap > 0 && gc.totalSpent+cost > st.DailyCap {
return false
}
switch st.SpendRule {
case db.SpendAnyone:
return true
case db.SpendCapped:
return gc.memberSpent+cost <= st.SpendCap
default: // admins only
return gc.admin
}
}
// gate applies the group's own settings: whether the bot is on, who may
// use it, and which sites are allowed.
func (s *Service) gate(ctx context.Context, who Who, info *CardInfo, dec entitle.Decision, gc *groupContext) error {
if on, _ := s.store.GetKV(ctx, "maintenance"); on == "1" && !s.cfg.IsOwner(who.UserID) {
return &LimitError{Code: LimitMaintenance, Decision: dec}
}
if gc == nil {
return nil
}
st := gc.settings
refuse := func(code string) error { return &LimitError{Code: code, Decision: dec} }
if !st.Enabled {
return refuse(LimitGroupDisabled)
}
switch st.WhoCanUse {
case db.UseAdmins:
if !gc.admin {
return refuse(LimitGroupAdminsOnly)
}
case db.UsePassHolders:
if !gc.admin && dec.Source != entitle.OwnPass && dec.Source != entitle.GroupPass {
return refuse(LimitGroupPassOnly)
}
}
if info != nil && info.Site != "" {
if allowed := db.Sites(st.Allowed); len(allowed) > 0 && !hostInList(info.Site, allowed) {
return refuse(LimitGroupSite)
}
if hostInList(info.Site, db.Sites(st.Blocked)) {
return refuse(LimitGroupSite)
}
}
return nil
}
func hostInList(site string, list []string) bool {
site = strings.ToLower(site)
for _, h := range list {
if site == h || strings.HasSuffix(site, "."+h) {
return true
}
}
return false
}
// ErrPlaylist is returned by Probe for links that resolve to a list.
var ErrPlaylist = errors.New("service: link is a playlist")
@@ -168,6 +278,7 @@ type Service struct {
billing *billing.Billing
cache *cache.Cache
prober Prober
admins AdminChecker
log *slog.Logger
probes chan struct{}
now func() time.Time
@@ -281,6 +392,13 @@ type Who struct {
// which limits apply. oneOffPaid is true when an invoice for exactly this
// file was paid.
func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, error) {
dec, _, err := s.entitle(ctx, who, oneOffPaid)
return dec, err
}
// entitle resolves the entitlement and returns the group context it was
// resolved with, which is nil in a private chat.
func (s *Service) entitle(ctx context.Context, who Who, oneOffPaid bool) (entitle.Decision, *groupContext, error) {
in := entitle.Input{
Now: s.now().UnixMilli(),
OneOffPaid: oneOffPaid,
@@ -291,10 +409,22 @@ func (s *Service) Entitlement(ctx context.Context, who Who, oneOffPaid bool) (en
}
user, err := s.billing.State(ctx, db.OwnerUser, who.UserID)
if err != nil {
return entitle.Decision{}, err
return entitle.Decision{}, nil, err
}
in.User = user
return entitle.Resolve(in), nil
gc, err := s.groupContext(ctx, who)
if err != nil {
return entitle.Decision{}, nil, err
}
if gc != nil {
in.Group = &entitle.Group{
Wallet: gc.wallet,
CreditsAllowed: gc.creditsAllowed(in.CreditCost),
MaxSize: gc.settings.MaxSizeMB << 20,
MaxDuration: gc.settings.MaxDuration,
}
}
return entitle.Resolve(in), gc, nil
}
// Usage returns what the user consumed today.
@@ -347,7 +477,8 @@ func (s *Service) admit(ctx context.Context, who Who, info *CardInfo, profile me
func (s *Service) limitError(code string, info *CardInfo, profile media.Profile, dec entitle.Decision) *LimitError {
le := &LimitError{Code: code, Decision: dec, Size: info.Sizes[string(profile)]}
if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || dec.Source.Paid() || !s.billing.Enabled() {
if code == LimitLive || code == LimitQueueFull || code == LimitBlocked || strings.HasPrefix(code, "group_") ||
code == LimitMaintenance || dec.Source.Paid() || !s.billing.Enabled() {
return le
}
// Would the paid tier accept it? Only then is it worth offering.
@@ -416,10 +547,13 @@ func (s *Service) resolve(ctx context.Context, url string, info *CardInfo, profi
// queueing or charging anything. It returns *LimitError when a rule would
// refuse it.
func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardInfo, profile media.Profile) error {
dec, err := s.Entitlement(ctx, who, false)
dec, gc, err := s.entitle(ctx, who, false)
if err != nil {
return err
}
if err := s.gate(ctx, who, info, dec, gc); err != nil {
return err
}
r, err := s.resolve(ctx, url, info, profile, dec)
if err != nil {
return err
@@ -427,6 +561,16 @@ func (s *Service) Preview(ctx context.Context, who Who, url string, info *CardIn
return s.admit(ctx, who, r.view, profile, dec)
}
// Gate reports whether the requester may use the bot in this chat at all,
// before a link is even looked up. It returns *LimitError when not.
func (s *Service) Gate(ctx context.Context, who Who) error {
dec, gc, err := s.entitle(ctx, who, false)
if err != nil {
return err
}
return s.gate(ctx, who, nil, dec, gc)
}
// StartParams describes a download a requester asked for.
type StartParams struct {
Request *db.Request
@@ -462,10 +606,13 @@ func (s *Service) Start(ctx context.Context, p StartParams) (*db.Job, *db.Delive
}
func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Job, *db.Delivery, error) {
dec, err := s.Entitlement(ctx, who, p.OneOff != nil)
dec, gc, err := s.entitle(ctx, who, p.OneOff != nil)
if err != nil {
return nil, nil, err
}
if err := s.gate(ctx, who, p.Info, dec, gc); err != nil {
return nil, nil, err
}
r, err := s.resolve(ctx, p.Request.URL, p.Info, p.Profile, dec)
if err != nil {
return nil, nil, err
@@ -565,6 +712,17 @@ func (s *Service) startOnce(ctx context.Context, who Who, p StartParams) (*db.Jo
return err
}
}
if gc != nil {
// Per-member use of the group: the base for spending caps and
// for the usage-by-member view.
var sats int64
if dec.Source == entitle.GroupCredits {
sats = dec.Charge
}
if err := tx.AddGroupUsage(ctx, who.ChatID, who.UserID, day, 1, sats, 0); err != nil {
return err
}
}
return tx.AddUsage(ctx, who.UserID, day, 1, 0)
})
switch {
@@ -618,6 +776,15 @@ func (s *Service) Release(ctx context.Context, deliveryID string) (refunded int6
}
}
if d.QuotaDay > 0 {
if isGroup(d.ChatType) {
var sats int64
if d.Source == string(entitle.GroupCredits) {
sats = d.ChargeSats
}
if err := tx.AddGroupUsage(ctx, d.ChatID, d.UserID, d.QuotaDay, -1, -sats, 0); err != nil {
return err
}
}
return tx.AddUsage(ctx, d.UserID, d.QuotaDay, -1, 0)
}
return nil
@@ -649,6 +816,11 @@ func (s *Service) RecordDelivered(ctx context.Context, d *db.Delivery, bytes int
if day == 0 {
day = Day(s.now())
}
if isGroup(d.ChatType) {
if err := s.store.AddGroupUsage(ctx, d.ChatID, d.UserID, day, 0, 0, bytes); err != nil {
return err
}
}
return s.store.AddUsage(ctx, d.UserID, day, 0, bytes)
}