// Package groups holds what the bot and the Mini App share about group // chats: who is an admin, and how site lists are matched. package groups import ( "context" "strings" "sync" "time" "github.com/mymmrac/telego" "github.com/noderunners/dlbot/internal/tg" ) // Admins answers "is this user an admin of this chat" by asking Telegram // (getChatMember) and remembering the answer for a few minutes. Admin // rights are never taken from anything a client sends. type Admins struct { api tg.API ttl time.Duration now func() time.Time mu sync.Mutex cache map[[2]int64]entry } type entry struct { admin bool at time.Time } // NewAdmins creates a checker. A ttl of 0 uses five minutes. func NewAdmins(api tg.API, ttl time.Duration) *Admins { if ttl <= 0 { ttl = 5 * time.Minute } return &Admins{api: api, ttl: ttl, now: time.Now, cache: map[[2]int64]entry{}} } // IsAdmin reports whether the user is the creator or an administrator of // the chat. When Telegram cannot be asked the answer is no. func (a *Admins) IsAdmin(ctx context.Context, chatID, userID int64) bool { key := [2]int64{chatID, userID} a.mu.Lock() if e, ok := a.cache[key]; ok && a.now().Sub(e.at) < a.ttl { a.mu.Unlock() return e.admin } a.mu.Unlock() m, err := a.api.GetChatMember(ctx, &telego.GetChatMemberParams{ChatID: telego.ChatID{ID: chatID}, UserID: userID}) if err != nil { return false // not cached: a later call may succeed } status := m.MemberStatus() admin := status == telego.MemberStatusCreator || status == telego.MemberStatusAdministrator a.mu.Lock() if len(a.cache) > 20000 { a.cache = map[[2]int64]entry{} } a.cache[key] = entry{admin: admin, at: a.now()} a.mu.Unlock() return admin } // Forget drops what is remembered about a chat, for example after the // bot's own status in it changed. func (a *Admins) Forget(chatID int64) { a.mu.Lock() defer a.mu.Unlock() for k := range a.cache { if k[0] == chatID { delete(a.cache, k) } } } // HostInList reports whether a site is covered by a list of hosts. An // entry covers the host itself and its subdomains. 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 } // CleanHost turns what an admin typed (a host, or a whole link) into a // bare host name, or "" when it is not one. func CleanHost(s string) string { s = strings.ToLower(strings.TrimSpace(s)) s = strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://") if i := strings.IndexAny(s, "/?#"); i >= 0 { s = s[:i] } s = strings.TrimPrefix(strings.TrimPrefix(s, "www."), "m.") if s == "" || !strings.Contains(s, ".") || strings.ContainsAny(s, " ,:@") { return "" } return s } // IsGroup reports whether a Telegram chat type is a group. func IsGroup(chatType string) bool { return chatType == telego.ChatTypeGroup || chatType == telego.ChatTypeSupergroup }