Fix: movie name too long auto truncate

This commit is contained in:
zijiren233 2024-01-21 00:51:15 +08:00
parent c95b0b91d2
commit e5f2e173a8
4 changed files with 40 additions and 4 deletions

View File

@ -28,7 +28,7 @@ func (m *Movie) BeforeCreate(tx *gorm.DB) error {
type BaseMovie struct {
Url string `gorm:"type:varchar(8192)" json:"url"`
Name string `gorm:"not null;type:varchar(128)" json:"name"`
Name string `gorm:"not null;type:varchar(256)" json:"name"`
Live bool `json:"live"`
Proxy bool `json:"proxy"`
RtmpSource bool `json:"rtmpSource"`

View File

@ -7,12 +7,12 @@ import (
json "github.com/json-iterator/go"
"github.com/synctv-org/synctv/internal/model"
"github.com/synctv-org/synctv/internal/op"
"github.com/synctv-org/synctv/utils"
)
var (
ErrUrlTooLong = errors.New("url too long")
ErrEmptyName = errors.New("empty name")
ErrNameTooLong = errors.New("name too long")
ErrTypeTooLong = errors.New("type too long")
ErrId = errors.New("id must be greater than 0")
@ -33,8 +33,9 @@ func (p *PushMovieReq) Validate() error {
if p.Name == "" {
return ErrEmptyName
} else if len(p.Name) > 128 {
return ErrNameTooLong
} else if len(p.Name) > 256 {
// 从最后一个完整rune截断而不是返回错误
p.Name = utils.TruncateByRune(p.Name, 253) + "..."
}
if len(p.Type) > 32 {

View File

@ -384,3 +384,17 @@ func GetPageAndMax(ctx *gin.Context) (page int, max int, err error) {
}
return
}
func TruncateByRune(s string, length int) string {
if len(s) <= length {
return s
}
total := 0
for _, v := range s {
total += len(string(v))
if total > length {
return s[:total-len(string(v))]
}
}
panic("truncate by rune error")
}

View File

@ -2,6 +2,7 @@ package utils_test
import (
"reflect"
"strings"
"testing"
"github.com/synctv-org/synctv/utils"
@ -107,3 +108,23 @@ func TestIsLocalIP(t *testing.T) {
})
}
}
func TestTruncateByRune(t *testing.T) {
// len("测") = 3
name := "abcd测试"
if !strings.EqualFold(utils.TruncateByRune(name, 6), "abcd") {
t.Errorf("TruncateByRune() = %v, want %v", utils.TruncateByRune(name, 6), "abcd")
}
if !strings.EqualFold(utils.TruncateByRune(name, 7), "abcd测") {
t.Errorf("TruncateByRune() = %v, want %v", utils.TruncateByRune(name, 7), "abcd测")
}
if !strings.EqualFold(utils.TruncateByRune(name, 8), "abcd测") {
t.Errorf("TruncateByRune() = %v, want %v", utils.TruncateByRune(name, 8), "abcd测")
}
if !strings.EqualFold(utils.TruncateByRune(name, 9), "abcd测") {
t.Errorf("TruncateByRune() = %v, want %v", utils.TruncateByRune(name, 9), "abcd测")
}
if !strings.EqualFold(utils.TruncateByRune(name, 10), "abcd测试") {
t.Errorf("TruncateByRune() = %v, want %v", utils.TruncateByRune(name, 10), "abcd测试")
}
}