resource_service.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package v2
  2. import (
  3. "context"
  4. "time"
  5. "google.golang.org/grpc/codes"
  6. "google.golang.org/grpc/status"
  7. "google.golang.org/protobuf/types/known/timestamppb"
  8. apiv2pb "github.com/usememos/memos/proto/gen/api/v2"
  9. "github.com/usememos/memos/store"
  10. )
  11. type ResourceService struct {
  12. apiv2pb.UnimplementedResourceServiceServer
  13. Store *store.Store
  14. }
  15. // NewResourceService creates a new ResourceService.
  16. func NewResourceService(store *store.Store) *ResourceService {
  17. return &ResourceService{
  18. Store: store,
  19. }
  20. }
  21. func (s *ResourceService) ListResources(ctx context.Context, _ *apiv2pb.ListResourcesRequest) (*apiv2pb.ListResourcesResponse, error) {
  22. user, err := getCurrentUser(ctx, s.Store)
  23. if err != nil {
  24. return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
  25. }
  26. resources, err := s.Store.ListResources(ctx, &store.FindResource{
  27. CreatorID: &user.ID,
  28. HasRelatedMemo: true,
  29. })
  30. if err != nil {
  31. return nil, status.Errorf(codes.Internal, "failed to list resources: %v", err)
  32. }
  33. response := &apiv2pb.ListResourcesResponse{}
  34. for _, resource := range resources {
  35. response.Resources = append(response.Resources, convertResourceFromStore(resource))
  36. }
  37. return response, nil
  38. }
  39. func convertResourceFromStore(resource *store.Resource) *apiv2pb.Resource {
  40. return &apiv2pb.Resource{
  41. Id: resource.ID,
  42. CreatedTs: timestamppb.New(time.Unix(resource.CreatedTs, 0)),
  43. Filename: resource.Filename,
  44. ExternalLink: resource.ExternalLink,
  45. Type: resource.Type,
  46. Size: resource.Size,
  47. RelatedMemoId: resource.RelatedMemoID,
  48. }
  49. }