memos/api/v2/memo_service.go

856 lines
27 KiB
Go
Raw Normal View History

package v2
import (
"archive/zip"
"bytes"
"context"
2023-12-19 23:49:24 +08:00
"encoding/json"
2023-12-21 22:42:06 +08:00
"fmt"
2023-12-19 23:49:24 +08:00
"time"
"github.com/google/cel-go/cel"
2024-01-20 23:48:35 +08:00
"github.com/lithammer/shortuuid/v4"
"github.com/pkg/errors"
"go.uber.org/zap"
2023-12-17 09:53:22 +08:00
expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
2023-12-19 23:49:24 +08:00
"google.golang.org/protobuf/types/known/timestamppb"
2023-09-17 22:55:13 +08:00
2023-12-19 23:49:24 +08:00
apiv1 "github.com/usememos/memos/api/v1"
"github.com/usememos/memos/internal/log"
2024-01-20 23:48:35 +08:00
"github.com/usememos/memos/internal/util"
"github.com/usememos/memos/plugin/webhook"
2023-09-17 22:55:13 +08:00
apiv2pb "github.com/usememos/memos/proto/gen/api/v2"
storepb "github.com/usememos/memos/proto/gen/store"
"github.com/usememos/memos/server/service/metric"
2023-09-17 22:55:13 +08:00
"github.com/usememos/memos/store"
)
2024-01-08 21:17:21 +08:00
const (
2024-01-27 11:14:17 +08:00
DefaultPageSize = 10
2024-01-08 21:17:21 +08:00
MaxContentLength = 8 * 1024
ChunkSize = 64 * 1024 // 64 KiB
2024-01-08 21:17:21 +08:00
)
2023-10-27 09:07:35 +08:00
func (s *APIV2Service) CreateMemo(ctx context.Context, request *apiv2pb.CreateMemoRequest) (*apiv2pb.CreateMemoResponse, error) {
2023-10-01 14:44:10 +08:00
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get user")
}
if user == nil {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
2024-01-08 21:17:21 +08:00
if len(request.Content) > MaxContentLength {
return nil, status.Errorf(codes.InvalidArgument, "content too long")
}
2023-10-01 14:44:10 +08:00
create := &store.Memo{
2024-01-20 23:48:35 +08:00
ResourceName: shortuuid.New(),
CreatorID: user.ID,
Content: request.Content,
2024-01-28 07:13:11 +08:00
Visibility: convertVisibilityToStore(request.Visibility),
2023-10-01 14:44:10 +08:00
}
// Find disable public memos system setting.
disablePublicMemosSystem, err := s.getDisablePublicMemosSystemSettingValue(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get system setting")
}
if disablePublicMemosSystem && create.Visibility == store.Public {
return nil, status.Errorf(codes.PermissionDenied, "disable public memos system setting is enabled")
}
2023-10-01 14:44:10 +08:00
memo, err := s.Store.CreateMemo(ctx, create)
if err != nil {
return nil, err
}
metric.Enqueue("memo create")
2023-10-01 14:44:10 +08:00
2023-12-19 23:49:24 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memo)
2023-12-17 09:53:22 +08:00
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
// Try to dispatch webhook when memo is created.
if err := s.DispatchMemoCreatedWebhook(ctx, memoMessage); err != nil {
log.Warn("Failed to dispatch memo created webhook", zap.Error(err))
}
2023-10-01 14:44:10 +08:00
response := &apiv2pb.CreateMemoResponse{
2023-12-17 09:53:22 +08:00
Memo: memoMessage,
2023-10-01 14:44:10 +08:00
}
return response, nil
}
2023-10-27 09:07:35 +08:00
func (s *APIV2Service) ListMemos(ctx context.Context, request *apiv2pb.ListMemosRequest) (*apiv2pb.ListMemosResponse, error) {
2024-02-04 20:54:17 +08:00
memoFind := &store.FindMemo{
// Exclude comments by default.
ExcludeComments: true,
}
if err := s.buildMemoFindWithFilter(ctx, memoFind, request.Filter); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to build find memos with filter")
}
2024-01-27 11:14:17 +08:00
var limit, offset int
if request.PageToken != "" {
var pageToken apiv2pb.PageToken
if err := unmarshalPageToken(request.PageToken, &pageToken); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid page token: %v", err)
}
limit = int(pageToken.Limit)
offset = int(pageToken.Offset)
} else {
limit = int(request.PageSize)
}
if limit <= 0 {
limit = DefaultPageSize
}
2024-01-27 11:14:17 +08:00
limitPlusOne := limit + 1
memoFind.Limit = &limitPlusOne
2024-02-05 06:40:55 +08:00
memoFind.Offset = &offset
memos, err := s.Store.ListMemos(ctx, memoFind)
if err != nil {
2024-02-05 06:40:55 +08:00
return nil, status.Errorf(codes.Internal, "failed to list memos")
}
2024-01-27 11:14:17 +08:00
memoMessages := []*apiv2pb.Memo{}
nextPageToken := ""
if len(memos) == limitPlusOne {
memos = memos[:limit]
nextPageToken, err = getPageToken(limit, offset+limit)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get next page token, error: %v", err)
}
}
for _, memo := range memos {
2023-12-19 23:49:24 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memo)
2023-12-17 09:53:22 +08:00
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
2024-01-27 11:14:17 +08:00
memoMessages = append(memoMessages, memoMessage)
}
response := &apiv2pb.ListMemosResponse{
2024-01-27 11:14:17 +08:00
Memos: memoMessages,
NextPageToken: nextPageToken,
}
return response, nil
}
2023-10-27 09:07:35 +08:00
func (s *APIV2Service) GetMemo(ctx context.Context, request *apiv2pb.GetMemoRequest) (*apiv2pb.GetMemoResponse, error) {
2023-08-05 19:51:32 +08:00
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{
ID: &request.Id,
})
if err != nil {
return nil, err
}
if memo == nil {
return nil, status.Errorf(codes.NotFound, "memo not found")
}
if memo.Visibility != store.Public {
2023-09-14 20:16:17 +08:00
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get user")
}
if user == nil {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
2023-08-05 19:51:32 +08:00
}
2023-09-14 20:16:17 +08:00
if memo.Visibility == store.Private && memo.CreatorID != user.ID {
2023-08-05 19:51:32 +08:00
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
}
2023-12-19 23:49:24 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memo)
2023-12-17 09:53:22 +08:00
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
2023-08-05 19:51:32 +08:00
response := &apiv2pb.GetMemoResponse{
2023-12-17 09:53:22 +08:00
Memo: memoMessage,
2023-08-05 19:51:32 +08:00
}
return response, nil
}
2024-01-20 23:48:35 +08:00
func (s *APIV2Service) GetMemoByName(ctx context.Context, request *apiv2pb.GetMemoByNameRequest) (*apiv2pb.GetMemoByNameResponse, error) {
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{
ResourceName: &request.Name,
})
if err != nil {
return nil, err
}
if memo == nil {
return nil, status.Errorf(codes.NotFound, "memo not found")
}
2024-01-21 10:57:53 +08:00
if memo.Visibility != store.Public {
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get user")
}
if user == nil {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
if memo.Visibility == store.Private && memo.CreatorID != user.ID {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
}
2024-01-20 23:48:35 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memo)
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
response := &apiv2pb.GetMemoByNameResponse{
Memo: memoMessage,
}
return response, nil
}
2023-12-20 23:14:15 +08:00
func (s *APIV2Service) UpdateMemo(ctx context.Context, request *apiv2pb.UpdateMemoRequest) (*apiv2pb.UpdateMemoResponse, error) {
if request.UpdateMask == nil || len(request.UpdateMask.Paths) == 0 {
return nil, status.Errorf(codes.InvalidArgument, "update mask is required")
}
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{
ID: &request.Id,
})
if err != nil {
return nil, err
}
if memo == nil {
return nil, status.Errorf(codes.NotFound, "memo not found")
}
user, _ := getCurrentUser(ctx, s.Store)
if memo.CreatorID != user.ID {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
2023-12-22 09:01:30 +08:00
currentTs := time.Now().Unix()
2023-12-20 23:14:15 +08:00
update := &store.UpdateMemo{
2023-12-22 09:01:30 +08:00
ID: request.Id,
UpdatedTs: &currentTs,
2023-12-20 23:14:15 +08:00
}
for _, path := range request.UpdateMask.Paths {
if path == "content" {
update.Content = &request.Memo.Content
2024-01-20 23:48:35 +08:00
} else if path == "resource_name" {
update.ResourceName = &request.Memo.Name
if !util.ResourceNameMatcher.MatchString(*update.ResourceName) {
return nil, status.Errorf(codes.InvalidArgument, "invalid resource name")
}
2023-12-20 23:14:15 +08:00
} else if path == "visibility" {
visibility := convertVisibilityToStore(request.Memo.Visibility)
// Find disable public memos system setting.
disablePublicMemosSystem, err := s.getDisablePublicMemosSystemSettingValue(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get system setting")
}
if disablePublicMemosSystem && visibility == store.Public {
return nil, status.Errorf(codes.PermissionDenied, "disable public memos system setting is enabled")
}
2023-12-20 23:14:15 +08:00
update.Visibility = &visibility
} else if path == "row_status" {
rowStatus := convertRowStatusToStore(request.Memo.RowStatus)
println("rowStatus", rowStatus)
update.RowStatus = &rowStatus
2023-12-21 23:40:43 +08:00
} else if path == "created_ts" {
createdTs := request.Memo.CreateTime.AsTime().Unix()
update.CreatedTs = &createdTs
2023-12-22 00:31:29 +08:00
} else if path == "pinned" {
if _, err := s.Store.UpsertMemoOrganizer(ctx, &store.MemoOrganizer{
MemoID: request.Id,
UserID: user.ID,
Pinned: request.Memo.Pinned,
}); err != nil {
return nil, status.Errorf(codes.Internal, "failed to upsert memo organizer")
}
2023-12-20 23:14:15 +08:00
}
}
2024-01-08 21:17:21 +08:00
if update.Content != nil && len(*update.Content) > MaxContentLength {
return nil, status.Errorf(codes.InvalidArgument, "content too long")
}
2023-12-20 23:14:15 +08:00
if err = s.Store.UpdateMemo(ctx, update); err != nil {
return nil, status.Errorf(codes.Internal, "failed to update memo")
}
memo, err = s.Store.GetMemo(ctx, &store.FindMemo{
ID: &request.Id,
})
if err != nil {
return nil, errors.Wrap(err, "failed to get memo")
}
memoMessage, err := s.convertMemoFromStore(ctx, memo)
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
// Try to dispatch webhook when memo is updated.
if err := s.DispatchMemoUpdatedWebhook(ctx, memoMessage); err != nil {
log.Warn("Failed to dispatch memo updated webhook", zap.Error(err))
}
2023-12-20 23:14:15 +08:00
return &apiv2pb.UpdateMemoResponse{
Memo: memoMessage,
}, nil
}
func (s *APIV2Service) DeleteMemo(ctx context.Context, request *apiv2pb.DeleteMemoRequest) (*apiv2pb.DeleteMemoResponse, error) {
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{
ID: &request.Id,
})
if err != nil {
return nil, err
}
if memo == nil {
return nil, status.Errorf(codes.NotFound, "memo not found")
}
user, _ := getCurrentUser(ctx, s.Store)
if memo.CreatorID != user.ID {
return nil, status.Errorf(codes.PermissionDenied, "permission denied")
}
if memoMessage, err := s.convertMemoFromStore(ctx, memo); err == nil {
// Try to dispatch webhook when memo is deleted.
if err := s.DispatchMemoDeletedWebhook(ctx, memoMessage); err != nil {
log.Warn("Failed to dispatch memo deleted webhook", zap.Error(err))
}
}
2023-12-20 23:14:15 +08:00
if err = s.Store.DeleteMemo(ctx, &store.DeleteMemo{
ID: request.Id,
}); err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete memo")
}
return &apiv2pb.DeleteMemoResponse{}, nil
}
func (s *APIV2Service) CreateMemoComment(ctx context.Context, request *apiv2pb.CreateMemoCommentRequest) (*apiv2pb.CreateMemoCommentResponse, error) {
relatedMemo, err := s.Store.GetMemo(ctx, &store.FindMemo{ID: &request.Id})
2023-12-21 21:24:08 +08:00
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get memo")
2023-12-21 21:24:08 +08:00
}
2023-10-01 14:44:10 +08:00
// Create the comment memo first.
createMemoResponse, err := s.CreateMemo(ctx, request.Create)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create memo")
}
// Build the relation between the comment memo and the original memo.
memo := createMemoResponse.Memo
_, err = s.Store.UpsertMemoRelation(ctx, &store.MemoRelation{
MemoID: memo.Id,
RelatedMemoID: request.Id,
Type: store.MemoRelationComment,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create memo relation")
}
2024-01-03 08:19:38 +08:00
if memo.Visibility != apiv2pb.Visibility_PRIVATE && memo.CreatorId != relatedMemo.CreatorID {
activity, err := s.Store.CreateActivity(ctx, &store.Activity{
CreatorID: memo.CreatorId,
Type: store.ActivityTypeMemoComment,
Level: store.ActivityLevelInfo,
Payload: &storepb.ActivityPayload{
MemoComment: &storepb.ActivityMemoCommentPayload{
MemoId: memo.Id,
RelatedMemoId: request.Id,
},
},
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create activity")
}
if _, err := s.Store.CreateInbox(ctx, &store.Inbox{
SenderID: memo.CreatorId,
ReceiverID: relatedMemo.CreatorID,
Status: store.UNREAD,
Message: &storepb.InboxMessage{
Type: storepb.InboxMessage_TYPE_MEMO_COMMENT,
ActivityId: &activity.ID,
},
}); err != nil {
return nil, status.Errorf(codes.Internal, "failed to create inbox")
}
}
metric.Enqueue("memo comment create")
2023-10-01 14:44:10 +08:00
response := &apiv2pb.CreateMemoCommentResponse{
Memo: memo,
}
return response, nil
}
2023-10-27 09:07:35 +08:00
func (s *APIV2Service) ListMemoComments(ctx context.Context, request *apiv2pb.ListMemoCommentsRequest) (*apiv2pb.ListMemoCommentsResponse, error) {
2023-10-01 14:44:10 +08:00
memoRelationComment := store.MemoRelationComment
memoRelations, err := s.Store.ListMemoRelations(ctx, &store.FindMemoRelation{
RelatedMemoID: &request.Id,
Type: &memoRelationComment,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list memo relations")
}
var memos []*apiv2pb.Memo
for _, memoRelation := range memoRelations {
memo, err := s.Store.GetMemo(ctx, &store.FindMemo{
ID: &memoRelation.MemoID,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get memo")
}
if memo != nil {
2023-12-19 23:49:24 +08:00
memoMessage, err := s.convertMemoFromStore(ctx, memo)
2023-12-17 09:53:22 +08:00
if err != nil {
return nil, errors.Wrap(err, "failed to convert memo")
}
memos = append(memos, memoMessage)
2023-10-01 14:44:10 +08:00
}
}
response := &apiv2pb.ListMemoCommentsResponse{
Memos: memos,
}
return response, nil
}
func (s *APIV2Service) GetUserMemosStats(ctx context.Context, request *apiv2pb.GetUserMemosStatsRequest) (*apiv2pb.GetUserMemosStatsResponse, error) {
username, err := ExtractUsernameFromName(request.Name)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "invalid username")
}
user, err := s.Store.GetUser(ctx, &store.FindUser{
Username: &username,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get user")
}
if user == nil {
return nil, status.Errorf(codes.NotFound, "user not found")
}
normalRowStatus := store.Normal
2024-01-17 09:17:33 +08:00
memoFind := &store.FindMemo{
CreatorID: &user.ID,
RowStatus: &normalRowStatus,
ExcludeComments: true,
ExcludeContent: true,
2024-01-17 09:17:33 +08:00
}
2024-02-04 20:54:17 +08:00
if err := s.buildMemoFindWithFilter(ctx, memoFind, request.Filter); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "failed to build find memos with filter")
2024-01-18 08:06:59 +08:00
}
2024-01-17 09:17:33 +08:00
memos, err := s.Store.ListMemos(ctx, memoFind)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to list memos")
}
location, err := time.LoadLocation(request.Timezone)
if err != nil {
return nil, status.Errorf(codes.Internal, "invalid timezone location")
}
2024-02-04 20:54:17 +08:00
displayWithUpdatedTs, err := s.getMemoDisplayWithUpdatedTsSettingValue(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get memo display with updated ts setting value")
}
2024-01-17 09:17:33 +08:00
stats := make(map[string]int32)
for _, memo := range memos {
2024-01-17 09:17:33 +08:00
displayTs := memo.CreatedTs
if displayWithUpdatedTs {
displayTs = memo.UpdatedTs
}
stats[time.Unix(displayTs, 0).In(location).Format("2006-01-02")]++
}
response := &apiv2pb.GetUserMemosStatsResponse{
2024-01-17 09:17:33 +08:00
Stats: stats,
}
return response, nil
}
2024-02-04 20:20:14 +08:00
func (s *APIV2Service) ExportMemos(ctx context.Context, request *apiv2pb.ExportMemosRequest) (*apiv2pb.ExportMemosResponse, error) {
2024-02-04 20:54:17 +08:00
normalRowStatus := store.Normal
memoFind := &store.FindMemo{
RowStatus: &normalRowStatus,
// Exclude comments by default.
ExcludeComments: true,
}
if err := s.buildMemoFindWithFilter(ctx, memoFind, request.Filter); err != nil {
2024-02-04 20:20:14 +08:00
return nil, status.Errorf(codes.Internal, "failed to build find memos with filter")
}
memos, err := s.Store.ListMemos(ctx, memoFind)
if err != nil {
2024-02-04 20:20:14 +08:00
return nil, status.Errorf(codes.Internal, "failed to list memos")
}
buf := new(bytes.Buffer)
writer := zip.NewWriter(buf)
for _, memo := range memos {
memoMessage, err := s.convertMemoFromStore(ctx, memo)
if err != nil {
2024-02-04 20:20:14 +08:00
return nil, errors.Wrap(err, "failed to convert memo")
}
file, err := writer.Create(time.Unix(memo.CreatedTs, 0).Format(time.RFC3339) + ".md")
if err != nil {
2024-02-04 20:20:14 +08:00
return nil, status.Errorf(codes.Internal, "Failed to create memo file")
}
_, err = file.Write([]byte(memoMessage.Content))
if err != nil {
2024-02-04 20:20:14 +08:00
return nil, status.Errorf(codes.Internal, "Failed to write to memo file")
}
}
2024-02-04 20:54:17 +08:00
if err := writer.Close(); err != nil {
2024-02-04 20:20:14 +08:00
return nil, status.Errorf(codes.Internal, "Failed to close zip file writer")
}
2024-02-04 20:20:14 +08:00
return &apiv2pb.ExportMemosResponse{
Content: buf.Bytes(),
}, nil
}
2023-12-19 23:49:24 +08:00
func (s *APIV2Service) convertMemoFromStore(ctx context.Context, memo *store.Memo) (*apiv2pb.Memo, error) {
displayTs := memo.CreatedTs
if displayWithUpdatedTs, err := s.getMemoDisplayWithUpdatedTsSettingValue(ctx); err == nil && displayWithUpdatedTs {
displayTs = memo.UpdatedTs
}
2023-12-21 22:42:06 +08:00
creator, err := s.Store.GetUser(ctx, &store.FindUser{ID: &memo.CreatorID})
if err != nil {
return nil, errors.Wrap(err, "failed to get creator")
}
2023-12-22 20:18:31 +08:00
listMemoRelationsResponse, err := s.ListMemoRelations(ctx, &apiv2pb.ListMemoRelationsRequest{Id: memo.ID})
if err != nil {
return nil, errors.Wrap(err, "failed to list memo relations")
}
listMemoResourcesResponse, err := s.ListMemoResources(ctx, &apiv2pb.ListMemoResourcesRequest{Id: memo.ID})
if err != nil {
return nil, errors.Wrap(err, "failed to list memo resources")
}
2023-12-19 23:49:24 +08:00
return &apiv2pb.Memo{
Id: int32(memo.ID),
2024-01-20 23:48:35 +08:00
Name: memo.ResourceName,
2023-12-19 23:49:24 +08:00
RowStatus: convertRowStatusFromStore(memo.RowStatus),
2023-12-21 22:42:06 +08:00
Creator: fmt.Sprintf("%s%s", UserNamePrefix, creator.Username),
CreatorId: int32(memo.CreatorID),
2023-12-19 23:49:24 +08:00
CreateTime: timestamppb.New(time.Unix(memo.CreatedTs, 0)),
UpdateTime: timestamppb.New(time.Unix(memo.UpdatedTs, 0)),
DisplayTime: timestamppb.New(time.Unix(displayTs, 0)),
Content: memo.Content,
Visibility: convertVisibilityFromStore(memo.Visibility),
Pinned: memo.Pinned,
ParentId: memo.ParentID,
2023-12-22 20:18:31 +08:00
Relations: listMemoRelationsResponse.Relations,
Resources: listMemoResourcesResponse.Resources,
2023-12-19 23:49:24 +08:00
}, nil
}
func (s *APIV2Service) getMemoDisplayWithUpdatedTsSettingValue(ctx context.Context) (bool, error) {
memoDisplayWithUpdatedTsSetting, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
2023-12-19 23:49:24 +08:00
Name: apiv1.SystemSettingMemoDisplayWithUpdatedTsName.String(),
})
if err != nil {
return false, errors.Wrap(err, "failed to find system setting")
}
2024-01-18 19:20:48 +08:00
if memoDisplayWithUpdatedTsSetting == nil {
return false, nil
}
2023-12-19 23:49:24 +08:00
memoDisplayWithUpdatedTs := false
2024-01-18 19:23:45 +08:00
if err := json.Unmarshal([]byte(memoDisplayWithUpdatedTsSetting.Value), &memoDisplayWithUpdatedTs); err != nil {
return false, errors.Wrap(err, "failed to unmarshal system setting value")
2023-12-19 23:49:24 +08:00
}
return memoDisplayWithUpdatedTs, nil
}
func (s *APIV2Service) getDisablePublicMemosSystemSettingValue(ctx context.Context) (bool, error) {
disablePublicMemosSystemSetting, err := s.Store.GetWorkspaceSetting(ctx, &store.FindWorkspaceSetting{
Name: apiv1.SystemSettingDisablePublicMemosName.String(),
})
if err != nil {
return false, errors.Wrap(err, "failed to find system setting")
}
2024-01-18 19:20:48 +08:00
if disablePublicMemosSystemSetting == nil {
return false, nil
}
disablePublicMemos := false
2024-01-18 19:23:45 +08:00
if err := json.Unmarshal([]byte(disablePublicMemosSystemSetting.Value), &disablePublicMemos); err != nil {
return false, errors.Wrap(err, "failed to unmarshal system setting value")
}
return disablePublicMemos, nil
}
2023-12-19 23:49:24 +08:00
func convertVisibilityFromStore(visibility store.Visibility) apiv2pb.Visibility {
switch visibility {
case store.Private:
return apiv2pb.Visibility_PRIVATE
case store.Protected:
return apiv2pb.Visibility_PROTECTED
case store.Public:
return apiv2pb.Visibility_PUBLIC
default:
return apiv2pb.Visibility_VISIBILITY_UNSPECIFIED
}
}
2023-12-20 23:14:15 +08:00
func convertVisibilityToStore(visibility apiv2pb.Visibility) store.Visibility {
switch visibility {
case apiv2pb.Visibility_PRIVATE:
return store.Private
case apiv2pb.Visibility_PROTECTED:
return store.Protected
case apiv2pb.Visibility_PUBLIC:
return store.Public
default:
return store.Private
}
}
2024-02-05 06:40:55 +08:00
func (s *APIV2Service) buildMemoFindWithFilter(ctx context.Context, find *store.FindMemo, filter string) error {
user, _ := getCurrentUser(ctx, s.Store)
if find == nil {
find = &store.FindMemo{}
}
if filter != "" {
filter, err := parseListMemosFilter(filter)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err)
}
if len(filter.ContentSearch) > 0 {
find.ContentSearch = filter.ContentSearch
}
if len(filter.Visibilities) > 0 {
find.VisibilityList = filter.Visibilities
}
if filter.OrderByPinned {
find.OrderByPinned = filter.OrderByPinned
}
if filter.DisplayTimeAfter != nil {
displayWithUpdatedTs, err := s.getMemoDisplayWithUpdatedTsSettingValue(ctx)
if err != nil {
return status.Errorf(codes.Internal, "failed to get memo display with updated ts setting value")
}
if displayWithUpdatedTs {
find.UpdatedTsAfter = filter.DisplayTimeAfter
} else {
find.CreatedTsAfter = filter.DisplayTimeAfter
}
}
if filter.DisplayTimeBefore != nil {
displayWithUpdatedTs, err := s.getMemoDisplayWithUpdatedTsSettingValue(ctx)
if err != nil {
return status.Errorf(codes.Internal, "failed to get memo display with updated ts setting value")
}
if displayWithUpdatedTs {
find.UpdatedTsBefore = filter.DisplayTimeBefore
} else {
find.CreatedTsBefore = filter.DisplayTimeBefore
}
}
if filter.Creator != nil {
username, err := ExtractUsernameFromName(*filter.Creator)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid creator name")
}
user, err := s.Store.GetUser(ctx, &store.FindUser{
Username: &username,
})
if err != nil {
return status.Errorf(codes.Internal, "failed to get user")
}
if user == nil {
return status.Errorf(codes.NotFound, "user not found")
}
find.CreatorID = &user.ID
}
if filter.RowStatus != nil {
find.RowStatus = filter.RowStatus
}
}
// If the user is not authenticated, only public memos are visible.
if user == nil {
if filter == "" {
// If no filter is provided, return an error.
return status.Errorf(codes.InvalidArgument, "filter is required")
}
find.VisibilityList = []store.Visibility{store.Public}
} else if find.CreatorID != nil && *find.CreatorID != user.ID {
find.VisibilityList = []store.Visibility{store.Public, store.Protected}
}
displayWithUpdatedTs, err := s.getMemoDisplayWithUpdatedTsSettingValue(ctx)
if err != nil {
return status.Errorf(codes.Internal, "failed to get memo display with updated ts setting value")
}
if displayWithUpdatedTs {
find.OrderByUpdatedTs = true
}
return nil
}
2023-09-13 20:42:44 +08:00
// ListMemosFilterCELAttributes are the CEL attributes for ListMemosFilter.
var ListMemosFilterCELAttributes = []cel.EnvOption{
2023-12-22 09:09:03 +08:00
cel.Variable("content_search", cel.ListType(cel.StringType)),
2023-12-21 23:40:43 +08:00
cel.Variable("visibilities", cel.ListType(cel.StringType)),
2023-12-22 09:09:03 +08:00
cel.Variable("order_by_pinned", cel.BoolType),
2024-01-18 14:30:20 +08:00
cel.Variable("display_time_before", cel.IntType),
cel.Variable("display_time_after", cel.IntType),
2023-12-19 23:49:24 +08:00
cel.Variable("creator", cel.StringType),
cel.Variable("row_status", cel.StringType),
2023-09-13 20:42:44 +08:00
}
type ListMemosFilter struct {
2024-01-18 14:30:20 +08:00
ContentSearch []string
Visibilities []store.Visibility
OrderByPinned bool
DisplayTimeBefore *int64
DisplayTimeAfter *int64
Creator *string
RowStatus *store.RowStatus
2023-09-13 20:42:44 +08:00
}
func parseListMemosFilter(expression string) (*ListMemosFilter, error) {
e, err := cel.NewEnv(ListMemosFilterCELAttributes...)
if err != nil {
2023-09-13 20:42:44 +08:00
return nil, err
}
2023-09-13 20:42:44 +08:00
ast, issues := e.Compile(expression)
if issues != nil {
2023-09-13 20:42:44 +08:00
return nil, errors.Errorf("found issue %v", issues)
}
2023-09-13 20:42:44 +08:00
filter := &ListMemosFilter{}
expr, err := cel.AstToParsedExpr(ast)
if err != nil {
return nil, err
}
callExpr := expr.GetExpr().GetCallExpr()
2023-09-13 20:42:44 +08:00
findField(callExpr, filter)
return filter, nil
}
2023-12-17 09:53:22 +08:00
func findField(callExpr *expr.Expr_Call, filter *ListMemosFilter) {
2023-09-13 20:42:44 +08:00
if len(callExpr.Args) == 2 {
idExpr := callExpr.Args[0].GetIdentExpr()
if idExpr != nil {
2023-12-22 00:31:29 +08:00
if idExpr.Name == "content_search" {
contentSearch := []string{}
for _, expr := range callExpr.Args[1].GetListExpr().GetElements() {
value := expr.GetConstExpr().GetStringValue()
contentSearch = append(contentSearch, value)
}
filter.ContentSearch = contentSearch
} else if idExpr.Name == "visibilities" {
2023-12-21 23:40:43 +08:00
visibilities := []store.Visibility{}
for _, expr := range callExpr.Args[1].GetListExpr().GetElements() {
value := expr.GetConstExpr().GetStringValue()
visibilities = append(visibilities, store.Visibility(value))
}
filter.Visibilities = visibilities
2023-12-22 09:09:03 +08:00
} else if idExpr.Name == "order_by_pinned" {
value := callExpr.Args[1].GetConstExpr().GetBoolValue()
filter.OrderByPinned = value
2024-01-18 14:30:20 +08:00
} else if idExpr.Name == "display_time_before" {
displayTimeBefore := callExpr.Args[1].GetConstExpr().GetInt64Value()
filter.DisplayTimeBefore = &displayTimeBefore
} else if idExpr.Name == "display_time_after" {
displayTimeAfter := callExpr.Args[1].GetConstExpr().GetInt64Value()
filter.DisplayTimeAfter = &displayTimeAfter
2023-12-22 00:31:29 +08:00
} else if idExpr.Name == "creator" {
2023-12-19 23:49:24 +08:00
creator := callExpr.Args[1].GetConstExpr().GetStringValue()
filter.Creator = &creator
2023-12-22 00:31:29 +08:00
} else if idExpr.Name == "row_status" {
2023-12-19 23:49:24 +08:00
rowStatus := store.RowStatus(callExpr.Args[1].GetConstExpr().GetStringValue())
filter.RowStatus = &rowStatus
}
2023-09-13 20:42:44 +08:00
return
}
}
2023-09-13 20:42:44 +08:00
for _, arg := range callExpr.Args {
callExpr := arg.GetCallExpr()
if callExpr != nil {
findField(callExpr, filter)
}
}
}
// DispatchMemoCreatedWebhook dispatches webhook when memo is created.
func (s *APIV2Service) DispatchMemoCreatedWebhook(ctx context.Context, memo *apiv2pb.Memo) error {
return s.dispatchMemoRelatedWebhook(ctx, memo, "memos.memo.created")
}
// DispatchMemoUpdatedWebhook dispatches webhook when memo is updated.
func (s *APIV2Service) DispatchMemoUpdatedWebhook(ctx context.Context, memo *apiv2pb.Memo) error {
return s.dispatchMemoRelatedWebhook(ctx, memo, "memos.memo.updated")
}
// DispatchMemoDeletedWebhook dispatches webhook when memo is deleted.
func (s *APIV2Service) DispatchMemoDeletedWebhook(ctx context.Context, memo *apiv2pb.Memo) error {
return s.dispatchMemoRelatedWebhook(ctx, memo, "memos.memo.deleted")
}
func (s *APIV2Service) dispatchMemoRelatedWebhook(ctx context.Context, memo *apiv2pb.Memo, activityType string) error {
webhooks, err := s.Store.ListWebhooks(ctx, &store.FindWebhook{
CreatorID: &memo.CreatorId,
})
if err != nil {
return err
}
metric.Enqueue("webhook dispatch")
for _, hook := range webhooks {
payload := convertMemoToWebhookPayload(memo)
payload.ActivityType = activityType
payload.URL = hook.Url
err := webhook.Post(*payload)
if err != nil {
return errors.Wrap(err, "failed to post webhook")
}
}
return nil
}
func convertMemoToWebhookPayload(memo *apiv2pb.Memo) *webhook.WebhookPayload {
return &webhook.WebhookPayload{
CreatorID: memo.CreatorId,
CreatedTs: time.Now().Unix(),
Memo: &webhook.Memo{
ID: memo.Id,
CreatorID: memo.CreatorId,
CreatedTs: memo.CreateTime.Seconds,
UpdatedTs: memo.UpdateTime.Seconds,
Content: memo.Content,
Visibility: memo.Visibility.String(),
Pinned: memo.Pinned,
ResourceList: func() []*webhook.Resource {
resources := []*webhook.Resource{}
for _, resource := range memo.Resources {
resources = append(resources, &webhook.Resource{
ID: resource.Id,
Filename: resource.Filename,
ExternalLink: resource.ExternalLink,
Type: resource.Type,
Size: resource.Size,
})
}
return resources
}(),
RelationList: func() []*webhook.MemoRelation {
relations := []*webhook.MemoRelation{}
for _, relation := range memo.Relations {
relations = append(relations, &webhook.MemoRelation{
MemoID: relation.MemoId,
RelatedMemoID: relation.RelatedMemoId,
Type: relation.Type.String(),
})
}
return relations
}(),
},
}
}