resource.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package store
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/pkg/errors"
  8. "github.com/usememos/memos/internal/util"
  9. )
  10. const (
  11. // thumbnailImagePath is the directory to store image thumbnails.
  12. thumbnailImagePath = ".thumbnail_cache"
  13. )
  14. type Resource struct {
  15. ID int32
  16. // Standard fields
  17. CreatorID int32
  18. CreatedTs int64
  19. UpdatedTs int64
  20. // Domain specific fields
  21. Filename string
  22. Blob []byte
  23. InternalPath string
  24. ExternalLink string
  25. Type string
  26. Size int64
  27. MemoID *int32
  28. }
  29. type FindResource struct {
  30. GetBlob bool
  31. ID *int32
  32. CreatorID *int32
  33. Filename *string
  34. MemoID *int32
  35. HasRelatedMemo bool
  36. Limit *int
  37. Offset *int
  38. }
  39. type UpdateResource struct {
  40. ID int32
  41. UpdatedTs *int64
  42. Filename *string
  43. InternalPath *string
  44. MemoID *int32
  45. Blob []byte
  46. }
  47. type DeleteResource struct {
  48. ID int32
  49. MemoID *int32
  50. }
  51. func (s *Store) CreateResource(ctx context.Context, create *Resource) (*Resource, error) {
  52. return s.driver.CreateResource(ctx, create)
  53. }
  54. func (s *Store) ListResources(ctx context.Context, find *FindResource) ([]*Resource, error) {
  55. return s.driver.ListResources(ctx, find)
  56. }
  57. func (s *Store) GetResource(ctx context.Context, find *FindResource) (*Resource, error) {
  58. resources, err := s.ListResources(ctx, find)
  59. if err != nil {
  60. return nil, err
  61. }
  62. if len(resources) == 0 {
  63. return nil, nil
  64. }
  65. return resources[0], nil
  66. }
  67. func (s *Store) UpdateResource(ctx context.Context, update *UpdateResource) (*Resource, error) {
  68. return s.driver.UpdateResource(ctx, update)
  69. }
  70. func (s *Store) DeleteResource(ctx context.Context, delete *DeleteResource) error {
  71. resource, err := s.GetResource(ctx, &FindResource{ID: &delete.ID})
  72. if err != nil {
  73. return errors.Wrap(err, "failed to get resource")
  74. }
  75. if resource == nil {
  76. return errors.Wrap(nil, "resource not found")
  77. }
  78. // Delete the local file.
  79. if resource.InternalPath != "" {
  80. _ = os.Remove(resource.InternalPath)
  81. }
  82. // Delete the thumbnail.
  83. if util.HasPrefixes(resource.Type, "image/png", "image/jpeg") {
  84. ext := filepath.Ext(resource.Filename)
  85. thumbnailPath := filepath.Join(s.Profile.Data, thumbnailImagePath, fmt.Sprintf("%d%s", resource.ID, ext))
  86. _ = os.Remove(thumbnailPath)
  87. }
  88. return s.driver.DeleteResource(ctx, delete)
  89. }