Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

refactor: build storage key (#1326)

Cologler8c774316aeec
diff --git a/server/resource.go b/server/resource.go
index 484d78175..13dd8879a 100644
--- a/server/resource.go
+++ b/server/resource.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/url"
"path"
+ "regexp"
"strconv"
"strings"
"time"
@@ -24,6 +25,8 @@ const (
maxFileSize = 32 << 20
)
+var fileKeyPattern = regexp.MustCompile(`\{[a-z]{1,9}\}`)
+
func (s *Server) registerResourceRoutes(g *echo.Group) {
g.POST("/resource", func(c echo.Context) error {
ctx := c.Request().Context()
@@ -136,22 +139,39 @@ func (s *Server) registerResourceRoutes(g *echo.Group) {
if storage.Type == api.StorageS3 {
s3Config := storage.Config.S3Config
t := time.Now()
- s3FileKey := s3Config.Path
+ var s3FileKey string
if s3Config.Path == "" {
s3FileKey = filename
- } else if !strings.Contains(s3Config.Path, "{filename}") {
- s3FileKey = path.Join(s3Config.Path, filename)
} else {
- s3FileKey = strings.ReplaceAll(s3FileKey, "{filename}", filename)
- s3FileKey = strings.ReplaceAll(s3FileKey, "{filetype}", filetype)
- s3FileKey = strings.ReplaceAll(s3FileKey, "{timestamp}", fmt.Sprintf("%d", t.Unix()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{year}", fmt.Sprintf("%d", t.Year()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{month}", fmt.Sprintf("%02d", t.Month()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{day}", fmt.Sprintf("%02d", t.Day()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{hour}", fmt.Sprintf("%02d", t.Hour()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{minute}", fmt.Sprintf("%02d", t.Minute()))
- s3FileKey = strings.ReplaceAll(s3FileKey, "{second}", fmt.Sprintf("%02d", t.Second()))
+ s3FileKey = fileKeyPattern.ReplaceAllStringFunc(s3Config.Path, func(s string) string {
+ switch s {
+ case "{filename}":
+ return filename
+ case "{filetype}":
+ return filetype
+ case "{timestamp}":
+ return fmt.Sprintf("%d", t.Unix())
+ case "{year}":
+ return fmt.Sprintf("%d", t.Year())
+ case "{month}":
+ return fmt.Sprintf("%02d", t.Month())
+ case "{day}":
+ return fmt.Sprintf("%02d", t.Day())
+ case "{hour}":
+ return fmt.Sprintf("%02d", t.Hour())
+ case "{minute}":
+ return fmt.Sprintf("%02d", t.Minute())
+ case "{second}":
+ return fmt.Sprintf("%02d", t.Second())
+ }
+ return s
+ })
+
+ if !strings.Contains(s3Config.Path, "{filename}") {
+ s3FileKey = path.Join(s3FileKey, filename)
+ }
}
+
s3client, err := s3.NewClient(ctx, &s3.Config{
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,