Attachment size limit

This commit is contained in:
Philipp Heckel 2022-01-06 01:04:56 +01:00
parent 24eb27d41c
commit 5eca20469f
5 changed files with 76 additions and 7 deletions

View file

@ -6,6 +6,8 @@ import (
"math/rand"
"mime"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
@ -16,8 +18,9 @@ const (
)
var (
random = rand.New(rand.NewSource(time.Now().UnixNano()))
randomMutex = sync.Mutex{}
random = rand.New(rand.NewSource(time.Now().UnixNano()))
randomMutex = sync.Mutex{}
sizeStrRegex = regexp.MustCompile(`(?i)^(\d+)([gmkb])?$`)
errInvalidPriority = errors.New("invalid priority")
)
@ -178,3 +181,25 @@ func ExtensionByType(contentType string) string {
return ".bin"
}
}
// ParseSize parses a size string like 2K or 2M into bytes. If no unit is found, e.g. 123, bytes is assumed.
func ParseSize(s string) (int64, error) {
matches := sizeStrRegex.FindStringSubmatch(s)
if matches == nil {
return -1, fmt.Errorf("invalid size %s", s)
}
value, err := strconv.Atoi(matches[1])
if err != nil {
return -1, fmt.Errorf("cannot convert number %s", matches[1])
}
switch strings.ToUpper(matches[2]) {
case "G":
return int64(value) * 1024 * 1024 * 1024, nil
case "M":
return int64(value) * 1024 * 1024, nil
case "K":
return int64(value) * 1024, nil
default:
return int64(value), nil
}
}

View file

@ -121,3 +121,34 @@ func TestShortTopicURL(t *testing.T) {
require.Equal(t, "ntfy.sh/mytopic", ShortTopicURL("http://ntfy.sh/mytopic"))
require.Equal(t, "lalala", ShortTopicURL("lalala"))
}
func TestParseSize_10GSuccess(t *testing.T) {
s, err := ParseSize("10G")
if err != nil {
t.Fatal(err)
}
require.Equal(t, 10*1024*1024*1024, s)
}
func TestParseSize_10MUpperCaseSuccess(t *testing.T) {
s, err := ParseSize("10M")
if err != nil {
t.Fatal(err)
}
require.Equal(t, 10*1024*1024, s)
}
func TestParseSize_10kLowerCaseSuccess(t *testing.T) {
s, err := ParseSize("10k")
if err != nil {
t.Fatal(err)
}
require.Equal(t, 10*1024, s)
}
func TestParseSize_FailureInvalid(t *testing.T) {
_, err := ParseSize("not a size")
if err == nil {
t.Fatalf("expected error, but got none")
}
}