90 lines
2.3 KiB
Go
90 lines
2.3 KiB
Go
package access
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/mymmrac/telego"
|
|
th "github.com/mymmrac/telego/telegohandler"
|
|
|
|
"git.entityseven.com/rilaxik/pllist/internal/service"
|
|
"git.entityseven.com/rilaxik/pllist/internal/telegram/shared"
|
|
)
|
|
|
|
type Handler struct {
|
|
sender *shared.Sender
|
|
access *service.BotAccessService
|
|
}
|
|
|
|
func New(sender *shared.Sender, access *service.BotAccessService) *Handler {
|
|
return &Handler{sender: sender, access: access}
|
|
}
|
|
|
|
func (h *Handler) Register(router *th.BotHandler) {
|
|
router.HandleMessage(h.allow, th.CommandEqual("allow"))
|
|
router.HandleMessage(h.kick, th.CommandEqual("kick"))
|
|
}
|
|
|
|
func (h *Handler) allow(ctx *th.Context, message telego.Message) error {
|
|
user := shared.UserFrom(ctx)
|
|
if !h.access.IsOwner(user.TelegramID) {
|
|
return h.sender.Send(ctx, message.Chat.ID, ownerOnlyText, nil)
|
|
}
|
|
|
|
created, target, err := h.access.Allow(ctx, user.TelegramID, commandArgument(message.Text))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
label := shared.Escape(targetLabel(target))
|
|
|
|
var text string
|
|
switch {
|
|
case created && target.Username != "":
|
|
text = fmt.Sprintf(
|
|
"Access granted to %s. It activates when they contact the bot.", label,
|
|
)
|
|
case created:
|
|
text = fmt.Sprintf("Access granted to %s.", label)
|
|
case h.access.IsOwner(target.TelegramID):
|
|
text = "You already have access."
|
|
default:
|
|
text = fmt.Sprintf("%s already has access or a pending grant.", label)
|
|
}
|
|
return h.sender.Send(ctx, message.Chat.ID, text, nil)
|
|
}
|
|
|
|
func (h *Handler) kick(ctx *th.Context, message telego.Message) error {
|
|
user := shared.UserFrom(ctx)
|
|
if !h.access.IsOwner(user.TelegramID) {
|
|
return h.sender.Send(ctx, message.Chat.ID, ownerOnlyText, nil)
|
|
}
|
|
|
|
revoked, target, err := h.access.Kick(ctx, user.TelegramID, commandArgument(message.Text))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
label := shared.Escape(targetLabel(target))
|
|
if !revoked {
|
|
return h.sender.Send(ctx, message.Chat.ID,
|
|
fmt.Sprintf("No access grant found for %s.", label), nil)
|
|
}
|
|
return h.sender.Send(ctx, message.Chat.ID,
|
|
fmt.Sprintf("Access revoked for %s.", label), nil)
|
|
}
|
|
|
|
func commandArgument(text string) string {
|
|
fields := strings.Fields(text)
|
|
if len(fields) < 2 {
|
|
return ""
|
|
}
|
|
return strings.Join(fields[1:], " ")
|
|
}
|
|
|
|
func targetLabel(target service.GrantTarget) string {
|
|
if target.Username != "" {
|
|
return "@" + target.Username
|
|
}
|
|
return strconv.FormatInt(target.TelegramID, 10)
|
|
}
|