memos/server/route/api/v2/memo_resource_service.go

86 lines
2.5 KiB
Go
Raw Normal View History

package v2
import (
"context"
2024-01-06 09:23:20 +08:00
"slices"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
apiv2pb "github.com/usememos/memos/proto/gen/api/v2"
"github.com/usememos/memos/store"
)
func (s *APIV2Service) SetMemoResources(ctx context.Context, request *apiv2pb.SetMemoResourcesRequest) (*apiv2pb.SetMemoResourcesResponse, error) {
2024-03-20 21:17:04 +08:00
memoID, err := ExtractMemoIDFromName(request.Name)
2024-03-18 23:23:53 +08:00
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid memo name: %v", err)
}
2024-01-06 09:23:20 +08:00
resources, err := s.Store.ListResources(ctx, &store.FindResource{
2024-03-20 21:17:04 +08:00
MemoID: &memoID,
2024-01-06 09:23:20 +08:00
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list resources")
}
// Delete resources that are not in the request.
for _, resource := range resources {
found := false
for _, requestResource := range request.Resources {
2024-03-20 21:17:04 +08:00
if resource.UID == requestResource.Uid {
found = true
break
}
}
if !found {
if err = s.Store.DeleteResource(ctx, &store.DeleteResource{
ID: int32(resource.ID),
2024-03-20 21:17:04 +08:00
MemoID: &memoID,
}); err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete resource")
}
}
}
2024-01-06 09:23:20 +08:00
slices.Reverse(request.Resources)
// Update resources' memo_id in the request.
2024-01-06 09:23:20 +08:00
for index, resource := range request.Resources {
2024-03-24 22:35:10 +08:00
id, err := ExtractResourceIDFromName(resource.Name)
2024-03-20 21:17:04 +08:00
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid resource name: %v", err)
}
2024-01-06 09:23:20 +08:00
updatedTs := time.Now().Unix() + int64(index)
if _, err := s.Store.UpdateResource(ctx, &store.UpdateResource{
2024-03-20 21:17:04 +08:00
ID: id,
MemoID: &memoID,
2024-01-06 09:23:20 +08:00
UpdatedTs: &updatedTs,
}); err != nil {
2024-01-15 08:13:06 +08:00
return nil, status.Errorf(codes.Internal, "failed to update resource: %v", err)
}
}
return &apiv2pb.SetMemoResourcesResponse{}, nil
}
func (s *APIV2Service) ListMemoResources(ctx context.Context, request *apiv2pb.ListMemoResourcesRequest) (*apiv2pb.ListMemoResourcesResponse, error) {
2024-03-18 23:23:53 +08:00
id, err := ExtractMemoIDFromName(request.Name)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid memo name: %v", err)
}
resources, err := s.Store.ListResources(ctx, &store.FindResource{
2024-03-18 23:23:53 +08:00
MemoID: &id,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list resources")
}
response := &apiv2pb.ListMemoResourcesResponse{
Resources: []*apiv2pb.Resource{},
}
for _, resource := range resources {
response.Resources = append(response.Resources, s.convertResourceFromStore(ctx, resource))
}
return response, nil
}