memos/server/resource.go

446 lines
15 KiB
Go
Raw Normal View History

2022-02-03 10:32:03 +03:00
package server
import (
"bytes"
"encoding/json"
2022-02-03 10:32:03 +03:00
"fmt"
2022-08-20 06:36:24 +03:00
"io"
2022-02-03 10:32:03 +03:00
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
2022-02-03 10:32:03 +03:00
"strconv"
2023-01-07 05:51:34 +03:00
"strings"
"time"
2022-02-03 10:32:03 +03:00
"github.com/labstack/echo/v4"
2023-01-02 18:18:12 +03:00
"github.com/pkg/errors"
2022-06-27 17:09:06 +03:00
"github.com/usememos/memos/api"
"github.com/usememos/memos/common"
"github.com/usememos/memos/plugin/storage/s3"
2022-02-03 10:32:03 +03:00
)
const (
// The max file size is 32MB.
maxFileSize = 32 << 20
)
var fileKeyPattern = regexp.MustCompile(`\{[a-z]{1,9}\}`)
2022-02-03 10:32:03 +03:00
func (s *Server) registerResourceRoutes(g *echo.Group) {
g.POST("/resource", func(c echo.Context) error {
2022-08-07 05:17:12 +03:00
ctx := c.Request().Context()
2022-07-28 15:09:25 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-02-03 10:32:03 +03:00
resourceCreate := &api.ResourceCreate{}
if err := json.NewDecoder(c.Request().Body).Decode(resourceCreate); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post resource request").SetInternal(err)
}
resourceCreate.CreatorID = userID
2023-02-11 12:34:29 +03:00
// Only allow those external links with http prefix.
if resourceCreate.ExternalLink != "" && !strings.HasPrefix(resourceCreate.ExternalLink, "http") {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid external link")
}
resource, err := s.Store.CreateResource(ctx, resourceCreate)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create resource").SetInternal(err)
}
if err := s.createResourceCreateActivity(c, resource); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(resource))
})
g.POST("/resource/blob", func(c echo.Context) error {
ctx := c.Request().Context()
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
if err := c.Request().ParseMultipartForm(maxFileSize); err != nil {
2022-02-03 10:32:03 +03:00
return echo.NewHTTPError(http.StatusBadRequest, "Upload file overload max size").SetInternal(err)
}
file, err := c.FormFile("file")
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get uploading file").SetInternal(err)
}
if file == nil {
2022-02-03 10:32:03 +03:00
return echo.NewHTTPError(http.StatusBadRequest, "Upload file not found").SetInternal(err)
}
filename := file.Filename
filetype := file.Header.Get("Content-Type")
size := file.Size
src, err := file.Open()
if err != nil {
2022-02-04 13:54:24 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to open file").SetInternal(err)
2022-02-03 10:32:03 +03:00
}
defer src.Close()
systemSettingStorageServiceID, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{Name: api.SystemSettingStorageServiceIDName})
if err != nil && common.ErrorCode(err) != common.NotFound {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find storage").SetInternal(err)
}
storageServiceID := 0
if systemSettingStorageServiceID != nil {
err = json.Unmarshal([]byte(systemSettingStorageServiceID.Value), &storageServiceID)
2023-02-14 04:56:04 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal storage service id").SetInternal(err)
}
}
var resourceCreate *api.ResourceCreate
if storageServiceID == 0 {
// Database storage.
fileBytes, err := io.ReadAll(src)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to read file").SetInternal(err)
}
resourceCreate = &api.ResourceCreate{
CreatorID: userID,
Filename: filename,
Type: filetype,
Size: size,
Blob: fileBytes,
}
} else if storageServiceID == -1 {
// Local storage.
systemSettingLocalStoragePath, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{Name: api.SystemSettingLocalStoragePathName})
if err != nil && common.ErrorCode(err) != common.NotFound {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find storage").SetInternal(err)
}
localStoragePath := ""
if systemSettingLocalStoragePath != nil {
err = json.Unmarshal([]byte(systemSettingLocalStoragePath.Value), &localStoragePath)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal storage service id").SetInternal(err)
}
}
filePath := localStoragePath
if !strings.Contains(filePath, "{filename}") {
filePath = path.Join(filePath, "{filename}")
}
filePath = path.Join(s.Profile.Data, replacePathTemplate(filePath, filename))
dirPath := filepath.Dir(filePath)
err = os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create directory").SetInternal(err)
}
dst, err := os.Create(filePath)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create file").SetInternal(err)
}
defer dst.Close()
_, err = io.Copy(dst, src)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to copy file").SetInternal(err)
}
resourceCreate = &api.ResourceCreate{
CreatorID: userID,
Filename: filename,
Type: filetype,
Size: size,
InternalPath: filePath,
}
} else {
storage, err := s.Store.FindStorage(ctx, &api.StorageFind{ID: &storageServiceID})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find storage").SetInternal(err)
}
2023-02-23 19:02:51 +03:00
if storage.Type == api.StorageS3 {
s3Config := storage.Config.S3Config
var s3FileKey string
if !strings.Contains(s3Config.Path, "{filename}") {
s3FileKey = path.Join(s3Config.Path, "{filename}")
}
s3FileKey = replacePathTemplate(s3FileKey, filename)
2023-02-23 19:02:51 +03:00
s3client, err := s3.NewClient(ctx, &s3.Config{
AccessKey: s3Config.AccessKey,
SecretKey: s3Config.SecretKey,
EndPoint: s3Config.EndPoint,
Region: s3Config.Region,
Bucket: s3Config.Bucket,
URLPrefix: s3Config.URLPrefix,
URLSuffix: s3Config.URLSuffix,
2023-02-23 19:02:51 +03:00
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to new s3 client").SetInternal(err)
}
link, err := s3client.UploadFile(ctx, s3FileKey, filetype, src)
2023-02-23 19:02:51 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upload via s3 client").SetInternal(err)
}
resourceCreate = &api.ResourceCreate{
CreatorID: userID,
Filename: filename,
Type: filetype,
ExternalLink: link,
}
} else {
return echo.NewHTTPError(http.StatusInternalServerError, "Unsupported storage type")
}
2022-02-03 10:32:03 +03:00
}
2022-08-07 05:17:12 +03:00
resource, err := s.Store.CreateResource(ctx, resourceCreate)
2022-02-03 10:32:03 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create resource").SetInternal(err)
}
2023-01-02 18:18:12 +03:00
if err := s.createResourceCreateActivity(c, resource); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(resource))
2022-02-03 10:32:03 +03:00
})
2022-02-18 17:21:10 +03:00
2022-02-03 10:32:03 +03:00
g.GET("/resource", func(c echo.Context) error {
2022-08-07 05:17:12 +03:00
ctx := c.Request().Context()
2022-07-28 15:09:25 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-02-03 10:32:03 +03:00
resourceFind := &api.ResourceFind{
2022-05-02 21:05:43 +03:00
CreatorID: &userID,
2022-02-03 10:32:03 +03:00
}
if limit, err := strconv.Atoi(c.QueryParam("limit")); err == nil {
resourceFind.Limit = &limit
}
if offset, err := strconv.Atoi(c.QueryParam("offset")); err == nil {
resourceFind.Offset = &offset
}
2022-08-07 05:17:12 +03:00
list, err := s.Store.FindResourceList(ctx, resourceFind)
2022-02-03 10:32:03 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource list").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(list))
2022-06-22 14:16:31 +03:00
})
g.GET("/resource/:resourceId", func(c echo.Context) error {
2022-08-07 05:17:12 +03:00
ctx := c.Request().Context()
2022-06-22 14:16:31 +03:00
resourceID, err := strconv.Atoi(c.Param("resourceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
}
2022-07-28 15:09:25 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-06-22 14:16:31 +03:00
resourceFind := &api.ResourceFind{
ID: &resourceID,
CreatorID: &userID,
GetBlob: true,
2022-06-22 14:16:31 +03:00
}
2022-08-07 05:17:12 +03:00
resource, err := s.Store.FindResource(ctx, resourceFind)
2022-06-22 14:16:31 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(resource))
2022-06-22 14:16:31 +03:00
})
g.GET("/resource/:resourceId/blob", func(c echo.Context) error {
2022-08-07 05:17:12 +03:00
ctx := c.Request().Context()
2022-06-22 14:16:31 +03:00
resourceID, err := strconv.Atoi(c.Param("resourceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
}
2022-07-28 15:09:25 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-06-22 14:16:31 +03:00
resourceFind := &api.ResourceFind{
ID: &resourceID,
CreatorID: &userID,
GetBlob: true,
2022-06-22 14:16:31 +03:00
}
2022-08-07 05:17:12 +03:00
resource, err := s.Store.FindResource(ctx, resourceFind)
2022-06-22 14:16:31 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource").SetInternal(err)
}
2023-02-11 12:34:29 +03:00
return c.Stream(http.StatusOK, resource.Type, bytes.NewReader(resource.Blob))
2022-02-03 10:32:03 +03:00
})
2022-02-18 17:21:10 +03:00
2022-12-19 13:45:17 +03:00
g.PATCH("/resource/:resourceId", func(c echo.Context) error {
2022-08-07 05:17:12 +03:00
ctx := c.Request().Context()
2022-08-06 20:30:48 +03:00
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
2022-05-02 21:05:43 +03:00
resourceID, err := strconv.Atoi(c.Param("resourceId"))
2022-02-03 10:32:03 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
}
2022-12-19 13:45:17 +03:00
resourceFind := &api.ResourceFind{
2022-12-28 15:22:52 +03:00
ID: &resourceID,
2022-11-06 07:21:58 +03:00
}
2022-12-28 15:22:52 +03:00
resource, err := s.Store.FindResource(ctx, resourceFind)
if err != nil {
2022-12-19 13:45:17 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find resource").SetInternal(err)
2022-11-06 07:21:58 +03:00
}
2022-12-28 15:22:52 +03:00
if resource.CreatorID != userID {
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
}
2022-11-06 07:21:58 +03:00
2022-12-19 13:45:17 +03:00
currentTs := time.Now().Unix()
resourcePatch := &api.ResourcePatch{
UpdatedTs: &currentTs,
2022-02-03 10:32:03 +03:00
}
2022-12-19 13:45:17 +03:00
if err := json.NewDecoder(c.Request().Body).Decode(resourcePatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch resource request").SetInternal(err)
2022-02-03 10:32:03 +03:00
}
2023-02-09 18:20:36 +03:00
resourcePatch.ID = resourceID
2022-12-28 15:22:52 +03:00
resource, err = s.Store.PatchResource(ctx, resourcePatch)
2022-12-19 13:45:17 +03:00
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch resource").SetInternal(err)
}
return c.JSON(http.StatusOK, composeResponse(resource))
2022-02-03 10:32:03 +03:00
})
2022-12-19 13:45:17 +03:00
g.DELETE("/resource/:resourceId", func(c echo.Context) error {
ctx := c.Request().Context()
userID, ok := c.Get(getUserIDContextKey()).(int)
if !ok {
return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
}
resourceID, err := strconv.Atoi(c.Param("resourceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
}
2022-12-19 13:45:17 +03:00
resource, err := s.Store.FindResource(ctx, &api.ResourceFind{
ID: &resourceID,
CreatorID: &userID,
2022-12-19 13:45:17 +03:00
})
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find resource").SetInternal(err)
}
2022-12-28 15:22:52 +03:00
if resource.CreatorID != userID {
return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
}
2022-12-19 13:45:17 +03:00
resourceDelete := &api.ResourceDelete{
ID: resourceID,
}
2022-12-19 13:45:17 +03:00
if err := s.Store.DeleteResource(ctx, resourceDelete); err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Resource ID not found: %d", resourceID))
}
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to delete resource").SetInternal(err)
}
2022-12-19 13:45:17 +03:00
return c.JSON(http.StatusOK, true)
})
2022-02-03 10:32:03 +03:00
}
2022-09-08 19:50:58 +03:00
func (s *Server) registerResourcePublicRoutes(g *echo.Group) {
g.GET("/r/:resourceId/:filename", func(c echo.Context) error {
ctx := c.Request().Context()
resourceID, err := strconv.Atoi(c.Param("resourceId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
}
filename, err := url.QueryUnescape(c.Param("filename"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("filename is invalid: %s", c.Param("filename"))).SetInternal(err)
}
2022-09-08 19:50:58 +03:00
resourceFind := &api.ResourceFind{
ID: &resourceID,
Filename: &filename,
GetBlob: true,
2022-09-08 19:50:58 +03:00
}
resource, err := s.Store.FindResource(ctx, resourceFind)
if err != nil {
2023-02-11 12:34:29 +03:00
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find resource by ID: %v", resourceID)).SetInternal(err)
2022-09-08 19:50:58 +03:00
}
blob := resource.Blob
if resource.InternalPath != "" {
src, err := os.Open(resource.InternalPath)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to open the local resource: %s", resource.InternalPath)).SetInternal(err)
}
defer src.Close()
blob, err = io.ReadAll(src)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to read the local resource: %s", resource.InternalPath)).SetInternal(err)
}
}
2022-11-21 18:23:05 +03:00
c.Response().Writer.Header().Set(echo.HeaderCacheControl, "max-age=31536000, immutable")
c.Response().Writer.Header().Set(echo.HeaderContentSecurityPolicy, "default-src 'self'")
2023-02-11 12:34:29 +03:00
resourceType := strings.ToLower(resource.Type)
if strings.HasPrefix(resourceType, "text") {
resourceType = echo.MIMETextPlainCharsetUTF8
} else if strings.HasPrefix(resourceType, "video") || strings.HasPrefix(resourceType, "audio") {
http.ServeContent(c.Response(), c.Request(), resource.Filename, time.Unix(resource.UpdatedTs, 0), bytes.NewReader(blob))
return nil
}
return c.Stream(http.StatusOK, resourceType, bytes.NewReader(blob))
2022-09-08 19:50:58 +03:00
})
}
2023-01-02 18:18:12 +03:00
func (s *Server) createResourceCreateActivity(c echo.Context, resource *api.Resource) error {
ctx := c.Request().Context()
payload := api.ActivityResourceCreatePayload{
Filename: resource.Filename,
Type: resource.Type,
Size: resource.Size,
}
payloadBytes, err := json.Marshal(payload)
2023-01-02 18:18:12 +03:00
if err != nil {
return errors.Wrap(err, "failed to marshal activity payload")
}
2023-01-05 15:56:50 +03:00
activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
2023-01-02 18:18:12 +03:00
CreatorID: resource.CreatorID,
Type: api.ActivityResourceCreate,
Level: api.ActivityInfo,
Payload: string(payloadBytes),
2023-01-02 18:18:12 +03:00
})
2023-01-07 06:49:58 +03:00
if err != nil || activity == nil {
return errors.Wrap(err, "failed to create activity")
}
2023-01-02 18:18:12 +03:00
return err
}
func replacePathTemplate(path string, filename string) string {
t := time.Now()
path = fileKeyPattern.ReplaceAllStringFunc(path, func(s string) string {
switch s {
case "{filename}":
return filename
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
})
return path
}