Files
slacker-bot/slackerbot/internal/commands/commands.go
T

297 lines
7.5 KiB
Go

package commands
import (
"errors"
"fmt"
"math"
"regexp"
"slices"
"strconv"
"strings"
"time"
"slackerbot/internal/model"
"slackerbot/internal/units"
)
var ErrNotCommand = errors.New("not a command")
var unitSpace = regexp.MustCompile(`(\d)\s+(tib|tb|t|gib|gb|g|mib|mb|m|cpus|cpu|cores|core)\b`)
var sizeToken = regexp.MustCompile(`^([+-]?)(\d+(?:\.\d+)?)(g|gb|gib|m|mb|mib|cpu|cpus|core|cores)$`)
func ParseScale(args string, cur model.Size) (model.Size, error) {
args = unitSpace.ReplaceAllString(strings.ToLower(args), "$1$2")
words := strings.Fields(args)
if len(words) == 0 {
return model.Size{MemoryMB: cur.MemoryMB * 2, CPUs: cur.CPUs * 2}, nil
}
if len(words) == 1 {
switch words[0] {
case "up", "out":
return model.Size{MemoryMB: cur.MemoryMB * 2, CPUs: cur.CPUs * 2}, nil
case "down", "in":
return model.Size{MemoryMB: cur.MemoryMB / 2, CPUs: cur.CPUs / 2}, nil
}
}
next := cur
var memDone, cpuDone bool
for i, w := range words {
parts := sizeToken.FindStringSubmatch(w)
if parts == nil {
if i == 0 {
return cur, ErrNotCommand
}
return cur, fmt.Errorf("I didn't understand `%s`", w)
}
sign, num, unit := parts[1], parts[2], parts[3]
n, _ := strconv.ParseFloat(num, 64)
if unit == "cpu" || unit == "cpus" || unit == "core" || unit == "cores" {
if cpuDone {
return cur, errors.New("CPU was given twice")
}
cpuDone = true
next.CPUs = apply(sign, cur.CPUs, n)
continue
}
if memDone {
return cur, errors.New("memory was given twice")
}
memDone = true
mb := n
if strings.HasPrefix(unit, "g") {
mb = n * 1024
}
next.MemoryMB = int(math.Round(apply(sign, float64(cur.MemoryMB), mb)))
}
return next, nil
}
func apply(sign string, cur, n float64) float64 {
switch sign {
case "+":
return cur + n
case "-":
return cur - n
}
return n
}
type KeepSetting struct {
Show bool
Reset bool
Indefinite bool
Limit time.Duration
}
var dayToken = regexp.MustCompile(`(\d+(?:\.\d+)?)([dw])`)
var wordUnit = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*(weeks?|wks?|days?|hours?|hrs?|minutes?|mins?)\b`)
func ParseKeep(args string) (KeepSetting, error) {
a := strings.ToLower(strings.TrimSpace(args))
switch a {
case "":
return KeepSetting{Show: true}, nil
case "default", "reset", "normal":
return KeepSetting{Reset: true}, nil
case "indefinite", "indefinitely", "forever", "alive", "running", "on":
return KeepSetting{Indefinite: true}, nil
}
d, err := parseDuration(a)
if err != nil {
return KeepSetting{}, ErrNotCommand
}
if d <= 0 {
return KeepSetting{}, errors.New("the time has to be more than zero")
}
return KeepSetting{Limit: d}, nil
}
func parseDuration(s string) (time.Duration, error) {
s = wordUnit.ReplaceAllStringFunc(s, func(m string) string {
p := wordUnit.FindStringSubmatch(m)
return p[1] + map[byte]string{'w': "w", 'd': "d", 'h': "h", 'm': "m"}[p[2][0]]
})
s = strings.ReplaceAll(s, " ", "")
s = dayToken.ReplaceAllStringFunc(s, func(m string) string {
p := dayToken.FindStringSubmatch(m)
n, _ := strconv.ParseFloat(p[1], 64)
hours := n * 24
if p[2] == "w" {
hours = n * 24 * 7
}
return strconv.FormatFloat(hours, 'f', -1, 64) + "h"
})
return time.ParseDuration(s)
}
func Human(d time.Duration) string {
d = d.Round(time.Minute)
days := d / (24 * time.Hour)
d -= days * 24 * time.Hour
out := ""
if days > 0 {
out = fmt.Sprintf("%dd", days)
}
if d > 0 {
r := strings.TrimSuffix(d.String(), "0s")
if strings.HasSuffix(r, "h0m") {
r = strings.TrimSuffix(r, "0m")
}
out += r
}
if out == "" {
out = "0m"
}
return out
}
func ParseStorage(args string, curMin, curMax int64) (min, max int64, err error) {
args = unitSpace.ReplaceAllString(strings.ToLower(args), "$1$2")
words := strings.Fields(args)
min, max = curMin, curMax
var minDone, maxDone bool
for i := 0; i < len(words); i++ {
target := "max"
switch words[i] {
case "min", "guarantee", "guaranteed", "reserve":
target = "min"
i++
case "max", "cap", "limit":
i++
}
if i >= len(words) {
return curMin, curMax, fmt.Errorf("%s needs a size after it, like `%s 10G`", target, target)
}
p := units.StorageToken.FindStringSubmatch(words[i])
if p == nil {
if i == 0 {
return curMin, curMax, ErrNotCommand
}
return curMin, curMax, fmt.Errorf("I didn't understand `%s`", words[i])
}
n := units.ToMB(p[2], p[3])
if target == "min" {
if minDone {
return curMin, curMax, errors.New("min was given twice")
}
minDone = true
min = int64(apply(p[1], float64(curMin), float64(n)))
} else {
if maxDone {
return curMin, curMax, errors.New("max was given twice")
}
maxDone = true
max = int64(apply(p[1], float64(curMax), float64(n)))
}
}
return min, max, nil
}
var mentionRe = regexp.MustCompile(`^<@([UW][A-Z0-9]+)(?:\|[^>]*)?>[,.]?$`)
type GrantCmd struct {
ToDefault bool
Users []string
Actions []model.Action
}
func ParseGrant(args string) (GrantCmd, error) {
var g GrantCmd
words := strings.Fields(args)
i := 0
if len(words) > 0 && strings.ToLower(words[0]) == "default" {
g.ToDefault, i = true, 1
}
for ; i < len(words); i++ {
if m := mentionRe.FindStringSubmatch(words[i]); m != nil {
g.Users = append(g.Users, m[1])
continue
}
w := strings.ToLower(strings.Trim(words[i], ",."))
if w == "all" || slices.Contains(model.GrantActions, model.Action(w)) {
g.Actions = append(g.Actions, model.Action(w))
continue
}
if len(g.Users) == 0 && !g.ToDefault {
return g, ErrNotCommand
}
return g, fmt.Errorf("I didn't understand `%s`", words[i])
}
switch {
case len(g.Users) == 0 && !g.ToDefault:
return g, ErrNotCommand
case len(g.Users) == 0:
return g, errors.New("name at least one person, like `grant default @alice all`")
}
return g, nil
}
func ParseToggle(word string) (on, ok bool) {
switch strings.ToLower(word) {
case "on", "yes", "true", "allow", "allowed", "enable":
return true, true
case "off", "no", "false", "deny", "denied", "disable":
return false, true
}
return false, false
}
var listenModes = map[string]model.ListenMode{
"all": model.ListenAll, "all-messages": model.ListenAll, "all-message": model.ListenAll, "everything": model.ListenAll,
"mentions": model.ListenMentions, "only-mentions": model.ListenMentions, "only-mention": model.ListenMentions,
"mentions-only": model.ListenMentions,
}
type ListenCmd struct {
Channel bool
// Empty means show the current setting.
Mode model.ListenMode
}
// IsListen accepts `listen` and `/listen`. Slack only treats a leading slash
// as a slash command, so `@slacker /listen …` reaches the bot as text.
func IsListen(verb string) bool { return verb == "listen" || verb == "/listen" }
func ParseListen(args string) (ListenCmd, error) {
var c ListenCmd
words := strings.Fields(strings.ToLower(args))
if len(words) > 0 && (words[0] == "channel" || words[0] == "default") {
c.Channel, words = true, words[1:]
}
switch len(words) {
case 0:
return c, nil
case 1:
if mode, ok := listenModes[words[0]]; ok {
c.Mode = mode
return c, nil
}
}
return c, ErrNotCommand
}
func NeededPermission(verb, args string) model.Action {
switch verb {
case "scale":
if _, err := ParseScale(args, model.Size{MemoryMB: 1024, CPUs: 1}); !errors.Is(err, ErrNotCommand) {
return model.ActScale
}
case "keep":
if k, err := ParseKeep(args); !errors.Is(err, ErrNotCommand) && !k.Show {
return model.ActKeep
}
case "storage", "disk":
if args == "" {
return ""
}
if _, _, err := ParseStorage(args, 1024, 1024); !errors.Is(err, ErrNotCommand) {
return model.ActStorage
}
}
return ""
}