refactor(pkg): name honesty and dead-code removal

- hashid: consolidate 11 identical EncodeXxxID wrappers onto one helper;
  fix copy-pasted doc comments.
- thumb: rename Thumb.GetThumb -> Resize; it mutates the receiver, and a
  getter name lied about it.
- oauth: rename GrantService.Get -> Issue; it creates a grant, it is not
  a query.
- util: delete unused EncodeTimeFlowString/DecodeTimeFlowStringTime;
  rename IsInExtensionListExt -> IsExtInList (the 'Ext' suffix was
  ambiguous).
- upyun: remove stray fmt.Println that dumped raw media API responses.
- request: drop dead GeneralClient var and the NewClientDeprecated shim;
  tests use NewClient(nil, ...) directly.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
pull/3582/head
Tomas Dvorak 2 weeks ago
parent 54a518c6a5
commit ded86c1617

@ -31,8 +31,6 @@ func (handler *Driver) extractImageMeta(ctx context.Context, path string) ([]dri
return nil, err return nil, err
} }
fmt.Println(resp)
var imageInfo ImageInfo var imageInfo ImageInfo
if err := json.Unmarshal([]byte(resp), &imageInfo); err != nil { if err := json.Unmarshal([]byte(resp), &imageInfo); err != nil {
return nil, fmt.Errorf("failed to unmarshal image info: %w", err) return nil, fmt.Errorf("failed to unmarshal image info: %w", err)

@ -75,76 +75,69 @@ func (e *hashEncoder) Decode(raw string, t int) (int, error) {
return res[0], nil return res[0], nil
} }
func encodeID(encoder Encoder, id, t int) string {
res, _ := encoder.Encode([]int{id, t})
return res
}
// EncodeUserID encode user id to hash id // EncodeUserID encode user id to hash id
func EncodeUserID(encoder Encoder, uid int) string { func EncodeUserID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, UserID}) return encodeID(encoder, uid, UserID)
return res
} }
// EncodeGroupID encode group id to hash id // EncodeGroupID encode group id to hash id
func EncodeGroupID(encoder Encoder, uid int) string { func EncodeGroupID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, GroupID}) return encodeID(encoder, uid, GroupID)
return res
} }
// EncodePaymentID encode payment id to hash id // EncodePaymentID encode payment id to hash id
func EncodePaymentID(encoder Encoder, uid int) string { func EncodePaymentID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, PaymentID}) return encodeID(encoder, uid, PaymentID)
return res
} }
// EncodeFileID encode file id to hash id // EncodeFileID encode file id to hash id
func EncodeFileID(encoder Encoder, uid int) string { func EncodeFileID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, FileID}) return encodeID(encoder, uid, FileID)
return res
} }
// EncodeAuditLogID encode audit log id to hash id // EncodeAuditLogID encode audit log id to hash id
func EncodeAuditLogID(encoder Encoder, uid int) string { func EncodeAuditLogID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, AuditLogID}) return encodeID(encoder, uid, AuditLogID)
return res
} }
// EncodeTaskID encode task id to hash id // EncodeTaskID encode task id to hash id
func EncodeTaskID(encoder Encoder, uid int) string { func EncodeTaskID(encoder Encoder, uid int) string {
res, _ := encoder.Encode([]int{uid, TaskID}) return encodeID(encoder, uid, TaskID)
return res
} }
// EncodeEntityID encode entity id to hash id // EncodeEntityID encode entity id to hash id
func EncodeEntityID(encoder Encoder, id int) string { func EncodeEntityID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, EntityID}) return encodeID(encoder, id, EntityID)
return res
} }
// EncodeNodeID encode node id to hash id // EncodeNodeID encode node id to hash id
func EncodeNodeID(encoder Encoder, id int) string { func EncodeNodeID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, NodeID}) return encodeID(encoder, id, NodeID)
return res
} }
// EncodeEntityID encode policy id to hash id // EncodePolicyID encode policy id to hash id
func EncodePolicyID(encoder Encoder, id int) string { func EncodePolicyID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, PolicyID}) return encodeID(encoder, id, PolicyID)
return res
} }
// EncodeEntityID encode share id to hash id // EncodeShareID encode share id to hash id
func EncodeShareID(encoder Encoder, id int) string { func EncodeShareID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, ShareID}) return encodeID(encoder, id, ShareID)
return res
} }
// EncodeDavAccountID encode dav account id to hash id // EncodeDavAccountID encode dav account id to hash id
func EncodeDavAccountID(encoder Encoder, id int) string { func EncodeDavAccountID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, DavAccountID}) return encodeID(encoder, id, DavAccountID)
return res
} }
// EncodeSourceLinkID encode source link id to hash id // EncodeSourceLinkID encode source link id to hash id
func EncodeSourceLinkID(encoder Encoder, id int) string { func EncodeSourceLinkID(encoder Encoder, id int) string {
res, _ := encoder.Encode([]int{id, SourceLinkID}) return encodeID(encoder, id, SourceLinkID)
return res
} }
func FromContext(c context.Context) int { func FromContext(c context.Context) int {

@ -21,9 +21,6 @@ import (
"github.com/samber/lo" "github.com/samber/lo"
) )
// GeneralClient 通用 HTTP Client
var GeneralClient Client = NewClientDeprecated()
const ( const (
CorrelationHeader = constants.CrHeaderPrefix + "Correlation-Id" CorrelationHeader = constants.CrHeaderPrefix + "Correlation-Id"
SiteURLHeader = constants.CrHeaderPrefix + "Site-Url" SiteURLHeader = constants.CrHeaderPrefix + "Site-Url"
@ -72,20 +69,6 @@ func NewClient(config conf.ConfigProvider, opts ...Option) Client {
return client return client
} }
// Deprecated
func NewClientDeprecated(opts ...Option) Client {
client := &HTTPClient{
options: newDefaultOption(),
tpsLimiter: globalTPSLimiter,
}
for _, o := range opts {
o.apply(client.options)
}
return client
}
func (c *HTTPClient) Apply(opts ...Option) { func (c *HTTPClient) Apply(opts ...Option) {
for _, o := range opts { for _, o := range opts {
o.apply(c.options) o.apply(c.options)

@ -56,7 +56,7 @@ func TestWithContext(t *testing.T) {
func TestHTTPClient_Request(t *testing.T) { func TestHTTPClient_Request(t *testing.T) {
asserts := assert.New(t) asserts := assert.New(t)
client := NewClientDeprecated(WithSlaveMeta(1)) client := NewClient(nil, WithSlaveMeta(1))
// 正常 // 正常
{ {
@ -239,7 +239,7 @@ func TestBlackHole(t *testing.T) {
func TestHTTPClient_TPSLimit(t *testing.T) { func TestHTTPClient_TPSLimit(t *testing.T) {
a := assert.New(t) a := assert.New(t)
client := NewClientDeprecated() client := NewClient(nil, )
finished := make(chan struct{}) finished := make(chan struct{})
go func() { go func() {
@ -296,7 +296,7 @@ func TestSignBaseTimeShiftsExpiry(t *testing.T) {
})) }))
defer srv.Close() defer srv.Close()
client := NewClientDeprecated(WithEndpoint(srv.URL)) client := NewClient(nil, WithEndpoint(srv.URL))
base := time.Now().Add(2 * time.Hour) base := time.Now().Add(2 * time.Hour)
resp := client.Request( resp := client.Request(
"POST", "POST",

@ -77,8 +77,8 @@ func NewThumbFromFile(file io.Reader, ext string) (*Thumb, error) {
}, nil }, nil
} }
// GetThumb 生成给定最大尺寸的缩略图 // Resize 生成给定最大尺寸的缩略图(就地修改)
func (image *Thumb) GetThumb(width, height uint) { func (image *Thumb) Resize(width, height uint) {
//image.src = resize.Thumbnail(width, height, image.src, resize.Lanczos3) //image.src = resize.Thumbnail(width, height, image.src, resize.Lanczos3)
image.src = Thumbnail(width, height, image.src) image.src = Thumbnail(width, height, image.src)
} }
@ -170,7 +170,7 @@ func (b Builtin) Generate(ctx context.Context, es entitysource.EntitySource, ext
} }
w, h := b.settings.ThumbSize(ctx) w, h := b.settings.ThumbSize(ctx)
img.GetThumb(uint(w), uint(h)) img.Resize(uint(w), uint(h))
tempPath := filepath.Join( tempPath := filepath.Join(
util.DataPath(b.settings.TempPath(ctx)), util.DataPath(b.settings.TempPath(ctx)),
thumbTempFolder, thumbTempFolder,

@ -30,7 +30,7 @@ type FfmpegGenerator struct {
} }
func (f *FfmpegGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) { func (f *FfmpegGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) {
if !util.IsInExtensionListExt(f.settings.FFMpegThumbExts(ctx), ext) { if !util.IsExtInList(f.settings.FFMpegThumbExts(ctx), ext) {
return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough) return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough)
} }

@ -30,7 +30,7 @@ type LibRawGenerator struct {
} }
func (l *LibRawGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) { func (l *LibRawGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) {
if !util.IsInExtensionListExt(l.settings.LibRawThumbExts(ctx), ext) { if !util.IsExtInList(l.settings.LibRawThumbExts(ctx), ext) {
return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough) return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough)
} }

@ -27,7 +27,7 @@ type LibreOfficeGenerator struct {
} }
func (l *LibreOfficeGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) { func (l *LibreOfficeGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) {
if !util.IsInExtensionListExt(l.settings.LibreOfficeThumbExts(ctx), ext) { if !util.IsExtInList(l.settings.LibreOfficeThumbExts(ctx), ext) {
return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough) return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough)
} }

@ -23,7 +23,7 @@ type MusicCoverGenerator struct {
} }
func (v *MusicCoverGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) { func (v *MusicCoverGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) {
if !util.IsInExtensionListExt(v.settings.MusicCoverThumbExts(ctx), ext) { if !util.IsExtInList(v.settings.MusicCoverThumbExts(ctx), ext) {
return nil, fmt.Errorf("unsupported music format: %w", ErrPassThrough) return nil, fmt.Errorf("unsupported music format: %w", ErrPassThrough)
} }

@ -28,7 +28,7 @@ type VipsGenerator struct {
} }
func (v *VipsGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) { func (v *VipsGenerator) Generate(ctx context.Context, es entitysource.EntitySource, ext string, previous *Result) (*Result, error) {
if !util.IsInExtensionListExt(v.settings.VipsThumbExts(ctx), ext) { if !util.IsExtInList(v.settings.VipsThumbExts(ctx), ext) {
return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough) return nil, fmt.Errorf("unsupported video format: %w", ErrPassThrough)
} }

@ -3,7 +3,6 @@ package util
import ( import (
"context" "context"
cryptoRand "crypto/rand" cryptoRand "crypto/rand"
"fmt"
"math/big" "math/big"
"math/rand" "math/rand"
"path" "path"
@ -12,7 +11,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"unicode/utf8"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gofrs/uuid" "github.com/gofrs/uuid"
@ -85,7 +83,7 @@ func IsInExtensionList(extList []string, fileName string) bool {
} }
// IsInExtensionList 返回文件的扩展名是否在给定的列表范围内 // IsInExtensionList 返回文件的扩展名是否在给定的列表范围内
func IsInExtensionListExt(extList []string, ext string) bool { func IsExtInList(extList []string, ext string) bool {
// 无扩展名时 // 无扩展名时
if len(ext) == 0 { if len(ext) == 0 {
return false return false
@ -260,101 +258,6 @@ func BoolToString(b bool) string {
return "0" return "0"
} }
func EncodeTimeFlowString(str string, timeNow int64) string {
timeNow = timeNow / 1000
timeDigits := []int{}
timeDigitIndex := 0
if len(str) == 0 {
return ""
}
str = fmt.Sprintf("%d|%s", timeNow, str)
res := make([]int32, 0, utf8.RuneCountInString(str))
for timeNow > 0 {
timeDigits = append(timeDigits, int(timeNow%int64(10)))
timeNow = timeNow / 10
}
add := false
for pos, rune := range str {
// take single digit with index timeDigitIndex from timeNow
newIndex := pos
if add {
newIndex = pos + timeDigits[timeDigitIndex]*timeDigitIndex
} else {
newIndex = 2*timeDigitIndex*timeDigits[timeDigitIndex] - pos
}
if newIndex < 0 {
newIndex = newIndex * -1
}
res = append(res, rune)
newIndex = newIndex % len(res)
res[newIndex], res[len(res)-1] = res[len(res)-1], res[newIndex]
add = !add
// Add timeDigitIndex by 1, but does not exceed total digits in timeNow
timeDigitIndex++
timeDigitIndex = timeDigitIndex % len(timeDigits)
}
return string(res)
}
func DecodeTimeFlowStringTime(str string, timeNow int64) string {
timeNow = timeNow / 1000
timeDigits := []int{}
if len(str) == 0 {
return ""
}
for timeNow > 0 {
timeDigits = append(timeDigits, int(timeNow%int64(10)))
timeNow = timeNow / 10
}
res := make([]int32, utf8.RuneCountInString(str))
secret := []rune(str)
add := false
if len(secret)%2 == 0 {
add = true
}
timeDigitIndex := (len(secret) - 1) % len(timeDigits)
for pos := range secret {
// take single digit with index timeDigitIndex from timeNow
newIndex := len(res) - 1 - pos
if add {
newIndex = newIndex + timeDigits[timeDigitIndex]*timeDigitIndex
} else {
newIndex = 2*timeDigitIndex*timeDigits[timeDigitIndex] - newIndex
}
if newIndex < 0 {
newIndex = newIndex * -1
}
newIndex = newIndex % len(secret)
res[len(res)-1-pos] = secret[newIndex]
secret[newIndex], secret[len(res)-1-pos] = secret[len(res)-1-pos], secret[newIndex]
secret = secret[:len(secret)-1]
add = !add
// Add timeDigitIndex by 1, but does not exceed total digits in timeNow
timeDigitIndex--
if timeDigitIndex < 0 {
timeDigitIndex = len(timeDigits) - 1
}
}
return string(res)
}
func ToPtr[T any](v T) *T { func ToPtr[T any](v T) *T {
return &v return &v
} }

@ -37,7 +37,7 @@ func GetAppRegistration(c *gin.Context) {
func GrantAppConsent(c *gin.Context) { func GrantAppConsent(c *gin.Context) {
service := ParametersFromContext[*oauth.GrantService](c, oauth.GrantParamCtx{}) service := ParametersFromContext[*oauth.GrantService](c, oauth.GrantParamCtx{})
res, err := service.Get(c) res, err := service.Issue(c)
if err != nil { if err != nil {
c.JSON(200, serializer.Err(c, err)) c.JSON(200, serializer.Err(c, err))
c.Abort() c.Abort()

@ -58,7 +58,7 @@ type (
} }
) )
func (s *GrantService) Get(c *gin.Context) (*GrantResponse, error) { func (s *GrantService) Issue(c *gin.Context) (*GrantResponse, error) {
dep := dependency.FromContext(c) dep := dependency.FromContext(c)
user := inventory.UserFromContext(c) user := inventory.UserFromContext(c)
kv := dep.KV() kv := dep.KV()

Loading…
Cancel
Save