From 66b9cb49c14e34e8e3c1f996f43d0360864ab4db Mon Sep 17 00:00:00 2001 From: ABird Date: Mon, 24 Aug 2026 23:13:55 +0800 Subject: [PATCH] feat(spaces): add space-aware UI and filtering (#6230) --- internal/filter/engine_test.go | 27 +++ internal/filter/schema.go | 31 ++++ proto/api/v1/attachment_service.proto | 9 +- proto/api/v1/memo_service.proto | 12 +- proto/api/v1/user_service.proto | 10 ++ proto/gen/api/v1/attachment_service.pb.go | 11 +- proto/gen/api/v1/memo_service.pb.go | 68 +------ proto/gen/api/v1/user_service.pb.go | 21 ++- proto/gen/api/v1/user_service.pb.gw.go | 14 ++ proto/gen/openapi.yaml | 27 +-- server/router/api/v1/attachment_service.go | 23 +-- server/router/api/v1/filter_access.go | 145 +++++++++++++++ server/router/api/v1/memo_service.go | 25 +-- .../api/v1/test/attachment_service_test.go | 103 +++++++++++ .../api/v1/test/user_service_stats_test.go | 102 +++++++++++ server/router/api/v1/user_service_stats.go | 13 +- store/db/mysql/attachment.go | 1 + store/db/mysql/memo.go | 7 +- store/db/postgres/attachment.go | 1 + store/db/postgres/memo.go | 7 +- store/db/sqlite/attachment.go | 1 + store/db/sqlite/memo.go | 7 +- store/memo.go | 2 - store/test/attachment_access_test.go | 71 ++++++++ web/src/components/AppSidebar/AppSidebar.tsx | 53 ++++-- .../components/AppSidebar/SpaceSwitcher.tsx | 136 ++++++++++++++ web/src/components/CreateSpaceDialog.tsx | 105 +++++++++++ .../MemoEditor/Toolbar/VisibilitySelector.tsx | 21 ++- .../MemoEditor/hooks/useMemoSave.ts | 7 +- web/src/components/MemoEditor/index.tsx | 2 + .../MemoEditor/services/memoService.ts | 2 + .../components/MemoEditor/types/components.ts | 2 + .../MemoView/components/MemoHeader.tsx | 7 +- web/src/components/MemosLogo.tsx | 19 +- .../PagedMemoList/PagedMemoList.tsx | 4 +- .../Settings/PreferencesSection.tsx | 9 +- web/src/components/VisibilityIcon.tsx | 13 +- web/src/connect.ts | 2 + web/src/contexts/GlobalMemoEditorContext.tsx | 23 ++- web/src/contexts/SpaceContext.tsx | 144 +++++++++++++++ web/src/hooks/useAttachmentLibrary.ts | 16 +- web/src/hooks/useFilteredMemoStats.ts | 18 +- web/src/hooks/useLiveMemoRefresh.ts | 2 + web/src/hooks/useMemoFilters.ts | 15 +- web/src/hooks/useMemoQueries.ts | 7 + web/src/hooks/useSpaceQueries.ts | 52 ++++++ web/src/hooks/useUserQueries.ts | 9 +- web/src/layouts/RootLayout.tsx | 17 +- web/src/lib/cel-filter.ts | 6 + web/src/lib/resource-names.ts | 4 + web/src/locales/en.json | 17 +- web/src/pages/Archived.tsx | 3 + web/src/pages/Attachments.tsx | 27 ++- web/src/pages/Explore.tsx | 9 +- web/src/pages/Home.tsx | 11 +- .../proto/api/v1/attachment_service_pb.ts | 8 +- web/src/types/proto/api/v1/memo_service_pb.ts | 26 +-- web/src/types/proto/api/v1/user_service_pb.ts | 10 +- web/src/utils/memo.ts | 97 +++++++--- web/tests/app-sidebar-logo.test.tsx | 73 +++++++- web/tests/attachment-library-stats.test.ts | 21 ++- web/tests/create-space-dialog.test.tsx | 77 ++++++++ web/tests/filtered-memo-stats.test.ts | 51 +++++- web/tests/global-memo-editor.test.tsx | 22 +++ web/tests/home-loading-boundary.test.tsx | 47 ++++- web/tests/insert-menu.test.tsx | 1 + web/tests/live-memo-refresh.test.tsx | 8 + web/tests/memo-editor-relations.test.ts | 36 +++- web/tests/memo-views.test.ts | 10 ++ web/tests/paged-memo-list.test.tsx | 31 +++- web/tests/root-layout-global-editor.test.tsx | 5 + web/tests/space-context.test.tsx | 167 ++++++++++++++++++ web/tests/space-feed-pages.test.tsx | 73 ++++++++ web/tests/space-queries.test.tsx | 71 ++++++++ web/tests/space-switcher.test.tsx | 90 ++++++++++ web/tests/use-memo-save.test.tsx | 61 +++++++ web/tests/user-stats-filter-queries.test.tsx | 46 +++++ web/tests/visibility-selector.test.tsx | 71 ++++++++ web/tests/visibility-space.test.tsx | 63 +++++++ 79 files changed, 2320 insertions(+), 345 deletions(-) create mode 100644 server/router/api/v1/filter_access.go create mode 100644 web/src/components/AppSidebar/SpaceSwitcher.tsx create mode 100644 web/src/components/CreateSpaceDialog.tsx create mode 100644 web/src/contexts/SpaceContext.tsx create mode 100644 web/src/hooks/useSpaceQueries.ts create mode 100644 web/src/lib/cel-filter.ts create mode 100644 web/tests/create-space-dialog.test.tsx create mode 100644 web/tests/space-context.test.tsx create mode 100644 web/tests/space-feed-pages.test.tsx create mode 100644 web/tests/space-queries.test.tsx create mode 100644 web/tests/space-switcher.test.tsx create mode 100644 web/tests/use-memo-save.test.tsx create mode 100644 web/tests/user-stats-filter-queries.test.tsx create mode 100644 web/tests/visibility-selector.test.tsx create mode 100644 web/tests/visibility-space.test.tsx diff --git a/internal/filter/engine_test.go b/internal/filter/engine_test.go index 34356966..2f92fb9d 100644 --- a/internal/filter/engine_test.go +++ b/internal/filter/engine_test.go @@ -74,6 +74,33 @@ func TestCompileRejectsStartsWithOnUnsupportedField(t *testing.T) { require.Contains(t, err.Error(), "does not support text matching") } +func TestRenderSpaceFilters(t *testing.T) { + t.Parallel() + + for _, schema := range []Schema{NewSchema(), NewAttachmentSchema()} { + engine, err := NewEngine(schema) + require.NoError(t, err) + for _, dialect := range []DialectName{DialectSQLite, DialectMySQL, DialectPostgres} { + assigned, err := engine.CompileToStatement( + context.Background(), + `space == "spaces/team"`, + RenderOptions{Dialect: dialect}, + ) + require.NoError(t, err, schema.Name, dialect) + require.Contains(t, assigned.SQL, "spaces/", schema.Name, dialect) + require.Equal(t, []any{"spaces/team"}, assigned.Args, schema.Name, dialect) + + unassigned, err := engine.CompileToStatement(context.Background(), `space == null`, RenderOptions{Dialect: dialect}) + require.NoError(t, err, schema.Name, dialect) + require.Contains(t, unassigned.SQL, "IS NULL", schema.Name, dialect) + require.Empty(t, unassigned.Args, schema.Name, dialect) + } + + _, err = engine.Compile(context.Background(), `space != null`) + require.ErrorContains(t, err, `operator != not allowed for field "space"`) + } +} + func TestCompileContainsEscapesLikeWildcards(t *testing.T) { t.Parallel() diff --git a/internal/filter/schema.go b/internal/filter/schema.go index 6cf2838d..5e4a7b65 100644 --- a/internal/filter/schema.go +++ b/internal/filter/schema.go @@ -172,6 +172,20 @@ func NewSchema() Schema { CompareNeq: true, }, }, + "space": { + Name: "space", + Kind: FieldKindScalar, + Type: FieldTypeString, + Column: Column{Table: "memo_space", Name: "uid"}, + Expressions: map[DialectName]string{ + DialectSQLite: "CASE WHEN `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END", + DialectMySQL: "CASE WHEN `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE CONCAT('spaces/', %[1]s) END", + DialectPostgres: "CASE WHEN memo.space_id IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END", + }, + AllowedComparisonOps: map[ComparisonOperator]bool{ + CompareEq: true, + }, + }, "tags": { Name: "tags", Kind: FieldKindJSONList, @@ -252,6 +266,8 @@ func NewSchema() Schema { cel.Variable("tag", cel.StringType), cel.Variable("tags", cel.ListType(cel.StringType)), cel.Variable("visibility", cel.StringType), + // Dyn permits the explicit null comparison used for memos without a space. + cel.Variable("space", cel.DynType), cel.Variable("has_task_list", cel.BoolType), cel.Variable("has_link", cel.BoolType), cel.Variable("has_code", cel.BoolType), @@ -312,6 +328,20 @@ func NewAttachmentSchema() Schema { CompareNeq: true, }, }, + "space": { + Name: "space", + Kind: FieldKindScalar, + Type: FieldTypeString, + Column: Column{Table: "attachment_space", Name: "uid"}, + Expressions: map[DialectName]string{ + DialectSQLite: "CASE WHEN `attachment`.`memo_id` IS NULL OR `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END", + DialectMySQL: "CASE WHEN `attachment`.`memo_id` IS NULL OR `memo`.`space_id` IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE CONCAT('spaces/', %[1]s) END", + DialectPostgres: "CASE WHEN attachment.memo_id IS NULL OR memo.space_id IS NULL THEN NULL WHEN %[1]s IS NULL THEN '' ELSE ('spaces/' || %[1]s) END", + }, + AllowedComparisonOps: map[ComparisonOperator]bool{ + CompareEq: true, + }, + }, } envOptions := []cel.EnvOption{ @@ -319,6 +349,7 @@ func NewAttachmentSchema() Schema { cel.Variable("mime_type", cel.StringType), cel.Variable("create_time", cel.TimestampType), cel.Variable("memo_id", cel.AnyType), + cel.Variable("space", cel.DynType), cel.Variable("now", cel.TimestampType), cel.ASTValidators(cel.ValidateRegexLiterals()), } diff --git a/proto/api/v1/attachment_service.proto b/proto/api/v1/attachment_service.proto index a214ba22..f489ff60 100644 --- a/proto/api/v1/attachment_service.proto +++ b/proto/api/v1/attachment_service.proto @@ -193,12 +193,19 @@ message ListAttachmentsRequest { // Optional. Filter to apply to the list results. // Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")" // Supported operators: =, !=, <, <=, >, >=, : (contains), in - // Supported fields: filename, mime_type, create_time, memo + // Supported fields: filename, mime_type, create_time, memo_id, space. + // `space` only supports a non-negated `==` comparison with a Space resource + // name or null. + // `space` is the linked memo's space resource name, or null when the + // attachment is unlinked or its linked memo has no space. string filter = 3 [(google.api.field_behavior) = OPTIONAL]; // Optional. The order to sort results by. // Example: "create_time desc" or "filename asc" string order_by = 4 [(google.api.field_behavior) = OPTIONAL]; + + reserved 5, 6; + reserved "space", "unassigned"; } message ListAttachmentsResponse { diff --git a/proto/api/v1/memo_service.proto b/proto/api/v1/memo_service.proto index dfacf7d0..3f70995c 100644 --- a/proto/api/v1/memo_service.proto +++ b/proto/api/v1/memo_service.proto @@ -340,6 +340,7 @@ message ListMemosRequest { // content (string), creator (string, e.g. "users/1"), // created_ts / updated_ts (timestamp), pinned (bool), // visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE), + // space (string resource name or null when the memo has no space), // tags (list; match with `"work" in tags`, not `tag == "work"`), // has_task_list / has_link / has_code / has_incomplete_tasks (bool), // has_location (bool; true when the memo has a location attached). @@ -347,6 +348,7 @@ message ListMemosRequest { // the create_time / update_time names used by order_by. // Examples: // pinned == true && visibility == "PUBLIC" + // space == "spaces/team" or space == null // tags.exists(t, t == "urgent") // content.contains("roadmap") && created_ts > now - duration("168h") string filter = 5 [(google.api.field_behavior) = OPTIONAL]; @@ -354,14 +356,8 @@ message ListMemosRequest { // Optional. If true, show deleted memos in the response. bool show_deleted = 6 [(google.api.field_behavior) = OPTIONAL]; - oneof scope { - // Optional. Limit results to readable non-comment memos in a space of - // which the caller is an active member. - string space = 7 [(google.api.resource_reference) = {type: "memos.api.v1/Space"}]; - - // Optional. Limit results to memos with no space. Must be true when set. - bool unassigned = 8; - } + reserved 7, 8; + reserved "space", "unassigned"; } message ListMemosResponse { diff --git a/proto/api/v1/user_service.proto b/proto/api/v1/user_service.proto index 304921f1..82e7f0c3 100644 --- a/proto/api/v1/user_service.proto +++ b/proto/api/v1/user_service.proto @@ -399,6 +399,13 @@ message GetUserStatsRequest { (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = {type: "memos.api.v1/User"} ]; + + // Optional. CEL expression selecting the readable non-comment memos to + // include. Supports the same fields as ListMemos, including `space`. + string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + reserved 3; + reserved "space", "unassigned"; } message ListAllUserStatsRequest { @@ -408,6 +415,9 @@ message ListAllUserStatsRequest { // Optional. Filter to apply to memo stats. // Uses the same filter syntax as ListMemos. string filter = 2 [(google.api.field_behavior) = OPTIONAL]; + + reserved 3, 4; + reserved "space", "unassigned"; } message ListAllUserStatsResponse { diff --git a/proto/gen/api/v1/attachment_service.pb.go b/proto/gen/api/v1/attachment_service.pb.go index 279f5d11..b7d9c97c 100644 --- a/proto/gen/api/v1/attachment_service.pb.go +++ b/proto/gen/api/v1/attachment_service.pb.go @@ -783,7 +783,11 @@ type ListAttachmentsRequest struct { // Optional. Filter to apply to the list results. // Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")" // Supported operators: =, !=, <, <=, >, >=, : (contains), in - // Supported fields: filename, mime_type, create_time, memo + // Supported fields: filename, mime_type, create_time, memo_id, space. + // `space` only supports a non-negated `==` comparison with a Space resource + // name or null. + // `space` is the linked memo's space resource name, or null when the + // attachment is unlinked or its linked memo has no space. Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. The order to sort results by. // Example: "create_time desc" or "filename asc" @@ -1170,13 +1174,14 @@ const file_api_v1_attachment_service_proto_rawDesc = "" + "\n" + "attachment\x18\x01 \x01(\v2\x18.memos.api.v1.AttachmentB\x03\xe0A\x02R\n" + "attachment\x12(\n" + - "\rattachment_id\x18\x02 \x01(\tB\x03\xe0A\x01R\fattachmentId\"\x9b\x01\n" + + "\rattachment_id\x18\x02 \x01(\tB\x03\xe0A\x01R\fattachmentId\"\xba\x01\n" + "\x16ListAttachmentsRequest\x12 \n" + "\tpage_size\x18\x01 \x01(\x05B\x03\xe0A\x01R\bpageSize\x12\"\n" + "\n" + "page_token\x18\x02 \x01(\tB\x03\xe0A\x01R\tpageToken\x12\x1b\n" + "\x06filter\x18\x03 \x01(\tB\x03\xe0A\x01R\x06filter\x12\x1e\n" + - "\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderBy\"}\n" + + "\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderByJ\x04\b\x05\x10\x06J\x04\b\x06\x10\aR\x05spaceR\n" + + "unassigned\"}\n" + "\x17ListAttachmentsResponse\x12:\n" + "\vattachments\x18\x01 \x03(\v2\x18.memos.api.v1.AttachmentR\vattachments\x12&\n" + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"K\n" + diff --git a/proto/gen/api/v1/memo_service.pb.go b/proto/gen/api/v1/memo_service.pb.go index 19e91ab6..dac005b2 100644 --- a/proto/gen/api/v1/memo_service.pb.go +++ b/proto/gen/api/v1/memo_service.pb.go @@ -556,6 +556,7 @@ type ListMemosRequest struct { // content (string), creator (string, e.g. "users/1"), // created_ts / updated_ts (timestamp), pinned (bool), // visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE), + // space (string resource name or null when the memo has no space), // tags (list; match with `"work" in tags`, not `tag == "work"`), // has_task_list / has_link / has_code / has_incomplete_tasks (bool), // has_location (bool; true when the memo has a location attached). @@ -565,16 +566,12 @@ type ListMemosRequest struct { // Examples: // // pinned == true && visibility == "PUBLIC" + // space == "spaces/team" or space == null // tags.exists(t, t == "urgent") // content.contains("roadmap") && created_ts > now - duration("168h") Filter string `protobuf:"bytes,5,opt,name=filter,proto3" json:"filter,omitempty"` // Optional. If true, show deleted memos in the response. - ShowDeleted bool `protobuf:"varint,6,opt,name=show_deleted,json=showDeleted,proto3" json:"show_deleted,omitempty"` - // Types that are valid to be assigned to Scope: - // - // *ListMemosRequest_Space - // *ListMemosRequest_Unassigned - Scope isListMemosRequest_Scope `protobuf_oneof:"scope"` + ShowDeleted bool `protobuf:"varint,6,opt,name=show_deleted,json=showDeleted,proto3" json:"show_deleted,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -651,50 +648,6 @@ func (x *ListMemosRequest) GetShowDeleted() bool { return false } -func (x *ListMemosRequest) GetScope() isListMemosRequest_Scope { - if x != nil { - return x.Scope - } - return nil -} - -func (x *ListMemosRequest) GetSpace() string { - if x != nil { - if x, ok := x.Scope.(*ListMemosRequest_Space); ok { - return x.Space - } - } - return "" -} - -func (x *ListMemosRequest) GetUnassigned() bool { - if x != nil { - if x, ok := x.Scope.(*ListMemosRequest_Unassigned); ok { - return x.Unassigned - } - } - return false -} - -type isListMemosRequest_Scope interface { - isListMemosRequest_Scope() -} - -type ListMemosRequest_Space struct { - // Optional. Limit results to readable non-comment memos in a space of - // which the caller is an active member. - Space string `protobuf:"bytes,7,opt,name=space,proto3,oneof"` -} - -type ListMemosRequest_Unassigned struct { - // Optional. Limit results to memos with no space. Must be true when set. - Unassigned bool `protobuf:"varint,8,opt,name=unassigned,proto3,oneof"` -} - -func (*ListMemosRequest_Space) isListMemosRequest_Scope() {} - -func (*ListMemosRequest_Unassigned) isListMemosRequest_Scope() {} - type ListMemosResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The list of memos. @@ -2424,7 +2377,7 @@ const file_api_v1_memo_service_proto_rawDesc = "" + "\tlongitude\x18\x03 \x01(\x01B\x03\xe0A\x01R\tlongitude\"^\n" + "\x11CreateMemoRequest\x12+\n" + "\x04memo\x18\x01 \x01(\v2\x12.memos.api.v1.MemoB\x03\xe0A\x02R\x04memo\x12\x1c\n" + - "\amemo_id\x18\x02 \x01(\tB\x03\xe0A\x01R\x06memoId\"\xc9\x02\n" + + "\amemo_id\x18\x02 \x01(\tB\x03\xe0A\x01R\x06memoId\"\x8c\x02\n" + "\x10ListMemosRequest\x12 \n" + "\tpage_size\x18\x01 \x01(\x05B\x03\xe0A\x01R\bpageSize\x12\"\n" + "\n" + @@ -2432,13 +2385,8 @@ const file_api_v1_memo_service_proto_rawDesc = "" + "\x05state\x18\x03 \x01(\x0e2\x13.memos.api.v1.StateB\x03\xe0A\x01R\x05state\x12\x1e\n" + "\border_by\x18\x04 \x01(\tB\x03\xe0A\x01R\aorderBy\x12\x1b\n" + "\x06filter\x18\x05 \x01(\tB\x03\xe0A\x01R\x06filter\x12&\n" + - "\fshow_deleted\x18\x06 \x01(\bB\x03\xe0A\x01R\vshowDeleted\x12/\n" + - "\x05space\x18\a \x01(\tB\x17\xfaA\x14\n" + - "\x12memos.api.v1/SpaceH\x00R\x05space\x12 \n" + - "\n" + - "unassigned\x18\b \x01(\bH\x00R\n" + - "unassignedB\a\n" + - "\x05scope\"e\n" + + "\fshow_deleted\x18\x06 \x01(\bB\x03\xe0A\x01R\vshowDeletedJ\x04\b\a\x10\bJ\x04\b\b\x10\tR\x05spaceR\n" + + "unassigned\"e\n" + "\x11ListMemosResponse\x12(\n" + "\x05memos\x18\x01 \x03(\v2\x12.memos.api.v1.MemoR\x05memos\x12&\n" + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"?\n" + @@ -2739,10 +2687,6 @@ func file_api_v1_memo_service_proto_init() { file_api_v1_attachment_service_proto_init() file_api_v1_common_proto_init() file_api_v1_memo_service_proto_msgTypes[1].OneofWrappers = []any{} - file_api_v1_memo_service_proto_msgTypes[4].OneofWrappers = []any{ - (*ListMemosRequest_Space)(nil), - (*ListMemosRequest_Unassigned)(nil), - } file_api_v1_memo_service_proto_msgTypes[23].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ diff --git a/proto/gen/api/v1/user_service.pb.go b/proto/gen/api/v1/user_service.pb.go index 86e2d453..528fdbfb 100644 --- a/proto/gen/api/v1/user_service.pb.go +++ b/proto/gen/api/v1/user_service.pb.go @@ -946,7 +946,10 @@ type GetUserStatsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Required. The resource name of the user. // Format: users/{user} - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Optional. CEL expression selecting the readable non-comment memos to + // include. Supports the same fields as ListMemos, including `space`. + Filter string `protobuf:"bytes,2,opt,name=filter,proto3" json:"filter,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -988,6 +991,13 @@ func (x *GetUserStatsRequest) GetName() string { return "" } +func (x *GetUserStatsRequest) GetFilter() string { + if x != nil { + return x.Filter + } + return "" +} + type ListAllUserStatsRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Optional. The state of memos to include. Defaults to NORMAL. @@ -3438,13 +3448,16 @@ const file_api_v1_user_service_proto_rawDesc = "" + "todo_count\x18\x03 \x01(\x05R\ttodoCount\x12\x1d\n" + "\n" + "undo_count\x18\x04 \x01(\x05R\tundoCount:E\xeaAB\n" + - "\x16memos.api.v1/UserStats\x12\x12users/{user}/stats*\tuserStats2\tuserStatsJ\x04\b\x02\x10\x03R\x17memo_display_timestamps\"D\n" + + "\x16memos.api.v1/UserStats\x12\x12users/{user}/stats*\tuserStats2\tuserStatsJ\x04\b\x02\x10\x03R\x17memo_display_timestamps\"z\n" + "\x13GetUserStatsRequest\x12-\n" + "\x04name\x18\x01 \x01(\tB\x19\xe0A\x02\xfaA\x13\n" + - "\x11memos.api.v1/UserR\x04name\"f\n" + + "\x11memos.api.v1/UserR\x04name\x12\x1b\n" + + "\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filterJ\x04\b\x03\x10\x04R\x05spaceR\n" + + "unassigned\"\x85\x01\n" + "\x17ListAllUserStatsRequest\x12.\n" + "\x05state\x18\x01 \x01(\x0e2\x13.memos.api.v1.StateB\x03\xe0A\x01R\x05state\x12\x1b\n" + - "\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filter\"I\n" + + "\x06filter\x18\x02 \x01(\tB\x03\xe0A\x01R\x06filterJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\x05spaceR\n" + + "unassigned\"I\n" + "\x18ListAllUserStatsResponse\x12-\n" + "\x05stats\x18\x01 \x03(\v2\x17.memos.api.v1.UserStatsR\x05stats\"\xf1\a\n" + "\vUserSetting\x12\x17\n" + diff --git a/proto/gen/api/v1/user_service.pb.gw.go b/proto/gen/api/v1/user_service.pb.gw.go index 563584d3..cad8017c 100644 --- a/proto/gen/api/v1/user_service.pb.gw.go +++ b/proto/gen/api/v1/user_service.pb.gw.go @@ -360,6 +360,8 @@ func local_request_UserService_ListAllUserStats_0(ctx context.Context, marshaler return msg, metadata, err } +var filter_UserService_GetUserStats_0 = &utilities.DoubleArray{Encoding: map[string]int{"name": 0}, Base: []int{1, 1, 0}, Check: []int{0, 1, 2}} + func request_UserService_GetUserStats_0(ctx context.Context, marshaler runtime.Marshaler, client UserServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { var ( protoReq GetUserStatsRequest @@ -374,6 +376,12 @@ func request_UserService_GetUserStats_0(ctx context.Context, marshaler runtime.M if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UserService_GetUserStats_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } if req.Body != nil { _, _ = io.Copy(io.Discard, req.Body) } @@ -395,6 +403,12 @@ func local_request_UserService_GetUserStats_0(ctx context.Context, marshaler run if err != nil { return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "name", err) } + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_UserService_GetUserStats_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } msg, err := server.GetUserStats(ctx, &protoReq) return msg, metadata, err } diff --git a/proto/gen/openapi.yaml b/proto/gen/openapi.yaml index 5e88bd59..a3766132 100644 --- a/proto/gen/openapi.yaml +++ b/proto/gen/openapi.yaml @@ -61,7 +61,11 @@ paths: Optional. Filter to apply to the list results. Example: "mime_type==\"image/png\"" or "filename.contains(\"test\")" Supported operators: =, !=, <, <=, >, >=, : (contains), in - Supported fields: filename, mime_type, create_time, memo + Supported fields: filename, mime_type, create_time, memo_id, space. + `space` only supports a non-negated `==` comparison with a Space resource + name or null. + `space` is the linked memo's space resource name, or null when the + attachment is unlinked or its linked memo has no space. schema: type: string - name: orderBy @@ -663,6 +667,7 @@ paths: content (string), creator (string, e.g. "users/1"), created_ts / updated_ts (timestamp), pinned (bool), visibility (string: PRIVATE | PROTECTED | PUBLIC | SPACE), + space (string resource name or null when the memo has no space), tags (list; match with `"work" in tags`, not `tag == "work"`), has_task_list / has_link / has_code / has_incomplete_tasks (bool), has_location (bool; true when the memo has a location attached). @@ -670,6 +675,7 @@ paths: the create_time / update_time names used by order_by. Examples: pinned == true && visibility == "PUBLIC" + space == "spaces/team" or space == null tags.exists(t, t == "urgent") content.contains("roadmap") && created_ts > now - duration("168h") schema: @@ -679,18 +685,6 @@ paths: description: Optional. If true, show deleted memos in the response. schema: type: boolean - - name: space - in: query - description: |- - Optional. Limit results to readable non-comment memos in a space of - which the caller is an active member. - schema: - type: string - - name: unassigned - in: query - description: Optional. Limit results to memos with no space. Must be true when set. - schema: - type: boolean responses: "200": description: OK @@ -2626,6 +2620,13 @@ paths: required: true schema: type: string + - name: filter + in: query + description: |- + Optional. CEL expression selecting the readable non-comment memos to + include. Supports the same fields as ListMemos, including `space`. + schema: + type: string responses: "200": description: OK diff --git a/server/router/api/v1/attachment_service.go b/server/router/api/v1/attachment_service.go index cc3aee8f..699ea912 100644 --- a/server/router/api/v1/attachment_service.go +++ b/server/router/api/v1/attachment_service.go @@ -10,12 +10,10 @@ import ( "path/filepath" "time" - "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/emptypb" - "github.com/usememos/memos/internal/filter" v1pb "github.com/usememos/memos/proto/gen/api/v1" "github.com/usememos/memos/store" ) @@ -234,11 +232,10 @@ func (s *APIV1Service) ListAttachments(ctx context.Context, request *v1pb.ListAt Limit: &pageSize, Offset: &offset, } - // Parse filter if provided if request.Filter != "" { - if err := s.validateAttachmentFilter(ctx, request.Filter); err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + if err := s.validateAttachmentFilterForUser(ctx, request.Filter, user); err != nil { + return nil, err } findAttachment.Filters = append(findAttachment.Filters, request.Filter) } @@ -545,22 +542,6 @@ func attachmentsIncludeMemo(attachments []*store.Attachment) bool { return false } -func (s *APIV1Service) validateAttachmentFilter(ctx context.Context, filterStr string) error { - if filterStr == "" { - return errors.New("filter cannot be empty") - } - - engine, err := filter.DefaultAttachmentEngine() - if err != nil { - return err - } - - if _, err := engine.CompileToStatement(ctx, filterStr, filter.RenderOptions{Dialect: s.filterDialect()}); err != nil { - return errors.Wrap(err, "failed to compile filter") - } - return nil -} - // checkAttachmentAccess verifies the user has permission to access the attachment. // For unlinked attachments (no memo), only the creator can access. // For linked attachments, access follows the memo's visibility rules. diff --git a/server/router/api/v1/filter_access.go b/server/router/api/v1/filter_access.go new file mode 100644 index 00000000..9ebb28ce --- /dev/null +++ b/server/router/api/v1/filter_access.go @@ -0,0 +1,145 @@ +package v1 + +import ( + "context" + "slices" + + "github.com/pkg/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + filterpkg "github.com/usememos/memos/internal/filter" + "github.com/usememos/memos/store" +) + +func (s *APIV1Service) validateMemoFilterForUser(ctx context.Context, filterText string, user *store.User) error { + engine, err := filterpkg.DefaultEngine() + if err != nil { + return status.Errorf(codes.Internal, "failed to initialize filter: %v", err) + } + return s.validateFilterSpaceAccess(ctx, filterText, engine, user) +} + +func (s *APIV1Service) validateAttachmentFilterForUser(ctx context.Context, filterText string, user *store.User) error { + engine, err := filterpkg.DefaultAttachmentEngine() + if err != nil { + return status.Errorf(codes.Internal, "failed to initialize filter: %v", err) + } + return s.validateFilterSpaceAccess(ctx, filterText, engine, user) +} + +func (s *APIV1Service) validateFilterSpaceAccess(ctx context.Context, filterText string, engine *filterpkg.Engine, user *store.User) error { + program, err := engine.Compile(ctx, filterText) + if err != nil { + return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + } + if _, err := program.Render(filterpkg.RenderOptions{Dialect: s.filterDialect()}); err != nil { + return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + } + + spaceNames := map[string]struct{}{} + if err := collectSpaceFilterNames(program.ConditionTree(), false, spaceNames); err != nil { + return status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + } + if len(spaceNames) == 0 { + return nil + } + if user == nil { + return status.Error(codes.Unauthenticated, "user not authenticated") + } + + names := make([]string, 0, len(spaceNames)) + for name := range spaceNames { + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + if _, err := s.resolveWritableSpaceByName(ctx, name, user.ID); err != nil { + return err + } + } + return nil +} + +func collectSpaceFilterNames(condition filterpkg.Condition, negated bool, names map[string]struct{}) error { + switch condition := condition.(type) { + case *filterpkg.LogicalCondition: + if err := collectSpaceFilterNames(condition.Left, negated, names); err != nil { + return err + } + return collectSpaceFilterNames(condition.Right, negated, names) + case *filterpkg.NotCondition: + return collectSpaceFilterNames(condition.Expr, true, names) + case *filterpkg.ComparisonCondition: + if !valueReferencesSpace(condition.Left) && !valueReferencesSpace(condition.Right) { + return nil + } + field, ok := condition.Left.(*filterpkg.FieldRef) + if !ok || field.Name != "space" || negated || condition.Operator != filterpkg.CompareEq { + return errors.New("space only supports a non-negated equality comparison") + } + literal, ok := condition.Right.(*filterpkg.LiteralValue) + if !ok { + return errors.New("space must be compared with a resource name or null") + } + if literal.Value == nil { + return nil + } + name, ok := literal.Value.(string) + if !ok { + return errors.New("space must be compared with a resource name or null") + } + names[name] = struct{}{} + return nil + case *filterpkg.InCondition: + if valueReferencesSpace(condition.Left) { + return errors.New("space does not support the in operator") + } + for _, value := range condition.Values { + if valueReferencesSpace(value) { + return errors.New("space does not support the in operator") + } + } + case *filterpkg.ElementInCondition: + if condition.Field == "space" || valueReferencesSpace(condition.Element) { + return errors.New("space does not support the in operator") + } + case *filterpkg.FieldPredicateCondition: + if condition.Field == "space" { + return errors.New("space must be compared with a resource name or null") + } + case *filterpkg.TextMatchCondition: + if condition.Field == "space" { + return errors.New("space does not support text matching") + } + case *filterpkg.RegexCondition: + if condition.Field == "space" { + return errors.New("space does not support regular expressions") + } + case *filterpkg.ListComprehensionCondition: + if condition.Field == "space" { + return errors.New("space does not support list operations") + } + default: + // Other condition types cannot reference a space. + } + return nil +} + +func valueReferencesSpace(value filterpkg.ValueExpr) bool { + switch value := value.(type) { + case *filterpkg.FieldRef: + return value.Name == "space" + case *filterpkg.FunctionValue: + for _, argument := range value.Args { + if valueReferencesSpace(argument) { + return true + } + } + case *filterpkg.FieldAccessorValue: + return value.Field == "space" + default: + // Other value expressions cannot reference a space. + } + return false +} diff --git a/server/router/api/v1/memo_service.go b/server/router/api/v1/memo_service.go index b76a3f45..4475f213 100644 --- a/server/router/api/v1/memo_service.go +++ b/server/router/api/v1/memo_service.go @@ -89,27 +89,6 @@ func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosReq } memoFind.Access = accessScope - if request.Scope != nil { - switch scope := request.Scope.(type) { - case *v1pb.ListMemosRequest_Space: - if currentUser == nil { - return nil, status.Errorf(codes.Unauthenticated, "user not authenticated") - } - space, err := s.resolveWritableSpaceByName(ctx, scope.Space, currentUser.ID) - if err != nil { - return nil, err - } - memoFind.SpaceID = &space.ID - case *v1pb.ListMemosRequest_Unassigned: - if !scope.Unassigned { - return nil, status.Errorf(codes.InvalidArgument, "unassigned scope must be true") - } - memoFind.Unassigned = true - default: - return nil, status.Errorf(codes.InvalidArgument, "unsupported memo scope") - } - } - if request.State == v1pb.State_ARCHIVED { state := store.Archived memoFind.RowStatus = &state @@ -134,8 +113,8 @@ func (s *APIV1Service) ListMemos(ctx context.Context, request *v1pb.ListMemosReq } if request.Filter != "" { - if err := s.validateFilter(ctx, request.Filter); err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil { + return nil, err } memoFind.Filters = append(memoFind.Filters, request.Filter) } diff --git a/server/router/api/v1/test/attachment_service_test.go b/server/router/api/v1/test/attachment_service_test.go index d9ad2df4..fd5ed82b 100644 --- a/server/router/api/v1/test/attachment_service_test.go +++ b/server/router/api/v1/test/attachment_service_test.go @@ -480,6 +480,109 @@ func TestLinkedAttachmentMutationsRevalidateMemoSpaceMembership(t *testing.T) { require.NoError(t, err) } +func TestListAttachmentsSpaceFilter(t *testing.T) { + ctx := context.Background() + ts := NewTestService(t) + defer ts.Cleanup() + + owner, err := ts.CreateRegularUser(ctx, "attachment-scope-owner") + require.NoError(t, err) + member, err := ts.CreateRegularUser(ctx, "attachment-scope-member") + require.NoError(t, err) + outsider, err := ts.CreateRegularUser(ctx, "attachment-scope-outsider") + require.NoError(t, err) + spaceA, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "attachment-api-scope-a", Title: "A"}, owner.ID) + require.NoError(t, err) + _, err = ts.Store.CreateSpaceMember(ctx, &store.SpaceMember{ + SpaceID: spaceA.ID, UserID: member.ID, Role: store.SpaceMemberRoleUser, + }, owner.ID) + require.NoError(t, err) + spaceB, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "attachment-api-scope-b", Title: "B"}, owner.ID) + require.NoError(t, err) + + unassignedMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{ + UID: "attachment-api-unassigned", CreatorID: owner.ID, Content: "unassigned", Visibility: store.Private, + }) + require.NoError(t, err) + spaceAMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{ + UID: "attachment-api-space-a", CreatorID: owner.ID, Content: "a", Visibility: store.Private, SpaceID: &spaceA.ID, + }) + require.NoError(t, err) + spaceBMemo, err := ts.Store.CreateMemo(ctx, &store.Memo{ + UID: "attachment-api-space-b", CreatorID: owner.ID, Content: "b", Visibility: store.Public, SpaceID: &spaceB.ID, + }) + require.NoError(t, err) + + createAttachment := func(uid string, memoID *int32) { + t.Helper() + _, createErr := ts.Store.CreateAttachment(ctx, &store.Attachment{ + UID: uid, CreatorID: owner.ID, Filename: uid + ".txt", Type: "text/plain", MemoID: memoID, + }) + require.NoError(t, createErr) + } + createAttachment("attachment-api-unlinked", nil) + createAttachment("attachment-api-unassigned-file", &unassignedMemo.ID) + createAttachment("attachment-api-space-a-file", &spaceAMemo.ID) + createAttachment("attachment-api-space-b-file", &spaceBMemo.ID) + + attachmentFilenames := func(response *v1pb.ListAttachmentsResponse) []string { + t.Helper() + filenames := make([]string, 0, len(response.Attachments)) + for _, attachment := range response.Attachments { + filenames = append(filenames, attachment.Filename) + } + return filenames + } + ownerCtx := ts.CreateUserContext(ctx, owner.ID) + allResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{PageSize: 100}) + require.NoError(t, err) + require.Len(t, allResponse.Attachments, 4, "omitting the filter must preserve the creator's full readable library") + + spaceResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{ + PageSize: 100, + Filter: `space == "spaces/` + spaceA.UID + `"`, + }) + require.NoError(t, err) + require.Equal(t, []string{"attachment-api-space-a-file.txt"}, attachmentFilenames(spaceResponse)) + + unassignedResponse, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{ + PageSize: 100, + Filter: `space == null`, + }) + require.NoError(t, err) + require.ElementsMatch(t, []string{"attachment-api-unlinked.txt", "attachment-api-unassigned-file.txt"}, attachmentFilenames(unassignedResponse)) + + unusedInMemos, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{ + PageSize: 100, + Filter: "memo_id == null && space == null", + }) + require.NoError(t, err) + require.Equal(t, []string{"attachment-api-unlinked.txt"}, attachmentFilenames(unusedInMemos)) + unusedInSpace, err := ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{ + PageSize: 100, + Filter: `memo_id == null && space == "spaces/` + spaceA.UID + `"`, + }) + require.NoError(t, err) + require.Empty(t, unusedInSpace.Attachments) + + memberResponse, err := ts.Service.ListAttachments(ts.CreateUserContext(ctx, member.ID), &v1pb.ListAttachmentsRequest{ + PageSize: 100, + Filter: `space == "spaces/` + spaceA.UID + `"`, + }) + require.NoError(t, err) + require.Empty(t, memberResponse.Attachments, "the attachment library remains creator-owned") + + _, err = ts.Service.ListAttachments(ts.CreateUserContext(ctx, outsider.ID), &v1pb.ListAttachmentsRequest{ + Filter: `space == "spaces/` + spaceA.UID + `"`, + }) + require.Equal(t, codes.NotFound, status.Code(err)) + + _, err = ts.Service.ListAttachments(ownerCtx, &v1pb.ListAttachmentsRequest{ + Filter: `space != null`, + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) +} + func memoIDFromName(ctx context.Context, t *testing.T, ts *TestService, name string) int32 { t.Helper() memoUID, err := apiv1.ExtractMemoUIDFromName(name) diff --git a/server/router/api/v1/test/user_service_stats_test.go b/server/router/api/v1/test/user_service_stats_test.go index 20f02d1e..b8f86649 100644 --- a/server/router/api/v1/test/user_service_stats_test.go +++ b/server/router/api/v1/test/user_service_stats_test.go @@ -6,6 +6,8 @@ import ( "testing" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" v1pb "github.com/usememos/memos/proto/gen/api/v1" storepb "github.com/usememos/memos/proto/gen/store" @@ -362,3 +364,103 @@ func TestUserStatsUseMemoLocalAccess(t *testing.T) { require.Contains(t, memberStats.Stats[0].TagCount, "space") require.NotContains(t, memberStats.Stats[0].TagCount, "private") } + +func TestUserStatsSpaceFilter(t *testing.T) { + ctx := context.Background() + ts := NewTestService(t) + defer ts.Cleanup() + + owner, err := ts.CreateRegularUser(ctx, "stats-scope-owner") + require.NoError(t, err) + member, err := ts.CreateRegularUser(ctx, "stats-scope-member") + require.NoError(t, err) + outsider, err := ts.CreateRegularUser(ctx, "stats-scope-outsider") + require.NoError(t, err) + + spaceA, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "stats-scope-a", Title: "A"}, owner.ID) + require.NoError(t, err) + _, err = ts.Store.CreateSpaceMember(ctx, &store.SpaceMember{ + SpaceID: spaceA.ID, + UserID: member.ID, + Role: store.SpaceMemberRoleUser, + }, owner.ID) + require.NoError(t, err) + spaceB, err := ts.Store.CreateSpace(ctx, &store.Space{UID: "stats-scope-b", Title: "B"}, owner.ID) + require.NoError(t, err) + + spaceAName := "spaces/" + spaceA.UID + fixtures := []struct { + uid string + creatorID int32 + visibility store.Visibility + spaceID *int32 + tag string + }{ + {uid: "stats-scope-unassigned", creatorID: owner.ID, visibility: store.Public, tag: "unassigned"}, + {uid: "stats-scope-a-members", creatorID: owner.ID, visibility: store.SpaceAudience, spaceID: &spaceA.ID, tag: "a-members"}, + {uid: "stats-scope-a-private", creatorID: owner.ID, visibility: store.Private, spaceID: &spaceA.ID, tag: "a-private"}, + {uid: "stats-scope-a-member-private", creatorID: member.ID, visibility: store.Private, spaceID: &spaceA.ID, tag: "member-private"}, + {uid: "stats-scope-b-public", creatorID: owner.ID, visibility: store.Public, spaceID: &spaceB.ID, tag: "b-public"}, + } + for _, fixture := range fixtures { + _, err := ts.Store.CreateMemo(ctx, &store.Memo{ + UID: fixture.uid, + CreatorID: fixture.creatorID, + Content: fixture.tag, + Visibility: fixture.visibility, + SpaceID: fixture.spaceID, + Payload: &storepb.MemoPayload{Tags: []string{fixture.tag}}, + }) + require.NoError(t, err) + } + + ownerName := fmt.Sprintf("users/%s", owner.Username) + ownerCtx := ts.CreateUserContext(ctx, owner.ID) + ownerSpaceStats, err := ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{ + Name: ownerName, + Filter: fmt.Sprintf(`space == %q`, spaceAName), + }) + require.NoError(t, err) + require.Equal(t, int32(2), ownerSpaceStats.TotalMemoCount) + require.Contains(t, ownerSpaceStats.TagCount, "a-members") + require.Contains(t, ownerSpaceStats.TagCount, "a-private") + require.NotContains(t, ownerSpaceStats.TagCount, "unassigned") + require.NotContains(t, ownerSpaceStats.TagCount, "b-public") + + ownerUnassignedStats, err := ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{ + Name: ownerName, + Filter: `space == null`, + }) + require.NoError(t, err) + require.Equal(t, int32(1), ownerUnassignedStats.TotalMemoCount) + require.Contains(t, ownerUnassignedStats.TagCount, "unassigned") + + memberSpaceStats, err := ts.Service.ListAllUserStats(ts.CreateUserContext(ctx, member.ID), &v1pb.ListAllUserStatsRequest{ + Filter: fmt.Sprintf(`space == %q`, spaceAName), + }) + require.NoError(t, err) + require.Len(t, memberSpaceStats.Stats, 2) + visibleTags := map[string]int32{} + for _, stats := range memberSpaceStats.Stats { + for tag, count := range stats.TagCount { + visibleTags[tag] += count + } + } + require.Equal(t, map[string]int32{"a-members": 1, "member-private": 1}, visibleTags) + + _, err = ts.Service.ListAllUserStats(ts.CreateUserContext(ctx, outsider.ID), &v1pb.ListAllUserStatsRequest{ + Filter: fmt.Sprintf(`space == %q`, spaceAName), + }) + require.Equal(t, codes.NotFound, status.Code(err)) + + _, err = ts.Service.ListAllUserStats(ctx, &v1pb.ListAllUserStatsRequest{ + Filter: fmt.Sprintf(`space == %q`, spaceAName), + }) + require.Equal(t, codes.Unauthenticated, status.Code(err)) + + _, err = ts.Service.GetUserStats(ownerCtx, &v1pb.GetUserStatsRequest{ + Name: ownerName, + Filter: `space != null`, + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) +} diff --git a/server/router/api/v1/user_service_stats.go b/server/router/api/v1/user_service_stats.go index 511a3757..45f11a58 100644 --- a/server/router/api/v1/user_service_stats.go +++ b/server/router/api/v1/user_service_stats.go @@ -68,8 +68,8 @@ func (s *APIV1Service) ListAllUserStats(ctx context.Context, request *v1pb.ListA } if request.Filter != "" { - if err := s.validateFilter(ctx, request.Filter); err != nil { - return nil, status.Errorf(codes.InvalidArgument, "invalid filter: %v", err) + if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil { + return nil, err } memoFind.Filters = append(memoFind.Filters, request.Filter) } @@ -190,7 +190,7 @@ func (s *APIV1Service) GetUserStats(ctx context.Context, request *v1pb.GetUserSt } userID := user.ID - accessScope, _, err := s.resolveMemoAccessScope(ctx) + accessScope, currentUser, err := s.resolveMemoAccessScope(ctx) if err != nil { return nil, status.Errorf(codes.Internal, "%v", err) } @@ -204,6 +204,13 @@ func (s *APIV1Service) GetUserStats(ctx context.Context, request *v1pb.GetUserSt RowStatus: &normalStatus, } + if request.Filter != "" { + if err := s.validateMemoFilterForUser(ctx, request.Filter, currentUser); err != nil { + return nil, err + } + memoFind.Filters = append(memoFind.Filters, request.Filter) + } + memoFind.Access = accessScope createdTimestamps := []*timestamppb.Timestamp{} diff --git a/store/db/mysql/attachment.go b/store/db/mysql/attachment.go index f065eba0..269f5b07 100644 --- a/store/db/mysql/attachment.go +++ b/store/db/mysql/attachment.go @@ -151,6 +151,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([ query := "SELECT " + strings.Join(fields, ", ") + " FROM `attachment`" + " " + "LEFT JOIN `memo` ON `attachment`.`memo_id` = `memo`.`id`" + " " + + "LEFT JOIN `space` AS `attachment_space` ON `memo`.`space_id` = `attachment_space`.`id`" + " " + "WHERE " + strings.Join(where, " AND ") + " " + "ORDER BY `updated_ts` DESC" if find.Limit != nil { diff --git a/store/db/mysql/memo.go b/store/db/mysql/memo.go index 520d361a..f580f27a 100644 --- a/store/db/mysql/memo.go +++ b/store/db/mysql/memo.go @@ -169,9 +169,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo } where = append(where, fmt.Sprintf("`memo`.`visibility` in (%s)", strings.Join(placeholder, ","))) } - if v := find.SpaceID; v != nil { - where, args = append(where, "`memo`.`space_id` = ?"), append(args, *v) - } if v := find.CommentContextMemoID; v != nil { where, args = append(where, `EXISTS ( SELECT 1 FROM memo_relation AS comment_context @@ -180,9 +177,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo AND comment_context.type = 'COMMENT' )`), append(args, *v) } - if find.Unassigned { - where = append(where, "`memo`.`space_id` IS NULL") - } if access := find.Access; access != nil { where = append(where, mysqlMemoAccessPredicate(access, "`memo`", "`access_member`", &args)) } @@ -231,6 +225,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo`" + " " + "LEFT JOIN `user` AS `memo_creator` ON `memo`.`creator_id` = `memo_creator`.`id`" + " " + + "LEFT JOIN `space` AS `memo_space` ON `memo`.`space_id` = `memo_space`.`id`" + " " + "WHERE " + strings.Join(where, " AND ") + " " + "HAVING " + strings.Join(having, " AND ") + " " + "ORDER BY " + strings.Join(orderBy, ", ") diff --git a/store/db/postgres/attachment.go b/store/db/postgres/attachment.go index 10507470..9c549fe9 100644 --- a/store/db/postgres/attachment.go +++ b/store/db/postgres/attachment.go @@ -148,6 +148,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([ %s FROM attachment LEFT JOIN memo ON attachment.memo_id = memo.id + LEFT JOIN space AS attachment_space ON memo.space_id = attachment_space.id WHERE %s ORDER BY attachment.updated_ts DESC `, strings.Join(fields, ", "), strings.Join(where, " AND ")) diff --git a/store/db/postgres/memo.go b/store/db/postgres/memo.go index dfcadb3b..070cc342 100644 --- a/store/db/postgres/memo.go +++ b/store/db/postgres/memo.go @@ -146,9 +146,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo } where = append(where, fmt.Sprintf("memo.visibility in (%s)", strings.Join(holders, ", "))) } - if v := find.SpaceID; v != nil { - where, args = append(where, "memo.space_id = "+placeholder(len(args)+1)), append(args, *v) - } if v := find.CommentContextMemoID; v != nil { contextHolder := placeholder(len(args) + 1) args = append(args, *v) @@ -159,9 +156,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo AND comment_context.type = 'COMMENT' )`) } - if find.Unassigned { - where = append(where, "memo.space_id IS NULL") - } if access := find.Access; access != nil { where = append(where, postgresMemoAccessPredicate(access, "memo", "access_member", &args)) } @@ -211,6 +205,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo query := `SELECT ` + strings.Join(fields, ", ") + ` FROM memo LEFT JOIN "user" AS memo_creator ON memo.creator_id = memo_creator.id + LEFT JOIN space AS memo_space ON memo.space_id = memo_space.id WHERE ` + strings.Join(where, " AND ") + ` ORDER BY ` + strings.Join(orderBy, ", ") if find.Limit != nil { diff --git a/store/db/sqlite/attachment.go b/store/db/sqlite/attachment.go index 1328305d..9c92cb5c 100644 --- a/store/db/sqlite/attachment.go +++ b/store/db/sqlite/attachment.go @@ -142,6 +142,7 @@ func (d *DB) ListAttachments(ctx context.Context, find *store.FindAttachment) ([ query := "SELECT " + strings.Join(fields, ", ") + " FROM `attachment`" + " " + "LEFT JOIN `memo` ON `attachment`.`memo_id` = `memo`.`id`" + " " + + "LEFT JOIN `space` AS `attachment_space` ON `memo`.`space_id` = `attachment_space`.`id`" + " " + "WHERE " + strings.Join(where, " AND ") + " " + "ORDER BY `attachment`.`updated_ts` DESC" if find.Limit != nil { diff --git a/store/db/sqlite/memo.go b/store/db/sqlite/memo.go index 3780b44c..e15f52d6 100644 --- a/store/db/sqlite/memo.go +++ b/store/db/sqlite/memo.go @@ -154,9 +154,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo } where = append(where, fmt.Sprintf("`memo`.`visibility` IN (%s)", strings.Join(placeholder, ","))) } - if v := find.SpaceID; v != nil { - where, args = append(where, "`memo`.`space_id` = ?"), append(args, *v) - } if v := find.CommentContextMemoID; v != nil { where, args = append(where, `EXISTS ( SELECT 1 FROM memo_relation AS comment_context @@ -165,9 +162,6 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo AND comment_context.type = 'COMMENT' )`), append(args, *v) } - if find.Unassigned { - where = append(where, "`memo`.`space_id` IS NULL") - } if access := find.Access; access != nil { where = append(where, sqliteMemoAccessPredicate(access, "`memo`", "`access_member`", &args)) } @@ -216,6 +210,7 @@ func (d *DB) ListMemos(ctx context.Context, find *store.FindMemo) ([]*store.Memo query := "SELECT " + strings.Join(fields, ", ") + " FROM `memo` " + "LEFT JOIN `user` AS `memo_creator` ON `memo`.`creator_id` = `memo_creator`.`id` " + + "LEFT JOIN `space` AS `memo_space` ON `memo`.`space_id` = `memo_space`.`id` " + "WHERE " + strings.Join(where, " AND ") + " " + "ORDER BY " + strings.Join(orderBy, ", ") if find.Limit != nil { diff --git a/store/memo.go b/store/memo.go index 266c368b..052b8378 100644 --- a/store/memo.go +++ b/store/memo.go @@ -80,9 +80,7 @@ type FindMemo struct { // Domain specific fields VisibilityList []Visibility - SpaceID *int32 CommentContextMemoID *int32 - Unassigned bool Access *MemoAccessScope ExcludeContent bool ExcludeComments bool diff --git a/store/test/attachment_access_test.go b/store/test/attachment_access_test.go index bae6685f..a2ffaa8d 100644 --- a/store/test/attachment_access_test.go +++ b/store/test/attachment_access_test.go @@ -56,6 +56,77 @@ func TestAttachmentAccessScopeFiltersBeforePagination(t *testing.T) { require.Equal(t, unlinked.ID, attachments[0].ID, "the inaccessible newer row must be removed before LIMIT is applied") } +func TestAttachmentSpaceFilterFiltersByMemoPlacement(t *testing.T) { + ctx := context.Background() + ts := NewTestingStore(ctx, t) + defer ts.Close() + + owner, err := ts.CreateUser(ctx, &store.User{Username: "attachment-scope-owner", Role: store.RoleUser, PasswordHash: "hash"}) + require.NoError(t, err) + spaceA, err := ts.CreateSpace(ctx, &store.Space{UID: "attachment-scope-a", Title: "A"}, owner.ID) + require.NoError(t, err) + spaceB, err := ts.CreateSpace(ctx, &store.Space{UID: "attachment-scope-b", Title: "B"}, owner.ID) + require.NoError(t, err) + + unassignedMemo, err := ts.CreateMemo(ctx, &store.Memo{ + UID: "attachment-scope-unassigned", CreatorID: owner.ID, Content: "unassigned", Visibility: store.Private, + }) + require.NoError(t, err) + spaceAMemo, err := ts.CreateMemo(ctx, &store.Memo{ + UID: "attachment-scope-a-memo", CreatorID: owner.ID, Content: "a", Visibility: store.Private, SpaceID: &spaceA.ID, + }) + require.NoError(t, err) + spaceBMemo, err := ts.CreateMemo(ctx, &store.Memo{ + UID: "attachment-scope-b-memo", CreatorID: owner.ID, Content: "b", Visibility: store.Public, SpaceID: &spaceB.ID, + }) + require.NoError(t, err) + + createAttachment := func(uid string, memoID *int32) *store.Attachment { + t.Helper() + attachment, createErr := ts.CreateAttachment(ctx, &store.Attachment{ + UID: uid, CreatorID: owner.ID, Filename: uid + ".txt", Type: "text/plain", MemoID: memoID, + }) + require.NoError(t, createErr) + return attachment + } + unlinked := createAttachment("attachment-scope-unlinked", nil) + unassigned := createAttachment("attachment-scope-unassigned-file", &unassignedMemo.ID) + inSpaceANewer := createAttachment("attachment-scope-a-newer", &spaceAMemo.ID) + inSpaceAOlder := createAttachment("attachment-scope-a-older", &spaceAMemo.ID) + inSpaceB := createAttachment("attachment-scope-b-file", &spaceBMemo.ID) + + baseTime := time.Now().Unix() - 100 + for attachment, updatedTs := range map[*store.Attachment]int64{ + inSpaceB: baseTime + 50, + inSpaceANewer: baseTime + 40, + unlinked: baseTime + 30, + inSpaceAOlder: baseTime + 20, + unassigned: baseTime + 10, + } { + require.NoError(t, ts.UpdateAttachment(ctx, &store.UpdateAttachment{ID: attachment.ID, UpdatedTs: &updatedTs})) + } + + access := &store.MemoAccessScope{UserID: &owner.ID, AllowPublic: true, AllowProtected: true} + limit, firstOffset := 1, 0 + spaceAttachments, err := ts.ListAttachments(ctx, &store.FindAttachment{ + CreatorID: &owner.ID, Access: access, Filters: []string{`space == "spaces/attachment-scope-a"`}, Limit: &limit, Offset: &firstOffset, + }) + require.NoError(t, err) + require.Equal(t, []int32{inSpaceANewer.ID}, attachmentIDs(spaceAttachments), "filter must be applied before the first page") + secondOffset := 1 + spaceAttachments, err = ts.ListAttachments(ctx, &store.FindAttachment{ + CreatorID: &owner.ID, Access: access, Filters: []string{`space == "spaces/attachment-scope-a"`}, Limit: &limit, Offset: &secondOffset, + }) + require.NoError(t, err) + require.Equal(t, []int32{inSpaceAOlder.ID}, attachmentIDs(spaceAttachments), "filter must be applied before the second page") + + unassignedAttachments, err := ts.ListAttachments(ctx, &store.FindAttachment{ + CreatorID: &owner.ID, Access: access, Filters: []string{`space == null`}, SkipDefaultLimit: true, + }) + require.NoError(t, err) + require.ElementsMatch(t, []int32{unlinked.ID, unassigned.ID}, attachmentIDs(unassignedAttachments)) +} + func TestAttachmentAccessScopeUsesDirectMemoAudience(t *testing.T) { ctx := context.Background() ts := NewTestingStore(ctx, t) diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsx index 57069f16..c91e8a45 100644 --- a/web/src/components/AppSidebar/AppSidebar.tsx +++ b/web/src/components/AppSidebar/AppSidebar.tsx @@ -43,6 +43,7 @@ import { useAuth } from "@/contexts/AuthContext"; import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext"; import { useInstance } from "@/contexts/InstanceContext"; import { stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext"; +import { useSpaceContext } from "@/contexts/SpaceContext"; import { useAttachmentLibraryStats } from "@/hooks/useAttachmentLibrary"; import useCurrentUser from "@/hooks/useCurrentUser"; import { type MemoStatsContext, useFilteredMemoStats } from "@/hooks/useFilteredMemoStats"; @@ -71,6 +72,7 @@ import SidebarSection, { SIDEBAR_SECTION_ACTION_ICON_CLASSES, SIDEBAR_SECTION_STACK_CLASSES, } from "./SidebarSection"; +import SpaceSwitcher from "./SpaceSwitcher"; import TagsSection from "./TagsSection"; const SIDEBAR_HORIZONTAL_PADDING = "px-3"; @@ -245,6 +247,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => const t = useTranslate(); const location = useLocation(); const currentUser = useCurrentUser(); + const { memoFilter, selectedSpaceName } = useSpaceContext(); const md = useMediaQuery("md"); const { mobileOpen, setMobileOpen } = useAppSidebar(); const { isInitialized: authInitialized } = useAuth(); @@ -254,9 +257,13 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => enabled: context === "profile" && !!profileMatch?.params.username, }); const statsUserName = context === "home" ? currentUser?.name : context === "profile" ? profileUser?.name : undefined; + // Profile remains instance-level, so its calendar must stay aligned with the unscoped profile feed. + const statsFilter = context === "profile" ? undefined : memoFilter; const { statistics, tags } = useFilteredMemoStats({ context, userName: statsUserName, + filter: statsFilter, + includeSpaceVisibility: !!selectedSpaceName, enabled: authInitialized && instanceInitialized && (md || mobileOpen), }); @@ -266,6 +273,7 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => // clicks must land somewhere that renders the filtered feed. const onCollectionRoute = isMemoScopeRoute(location.pathname) || !!profileMatch; const filterTarget = onCollectionRoute ? undefined : context === "explore" ? ROUTES.EXPLORE : ROUTES.HOME; + const tagStateScope = `${statsUserName ?? context}${selectedSpaceName ? `:${selectedSpaceName}` : ""}`; return (
@@ -274,15 +282,16 @@ const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => setMobileOpen(false)} /> {showViews && } - setMobileOpen(false)} /> + setMobileOpen(false)} />
); }; const AttachmentsSidebarContent = () => { const t = useTranslate(); + const { memoFilter, selectedSpaceName } = useSpaceContext(); const { attachmentSection, setAttachmentSection, setMobileOpen } = useAppSidebar(); - const { isComplete, stats } = useAttachmentLibraryStats(); + const { isComplete, stats } = useAttachmentLibraryStats(memoFilter); const total = stats.media + stats.documents + stats.audio; const rows: Array<{ value: AttachmentSection; icon: LucideIcon; label: string; count?: number }> = [ { value: "all", icon: ListIcon, label: t("common.all"), count: isComplete ? total : undefined }, @@ -294,8 +303,16 @@ const AttachmentsSidebarContent = () => { label: t("attachment-library.tabs.documents"), count: isComplete ? stats.documents : undefined, }, - { value: "unused", icon: Trash2Icon, label: t("attachment-library.labels.unused"), count: isComplete ? stats.unused : undefined }, ]; + // Unlinked uploads do not belong to any Space, so "Unused" is only a Memos-level collection. + if (!selectedSpaceName) { + rows.push({ + value: "unused", + icon: Trash2Icon, + label: t("attachment-library.labels.unused"), + count: isComplete ? stats.unused : undefined, + }); + } return ( {rows.map((row) => ( @@ -628,6 +645,21 @@ const GlobalNavigation = () => { ); }; +/** The sidebar/header brand slot: the Space switcher when signed in, the plain logo otherwise. */ +const SidebarBrand = ({ className }: { className?: string }) => { + const currentUser = useCurrentUser(); + + if (currentUser) { + return ; + } + + return ( + + + + ); +}; + const AppSidebar = ({ className }: { className?: string }) => { const t = useTranslate(); const currentUser = useCurrentUser(); @@ -636,12 +668,7 @@ const AppSidebar = ({ className }: { className?: string }) => { return (