From 78730de2d51d2533f15e00e4493f2b107002eb5d Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Sun, 30 Aug 2026 17:56:45 -0400 Subject: [PATCH 1/4] fix(android): target API 36 (#182) --- app.config.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app.config.js b/app.config.js index fd86d4e7f..3e74d67dc 100644 --- a/app.config.js +++ b/app.config.js @@ -299,8 +299,8 @@ module.exports = function (_config) { }, android: { compileSdkVersion: 36, - targetSdkVersion: 35, - buildToolsVersion: '35.0.0', + targetSdkVersion: 36, + buildToolsVersion: '36.0.0', buildReactNativeFromSource: IS_PRODUCTION, }, }, -- knotmirror 0.0.1 From 39c8763d5fdc2d9fbb9ee10185bd16dfc35fabb2 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Sun, 30 Aug 2026 18:11:46 -0400 Subject: [PATCH 2/4] Support permissioned feeds (#178) --- __e2e__/flows/group-invite/accept-outage.yml | 28 + .../group-invite/authentication-required.yml | 28 + .../flows/group-invite/capability-outage.yml | 33 ++ .../flows/group-invite/cold-auth-resume.yml | 24 + .../flows/group-invite/existing-unpinned.yml | 35 ++ .../flows/group-invite/group-at-capacity.yml | 28 + .../group-invite/https-universal-link.yml | 19 + .../invite-unavailable-consumed.yml | 20 + .../invite-unavailable-expired.yml | 14 + .../invite-unavailable-missing.yml | 20 + __e2e__/flows/group-invite/malformed-link.yml | 19 + .../flows/group-invite/malformed-success.yml | 33 ++ __e2e__/flows/group-invite/misconfigured.yml | 14 + .../flows/group-invite/navigation-failure.yml | 45 ++ __e2e__/flows/group-invite/no-post.yml | 24 + .../flows/group-invite/pin-add-failure.yml | 43 ++ .../flows/group-invite/pin-update-failure.yml | 43 ++ .../flows/group-invite/preview-identity.yml | 21 + __e2e__/flows/group-invite/preview-outage.yml | 14 + __e2e__/flows/group-invite/rapid-taps.yml | 35 ++ __e2e__/flows/group-invite/rate-limit.yml | 28 + __e2e__/flows/group-invite/read-only.yml | 36 ++ .../flows/group-invite/same-did-other-did.yml | 65 +++ .../selection-readable-fallback.yml | 37 ++ __e2e__/flows/group-invite/success-mixed.yml | 47 ++ .../flows/group-invite/warm-custom-scheme.yml | 23 + __e2e__/flows/group-invite/zero-readable.yml | 30 ++ __e2e__/helpers/assert-group-invite-state.js | 80 +++ __e2e__/helpers/group-invite-setup.yml | 8 + .../helpers/group-invite-sign-in-alice.yml | 12 + __e2e__/helpers/group-invite-sign-in.yml | 24 + __e2e__/setupApp.yml | 12 +- __e2e__/setupServer.js | 26 +- __tests__/lib/feed-manip-community.test.ts | 35 +- __tests__/lib/space-feed-routing.test.ts | 155 ++++++ dev-env/group-invite-fixture.ts | 314 +++++++++++ dev-env/mock-server.ts | 241 ++++++++- dev-env/test-pds.ts | 128 ++++- docs/testing.md | 22 + eslint-suppressions.json | 2 +- jest/jestSetup.js | 5 + package.json | 6 +- src/Navigation.tsx | 14 +- src/analytics/metrics/types.ts | 14 + src/components/CommunityOnlyBadge.tsx | 52 +- src/components/Dialog/index.tsx | 3 + src/components/Dialog/index.web.tsx | 2 +- src/components/Post/Embed/index.tsx | 10 +- .../PostControls/PostMenu/PostMenuItems.tsx | 18 +- .../PostControls/ShareMenu/ShareMenuItems.tsx | 8 +- .../ShareMenu/ShareMenuItems.web.tsx | 8 +- .../PostControls/ShareMenu/index.tsx | 8 +- src/components/PostControls/index.tsx | 15 +- src/components/__tests__/Typography.test.tsx | 70 --- src/components/forms/Toggle/index.tsx | 1 + .../hooks/useLandingEntry.native.ts | 17 +- src/components/intents/GroupInviteDialog.tsx | 502 ++++++++++++++++++ src/components/intents/IntentDialogs.tsx | 44 ++ src/env/common.ts | 16 + src/lib/api/__tests__/community-feed.test.ts | 175 ++++++ .../api/__tests__/community-post-uri.test.ts | 20 + src/lib/api/__tests__/community-post.test.ts | 29 + src/lib/api/__tests__/community.test.ts | 99 +++- .../__tests__/group-invite-fixture.test.ts | 132 +++++ src/lib/api/__tests__/group-invite-ui.test.ts | 200 +++++++ src/lib/api/__tests__/group-invites.test.ts | 183 +++++++ src/lib/api/__tests__/post-routing.test.ts | 258 +++++++++ src/lib/api/__tests__/space-permalink.test.ts | 138 +++++ src/lib/api/__tests__/space-post.test.ts | 124 +++++ src/lib/api/__tests__/space-write.test.ts | 274 ++++++++++ src/lib/api/community-feed.ts | 264 +++++++++ src/lib/api/community-post.ts | 92 ++++ src/lib/api/community-thread.ts | 81 +++ src/lib/api/community.ts | 77 ++- src/lib/api/feed-manip.ts | 16 +- src/lib/api/feed/custom.ts | 69 +++ src/lib/api/group-invite-e2e.e2e.ts | 33 ++ src/lib/api/group-invite-e2e.ts | 20 + src/lib/api/group-invite-ui.ts | 124 +++++ src/lib/api/group-invites.ts | 280 ++++++++++ src/lib/api/index.ts | 183 ++++++- src/lib/api/resolve.ts | 25 +- src/lib/api/service-auth.ts | 26 + src/lib/api/space-feed.ts | 45 ++ src/lib/api/space-permalink.ts | 61 +++ src/lib/api/space-post.ts | 130 +++++ src/lib/api/space-uri.ts | 117 ++++ src/lib/api/space-views.ts | 93 ++++ src/lib/api/space-write.ts | 233 ++++++++ src/lib/constants.ts | 5 +- .../useOpenComposer-context.test.tsx | 144 +++++ src/lib/hooks/useIntentHandler.ts | 86 ++- src/lib/hooks/useOpenComposer.tsx | 50 +- src/lib/media/video/upload.shared.ts | 25 +- src/lib/media/video/upload.ts | 3 +- src/lib/media/video/upload.web.ts | 3 +- src/lib/routes/links.ts | 28 + src/lib/routes/types.ts | 14 +- .../__tests__/group-invite-url.test.ts | 29 + src/lib/strings/__tests__/url-helpers.test.ts | 27 + src/lib/strings/url-helpers.ts | 55 ++ src/screens/GroupInviteLanding.tsx | 108 ++++ src/screens/Login/LoginForm.tsx | 50 ++ src/screens/Login/index.tsx | 1 + .../Messages/components/MessageInputEmbed.tsx | 6 +- src/screens/Post/PostLikedBy.tsx | 29 +- src/screens/Post/PostQuotes.tsx | 29 +- src/screens/Post/PostRepostedBy.tsx | 29 +- .../components/ThreadItemAnchor.tsx | 65 ++- .../PostThread/components/ThreadItemPost.tsx | 9 +- .../components/ThreadItemTreePost.tsx | 9 +- src/screens/PostThread/index.tsx | 2 + .../__tests__/ProfileFeed-composer.test.tsx | 149 ++++++ src/screens/Profile/ProfileFeed/index.tsx | 9 +- src/screens/VideoFeed/index.tsx | 2 + .../cache/__tests__/post-shadow-space.test.ts | 75 +++ .../__tests__/community-post-targets.test.tsx | 92 ++++ .../space-engagement-routing.test.ts | 106 ++++ .../queries/bookmarks/useBookmarksQuery.ts | 9 +- .../queries/community-feed-permissions.ts | 23 + src/state/queries/community-feed.ts | 36 +- src/state/queries/community-post-targets.ts | 48 ++ src/state/queries/explore-feed-previews.tsx | 20 +- src/state/queries/feed.ts | 18 + src/state/queries/group-invites.ts | 42 ++ .../__tests__/space-subjects.test.ts | 70 +++ src/state/queries/notifications/feed.ts | 15 +- src/state/queries/notifications/util.ts | 19 +- src/state/queries/pinned-post.ts | 7 + src/state/queries/post-feed.ts | 20 +- src/state/queries/post-liked-by.ts | 35 +- src/state/queries/post-quotes.ts | 39 +- src/state/queries/post-reposted-by.ts | 27 +- src/state/queries/post.ts | 40 +- src/state/queries/resolve-uri.ts | 15 +- src/state/queries/search-posts.ts | 9 +- src/state/queries/usePostThread/index.ts | 32 +- src/state/queries/usePostThread/queryCache.ts | 9 +- src/state/queries/util.ts | 24 +- .../__tests__/strip-appview-proxy-test.ts | 25 + src/state/session/agent.ts | 3 + src/state/session/oauth-client.ts | 18 +- src/state/session/oauth-client.web.ts | 20 +- src/state/shell/composer/index.tsx | 3 + src/state/shell/landing.tsx | 64 ++- src/state/shell/logged-out.tsx | 3 + src/view/com/auth/LoggedOut.tsx | 6 + src/view/com/composer/Composer.tsx | 222 ++++++-- src/view/com/composer/PostTargetControls.tsx | 91 ++++ .../__tests__/PostTargetControls.test.tsx | 196 +++++++ src/view/com/composer/state/composer.ts | 33 ++ src/view/com/feeds/FeedPage.tsx | 2 +- src/view/com/post-thread/PostLikedBy.tsx | 11 +- src/view/com/post-thread/PostQuotes.tsx | 11 +- src/view/com/post-thread/PostRepostedBy.tsx | 11 +- .../__tests__/space-engagement.test.tsx | 95 ++++ src/view/com/post/Post.tsx | 19 +- src/view/com/posts/PostFeedItem.tsx | 20 +- src/view/com/testing/TestCtrls.e2e.tsx | 19 + src/view/screens/PostThread.tsx | 43 +- src/view/shell/Composer.ios.tsx | 1 + src/view/shell/Composer.tsx | 1 + src/view/shell/Composer.web.tsx | 1 + .../shell/__tests__/Composer-context.test.tsx | 57 ++ src/view/shell/desktop/LeftNav.tsx | 20 +- 165 files changed, 8570 insertions(+), 500 deletions(-) create mode 100644 __e2e__/flows/group-invite/accept-outage.yml create mode 100644 __e2e__/flows/group-invite/authentication-required.yml create mode 100644 __e2e__/flows/group-invite/capability-outage.yml create mode 100644 __e2e__/flows/group-invite/cold-auth-resume.yml create mode 100644 __e2e__/flows/group-invite/existing-unpinned.yml create mode 100644 __e2e__/flows/group-invite/group-at-capacity.yml create mode 100644 __e2e__/flows/group-invite/https-universal-link.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-consumed.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-expired.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-missing.yml create mode 100644 __e2e__/flows/group-invite/malformed-link.yml create mode 100644 __e2e__/flows/group-invite/malformed-success.yml create mode 100644 __e2e__/flows/group-invite/misconfigured.yml create mode 100644 __e2e__/flows/group-invite/navigation-failure.yml create mode 100644 __e2e__/flows/group-invite/no-post.yml create mode 100644 __e2e__/flows/group-invite/pin-add-failure.yml create mode 100644 __e2e__/flows/group-invite/pin-update-failure.yml create mode 100644 __e2e__/flows/group-invite/preview-identity.yml create mode 100644 __e2e__/flows/group-invite/preview-outage.yml create mode 100644 __e2e__/flows/group-invite/rapid-taps.yml create mode 100644 __e2e__/flows/group-invite/rate-limit.yml create mode 100644 __e2e__/flows/group-invite/read-only.yml create mode 100644 __e2e__/flows/group-invite/same-did-other-did.yml create mode 100644 __e2e__/flows/group-invite/selection-readable-fallback.yml create mode 100644 __e2e__/flows/group-invite/success-mixed.yml create mode 100644 __e2e__/flows/group-invite/warm-custom-scheme.yml create mode 100644 __e2e__/flows/group-invite/zero-readable.yml create mode 100644 __e2e__/helpers/assert-group-invite-state.js create mode 100644 __e2e__/helpers/group-invite-setup.yml create mode 100644 __e2e__/helpers/group-invite-sign-in-alice.yml create mode 100644 __e2e__/helpers/group-invite-sign-in.yml create mode 100644 __tests__/lib/space-feed-routing.test.ts create mode 100644 dev-env/group-invite-fixture.ts delete mode 100644 src/components/__tests__/Typography.test.tsx create mode 100644 src/components/intents/GroupInviteDialog.tsx create mode 100644 src/lib/api/__tests__/community-feed.test.ts create mode 100644 src/lib/api/__tests__/community-post-uri.test.ts create mode 100644 src/lib/api/__tests__/community-post.test.ts create mode 100644 src/lib/api/__tests__/group-invite-fixture.test.ts create mode 100644 src/lib/api/__tests__/group-invite-ui.test.ts create mode 100644 src/lib/api/__tests__/group-invites.test.ts create mode 100644 src/lib/api/__tests__/post-routing.test.ts create mode 100644 src/lib/api/__tests__/space-permalink.test.ts create mode 100644 src/lib/api/__tests__/space-post.test.ts create mode 100644 src/lib/api/__tests__/space-write.test.ts create mode 100644 src/lib/api/community-feed.ts create mode 100644 src/lib/api/community-post.ts create mode 100644 src/lib/api/community-thread.ts create mode 100644 src/lib/api/group-invite-e2e.e2e.ts create mode 100644 src/lib/api/group-invite-e2e.ts create mode 100644 src/lib/api/group-invite-ui.ts create mode 100644 src/lib/api/group-invites.ts create mode 100644 src/lib/api/service-auth.ts create mode 100644 src/lib/api/space-feed.ts create mode 100644 src/lib/api/space-permalink.ts create mode 100644 src/lib/api/space-post.ts create mode 100644 src/lib/api/space-uri.ts create mode 100644 src/lib/api/space-views.ts create mode 100644 src/lib/api/space-write.ts create mode 100644 src/lib/hooks/__tests__/useOpenComposer-context.test.tsx create mode 100644 src/lib/strings/__tests__/group-invite-url.test.ts create mode 100644 src/lib/strings/__tests__/url-helpers.test.ts create mode 100644 src/screens/GroupInviteLanding.tsx create mode 100644 src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx create mode 100644 src/state/cache/__tests__/post-shadow-space.test.ts create mode 100644 src/state/queries/__tests__/community-post-targets.test.tsx create mode 100644 src/state/queries/__tests__/space-engagement-routing.test.ts create mode 100644 src/state/queries/community-feed-permissions.ts create mode 100644 src/state/queries/community-post-targets.ts create mode 100644 src/state/queries/group-invites.ts create mode 100644 src/state/queries/notifications/__tests__/space-subjects.test.ts create mode 100644 src/view/com/composer/PostTargetControls.tsx create mode 100644 src/view/com/composer/__tests__/PostTargetControls.test.tsx create mode 100644 src/view/com/post-thread/__tests__/space-engagement.test.tsx create mode 100644 src/view/shell/__tests__/Composer-context.test.tsx diff --git a/__e2e__/flows/group-invite/accept-outage.yml b/__e2e__/flows/group-invite/accept-outage.yml new file mode 100644 index 000000000..c936695a5 --- /dev/null +++ b/__e2e__/flows/group-invite/accept-outage.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: accept-outage +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/authentication-required.yml b/__e2e__/flows/group-invite/authentication-required.yml new file mode 100644 index 000000000..d0f2b13fb --- /dev/null +++ b/__e2e__/flows/group-invite/authentication-required.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: auth-required +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'Please sign in again to accept this invite.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/capability-outage.yml b/__e2e__/flows/group-invite/capability-outage.yml new file mode 100644 index 000000000..abd8d0e6e --- /dev/null +++ b/__e2e__/flows/group-invite/capability-outage.yml @@ -0,0 +1,33 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: capability-outage +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/cold-auth-resume.yml b/__e2e__/flows/group-invite/cold-auth-resume.yml new file mode 100644 index 000000000..2b81b5f3a --- /dev/null +++ b/__e2e__/flows/group-invite/cold-auth-resume.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: resumable +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLanding + timeout: 30000 +- assertVisible: 'Members' +- assertVisible: 'Test Community' +- runFlow: + file: ../../helpers/group-invite-sign-in.yml +- assertVisible: + id: groupInviteAcceptedMembership +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/existing-unpinned.yml b/__e2e__/flows/group-invite/existing-unpinned.yml new file mode 100644 index 000000000..93a740e3c --- /dev/null +++ b/__e2e__/flows/group-invite/existing-unpinned.yml @@ -0,0 +1,35 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: existing-unpinned +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' + EXPECT_INACCESSIBLE_SAVED: '0' diff --git a/__e2e__/flows/group-invite/group-at-capacity.yml b/__e2e__/flows/group-invite/group-at-capacity.yml new file mode 100644 index 000000000..d7e8ab80a --- /dev/null +++ b/__e2e__/flows/group-invite/group-at-capacity.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: capacity +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This group is currently at capacity.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/https-universal-link.yml b/__e2e__/flows/group-invite/https-universal-link.yml new file mode 100644 index 000000000..ab4541c2a --- /dev/null +++ b/__e2e__/flows/group-invite/https-universal-link.yml @@ -0,0 +1,19 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'https://blacksky.community/join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: + id: groupInviteAcceptButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/invite-unavailable-consumed.yml b/__e2e__/flows/group-invite/invite-unavailable-consumed.yml new file mode 100644 index 000000000..a70f5afb8 --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-consumed.yml @@ -0,0 +1,20 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: consumed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/invite-unavailable-expired.yml b/__e2e__/flows/group-invite/invite-unavailable-expired.yml new file mode 100644 index 000000000..5ea0c7fb7 --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-expired.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: expired +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/invite-unavailable-missing.yml b/__e2e__/flows/group-invite/invite-unavailable-missing.yml new file mode 100644 index 000000000..912e7afcd --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-missing.yml @@ -0,0 +1,20 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: missing +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- assertNotVisible: + id: groupInviteAcceptButton +- tapOn: + id: groupInviteLandingRetry +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/malformed-link.yml b/__e2e__/flows/group-invite/malformed-link.yml new file mode 100644 index 000000000..e2282d25c --- /dev/null +++ b/__e2e__/flows/group-invite/malformed-link.yml @@ -0,0 +1,19 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- openLink: 'blacksky://join/not-a-valid-group-code' +- extendedWaitUntil: + visible: + id: mobileShellView + timeout: 10000 +- assertNotVisible: + id: groupInviteLanding +- assertNotVisible: + id: groupInviteAcceptButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/malformed-success.yml b/__e2e__/flows/group-invite/malformed-success.yml new file mode 100644 index 000000000..32aff94db --- /dev/null +++ b/__e2e__/flows/group-invite/malformed-success.yml @@ -0,0 +1,33 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: malformed-success +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/misconfigured.yml b/__e2e__/flows/group-invite/misconfigured.yml new file mode 100644 index 000000000..2c036c055 --- /dev/null +++ b/__e2e__/flows/group-invite/misconfigured.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: misconfigured +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is temporarily unavailable.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/navigation-failure.yml b/__e2e__/flows/group-invite/navigation-failure.yml new file mode 100644 index 000000000..616eb151d --- /dev/null +++ b/__e2e__/flows/group-invite/navigation-failure.yml @@ -0,0 +1,45 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: navigation +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailNavigation +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInviteNavigationError + timeout: 30000 +- assertVisible: 'Your membership and saved feeds are preserved.' +- assertVisible: + id: groupInviteNavigationRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' +- tapOn: + id: groupInviteNavigationRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 diff --git a/__e2e__/flows/group-invite/no-post.yml b/__e2e__/flows/group-invite/no-post.yml new file mode 100644 index 000000000..91b8d7093 --- /dev/null +++ b/__e2e__/flows/group-invite/no-post.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: no-post +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoPostableFeeds + timeout: 30000 +- assertVisible: + id: groupInviteNoPostableFeeds +- assertVisible: + id: groupInvitePinOpenButton +- assertVisible: 'Please let your admins know if you think this is a mistake.' diff --git a/__e2e__/flows/group-invite/pin-add-failure.yml b/__e2e__/flows/group-invite/pin-add-failure.yml new file mode 100644 index 000000000..7dcbe3d19 --- /dev/null +++ b/__e2e__/flows/group-invite/pin-add-failure.yml @@ -0,0 +1,43 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: pin-add +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailAdd +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInvitePinError + timeout: 30000 +- assertVisible: 'We could not save your feeds. Please try again.' +- tapOn: + id: groupInvitePinRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' diff --git a/__e2e__/flows/group-invite/pin-update-failure.yml b/__e2e__/flows/group-invite/pin-update-failure.yml new file mode 100644 index 000000000..6cbb18af3 --- /dev/null +++ b/__e2e__/flows/group-invite/pin-update-failure.yml @@ -0,0 +1,43 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: pin-update +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailUpdate +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInvitePinError + timeout: 30000 +- assertVisible: 'We could not save your feeds. Please try again.' +- tapOn: + id: groupInvitePinRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' diff --git a/__e2e__/flows/group-invite/preview-identity.yml b/__e2e__/flows/group-invite/preview-identity.yml new file mode 100644 index 000000000..50d87ab12 --- /dev/null +++ b/__e2e__/flows/group-invite/preview-identity.yml @@ -0,0 +1,21 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: 'Members' +- assertVisible: 'Test Community' +- assertNotVisible: + id: groupInviteAcceptedMembership +- assertNotVisible: + id: groupInviteFeedOption-0 +- assertNotVisible: + id: groupInviteFeedOption-1 diff --git a/__e2e__/flows/group-invite/preview-outage.yml b/__e2e__/flows/group-invite/preview-outage.yml new file mode 100644 index 000000000..7c7622f8f --- /dev/null +++ b/__e2e__/flows/group-invite/preview-outage.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: preview-outage +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/rapid-taps.yml b/__e2e__/flows/group-invite/rapid-taps.yml new file mode 100644 index 000000000..8379b2c26 --- /dev/null +++ b/__e2e__/flows/group-invite/rapid-taps.yml @@ -0,0 +1,35 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: rapid +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton + repeat: 2 + delay: 0 +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' diff --git a/__e2e__/flows/group-invite/rate-limit.yml b/__e2e__/flows/group-invite/rate-limit.yml new file mode 100644 index 000000000..129d1d598 --- /dev/null +++ b/__e2e__/flows/group-invite/rate-limit.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: rate-limit +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'Too many attempts. Please try again shortly.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/read-only.yml b/__e2e__/flows/group-invite/read-only.yml new file mode 100644 index 000000000..7d2926806 --- /dev/null +++ b/__e2e__/flows/group-invite/read-only.yml @@ -0,0 +1,36 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: read-only +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoPostableFeeds + timeout: 30000 +- assertVisible: + id: groupInviteFeedOption-0 +- assertVisible: '.*Read only.*' +- assertVisible: "You joined the group, but you don't currently have access to a feed you can post in." +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '1' + EXPECT_SAVED_PINNED: '1' diff --git a/__e2e__/flows/group-invite/same-did-other-did.yml b/__e2e__/flows/group-invite/same-did-other-did.yml new file mode 100644 index 000000000..d8524a741 --- /dev/null +++ b/__e2e__/flows/group-invite/same-did-other-did.yml @@ -0,0 +1,65 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: resumable +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInviteDialogHandle +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInviteDialogHandle +- tapOn: + id: e2eSignOut +- extendedWaitUntil: + visible: + id: e2eSignInAlice + timeout: 10000 +- tapOn: + id: e2eSignInBob +- extendedWaitUntil: + visible: + id: bottomBarHomeBtn + timeout: 30000 +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '3' + EXPECT_ACCEPT_WITH_BEARER: '3' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/selection-readable-fallback.yml b/__e2e__/flows/group-invite/selection-readable-fallback.yml new file mode 100644 index 000000000..99f7abcdc --- /dev/null +++ b/__e2e__/flows/group-invite/selection-readable-fallback.yml @@ -0,0 +1,37 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteFeedOption-1 + timeout: 30000 +- tapOn: + id: groupInviteFeedOption-1 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- assertVisible: e2e-group-read +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '1' + EXPECT_SAVED_PINNED: '1' + EXPECT_SAVED_VISIBLE: '1' + EXPECT_VISIBLE_PINNED: '1' diff --git a/__e2e__/flows/group-invite/success-mixed.yml b/__e2e__/flows/group-invite/success-mixed.yml new file mode 100644 index 000000000..686c8db92 --- /dev/null +++ b/__e2e__/flows/group-invite/success-mixed.yml @@ -0,0 +1,47 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- assertVisible: + id: groupInviteFeedOption-0 +- assertVisible: '.*Read only.*' +- assertVisible: + id: groupInviteFeedOption-1 +- assertVisible: '.*Postable feed.*Post.*read.*' +- assertNotVisible: + id: groupInviteFeedOption-2 +- assertNotVisible: '.*Inaccessible feed.*' +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- assertVisible: e2e-group-post +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' + EXPECT_INACCESSIBLE_SAVED: '0' diff --git a/__e2e__/flows/group-invite/warm-custom-scheme.yml b/__e2e__/flows/group-invite/warm-custom-scheme.yml new file mode 100644 index 000000000..33f9cdcde --- /dev/null +++ b/__e2e__/flows/group-invite/warm-custom-scheme.yml @@ -0,0 +1,23 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: + id: groupInviteAcceptButton +- assertNotVisible: + id: groupInviteLanding +- assertNotVisible: + id: loginForm +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/zero-readable.yml b/__e2e__/flows/group-invite/zero-readable.yml new file mode 100644 index 000000000..adf34256f --- /dev/null +++ b/__e2e__/flows/group-invite/zero-readable.yml @@ -0,0 +1,30 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: zero-readable +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoReadableFeeds + timeout: 30000 +- assertVisible: 'No feeds available.' +- assertVisible: + id: groupInviteNoReadableWarning +- assertVisible: 'Please let your admins know if you think this is a mistake.' +- assertNotVisible: + id: groupInvitePinOpenButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' diff --git a/__e2e__/helpers/assert-group-invite-state.js b/__e2e__/helpers/assert-group-invite-state.js new file mode 100644 index 000000000..05c7757bb --- /dev/null +++ b/__e2e__/helpers/assert-group-invite-state.js @@ -0,0 +1,80 @@ +var response = http.get('http://localhost:1986/__e2e/group-invite/state') + +if (response.status !== 200 || !response.body) { + throw new Error('Group invite fixture state was unavailable') +} + +var state +try { + state = json(response.body) +} catch (_error) { + throw new Error('Group invite fixture state response was invalid') +} + +function assertNumber(path, actual, expected) { + if (expected === undefined || expected === '') return + var parsed = Number(expected) + if (actual !== parsed) { + throw new Error(path + ' expected ' + parsed + ' but was ' + actual) + } +} + +assertNumber( + 'acceptRequests', + state.acceptRequests, + typeof EXPECT_ACCEPT_REQUESTS === 'undefined' + ? undefined + : EXPECT_ACCEPT_REQUESTS, +) +assertNumber( + 'acceptRequestsWithBearer', + state.acceptRequestsWithBearer, + typeof EXPECT_ACCEPT_WITH_BEARER === 'undefined' + ? undefined + : EXPECT_ACCEPT_WITH_BEARER, +) +assertNumber( + 'claimCount', + state.claimCount, + typeof EXPECT_CLAIM_COUNT === 'undefined' ? undefined : EXPECT_CLAIM_COUNT, +) +assertNumber( + 'claimantCount', + state.claimantCount, + typeof EXPECT_CLAIMANT_COUNT === 'undefined' + ? undefined + : EXPECT_CLAIMANT_COUNT, +) +assertNumber( + 'savedFeeds.total', + state.savedFeeds.total, + typeof EXPECT_SAVED_TOTAL === 'undefined' ? undefined : EXPECT_SAVED_TOTAL, +) +assertNumber( + 'savedFeeds.pinned', + state.savedFeeds.pinned, + typeof EXPECT_SAVED_PINNED === 'undefined' ? undefined : EXPECT_SAVED_PINNED, +) +assertNumber( + 'savedFeeds.visible', + state.savedFeeds.visible, + typeof EXPECT_SAVED_VISIBLE === 'undefined' + ? undefined + : EXPECT_SAVED_VISIBLE, +) +assertNumber( + 'savedFeeds.visiblePinned', + state.savedFeeds.visiblePinned, + typeof EXPECT_VISIBLE_PINNED === 'undefined' + ? undefined + : EXPECT_VISIBLE_PINNED, +) +assertNumber( + 'savedFeeds.inaccessible', + state.savedFeeds.inaccessible, + typeof EXPECT_INACCESSIBLE_SAVED === 'undefined' + ? undefined + : EXPECT_INACCESSIBLE_SAVED, +) + +output.groupInviteStateChecked = true diff --git a/__e2e__/helpers/group-invite-setup.yml b/__e2e__/helpers/group-invite-setup.yml new file mode 100644 index 000000000..b61f74bf1 --- /dev/null +++ b/__e2e__/helpers/group-invite-setup.yml @@ -0,0 +1,8 @@ +appId: community.blacksky.app +--- +- runScript: + file: ../setupServer.js + env: + SERVER_PATH: '?groupInvite=${SCENARIO}' +- runFlow: + file: ../setupApp.yml diff --git a/__e2e__/helpers/group-invite-sign-in-alice.yml b/__e2e__/helpers/group-invite-sign-in-alice.yml new file mode 100644 index 000000000..a0af1e41c --- /dev/null +++ b/__e2e__/helpers/group-invite-sign-in-alice.yml @@ -0,0 +1,12 @@ +appId: community.blacksky.app +--- +- extendedWaitUntil: + visible: + id: e2eSignInAlice + timeout: 10000 +- tapOn: + id: e2eSignInAlice +- extendedWaitUntil: + visible: + id: bottomBarHomeBtn + timeout: 30000 diff --git a/__e2e__/helpers/group-invite-sign-in.yml b/__e2e__/helpers/group-invite-sign-in.yml new file mode 100644 index 000000000..307b121b2 --- /dev/null +++ b/__e2e__/helpers/group-invite-sign-in.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- tapOn: + id: 'groupInviteLandingSignIn' +- tapOn: + id: 'selectServiceButton' +- tapOn: 'Custom' +- tapOn: + id: 'customServerTextInput' +- inputText: 'http://localhost:3000' +- pressKey: Enter +- tapOn: + id: 'doneBtn' +- tapOn: + id: 'loginUsernameInput' +- inputText: 'alice.test' +- tapOn: + id: 'loginPasswordInput' +- inputText: 'hunter2' +- pressKey: Enter +- extendedWaitUntil: + visible: + id: 'groupInviteAcceptButton' + timeout: 30000 diff --git a/__e2e__/setupApp.yml b/__e2e__/setupApp.yml index d26ad9df2..3bee39643 100644 --- a/__e2e__/setupApp.yml +++ b/__e2e__/setupApp.yml @@ -1,15 +1,15 @@ appId: community.blacksky.app --- - launchApp: - appId: "community.blacksky.app" + appId: 'community.blacksky.app' clearState: true arguments: - "-EXDevMenuIsOnboardingFinished": true + '-EXDevMenuIsOnboardingFinished': true - runFlow: when: platform: iOS commands: - - openLink: "exp+blacksky://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8082" + - openLink: 'exp+blacksky://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8082' - runFlow: when: visible: 'Open in "Blacksky"' @@ -19,11 +19,11 @@ appId: community.blacksky.app when: platform: Android commands: - - tapOn: 'http://localhost:8082' + - tapOn: 'http://10.0.2.2:8082' - runFlow: - label: "Dismiss Expo dev menu" + label: 'Dismiss Expo dev menu' when: - visible: "Continue" + visible: 'Continue' commands: - back - tapOn: diff --git a/__e2e__/setupServer.js b/__e2e__/setupServer.js index 5038197b0..08fbf8996 100644 --- a/__e2e__/setupServer.js +++ b/__e2e__/setupServer.js @@ -4,5 +4,29 @@ var res = http.post('http://localhost:1986/' + SERVER_PATH, { body: '', }) +if (res.status !== 200 || !res.body) { + throw new Error( + 'Local E2E manager failed to create the requested fixture (status ' + + res.status + + ')', + ) +} + // eslint-disable-next-line no-undef -output.result = json(res.body).appviewDid +var payload +try { + payload = json(res.body) +} catch (_error) { + throw new Error('Local E2E manager returned an invalid fixture response') +} + +if (!payload || !payload.appviewDid) { + throw new Error('Local E2E manager returned an incomplete fixture response') +} + +output.result = payload.appviewDid +if (payload.groupInvite) { + output.groupInviteCode = payload.groupInvite.code + output.groupInviteScenario = payload.groupInvite.scenario + output.groupInviteServiceUrl = payload.groupInvite.acornUrl +} diff --git a/__tests__/lib/feed-manip-community.test.ts b/__tests__/lib/feed-manip-community.test.ts index 8350acef5..a78ca36a3 100644 --- a/__tests__/lib/feed-manip-community.test.ts +++ b/__tests__/lib/feed-manip-community.test.ts @@ -4,7 +4,7 @@ import { type AppBskyFeedPost, } from '@atproto/api' -import {FeedTuner} from '#/lib/api/feed-manip' +import {FeedTuner, FeedViewPostsSlice} from '#/lib/api/feed-manip' // The repo-wide manual mock stubs CID.parse away, which makes every // cid-format validation fail; these tests exercise real record validation. @@ -20,6 +20,8 @@ const VIEWER_DID = 'did:plc:viewer' const MEMBER_DID = 'did:plc:member' const COLLECTION = 'community.blacksky.feed.post' const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' +const SPACE_URI = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/root' function author( did: string, @@ -77,6 +79,37 @@ function followingTuner() { } describe('FeedTuner with merged community posts', () => { + it('keeps a space quote whose embedded record uses a space URI', () => { + const post = communityPost({rkey: 'quote'}) + post.uri = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/quote' + post.record = { + $type: 'app.bsky.feed.post', + text: 'quoted', + createdAt: '2026-07-17T12:00:00.000Z', + embed: { + $type: 'app.bsky.embed.record', + record: {uri: SPACE_URI, cid: CID}, + }, + } + post.embed = { + $type: 'app.bsky.embed.record#view', + record: { + $type: 'app.bsky.embed.record#viewRecord', + uri: SPACE_URI, + cid: CID, + author: author(MEMBER_DID), + value: {text: 'root', createdAt: '2026-07-17T12:00:00.000Z'}, + indexedAt: '2026-07-17T12:00:00.000Z', + }, + } + + const slice = new FeedViewPostsSlice({post}) + + expect(slice.items).toHaveLength(1) + expect(slice.isQuotePost).toBe(true) + }) + it('keeps a top-level community post', () => { const feed: AppBskyFeedDefs.FeedViewPost[] = [ {post: communityPost({rkey: 'aaa'})}, diff --git a/__tests__/lib/space-feed-routing.test.ts b/__tests__/lib/space-feed-routing.test.ts new file mode 100644 index 000000000..945977790 --- /dev/null +++ b/__tests__/lib/space-feed-routing.test.ts @@ -0,0 +1,155 @@ +// `jsonToLex` walks the body looking for CID links, and the multiformats CID +// helper it uses does not load under jest's module resolution. Nothing here is +// about CID inflation, so it is stubbed to a passthrough. +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) + +import {type AtpAgent} from '@atproto/api' + +import {CustomFeedAPI} from '#/lib/api/feed/custom' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' + +const FEED = 'at://did:plc:community/app.bsky.feed.generator/private' +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kaaa` + +const config = { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + group: 'at://did:plc:community/app.bsky.graph.list/members', + createdAt: '2026-08-18T00:00:00.000Z', + space: SPACE, +} + +type FakeAgent = { + did?: string + fetchHandler: jest.Mock + app: {bsky: {feed: {getFeed: jest.Mock}}} + com: {atproto: {repo: {getRecord: jest.Mock}}} +} + +function agent({did}: {did?: string}): FakeAgent { + const getFeed = jest.fn() + const fetchHandler = jest.fn((path: string) => { + if (path.includes('community.blacksky.feed.getSpaceFeed')) { + return Promise.resolve( + new Response( + JSON.stringify({ + cursor: '2026-08-18T00:00:00.000Z::bafyone', + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'hi'}, + indexedAt: '2026-08-18T00:00:00.000Z', + communitySpace: SPACE, + }, + }, + ], + }), + {status: 200, headers: {'content-type': 'application/json'}}, + ), + ) + } + throw new Error(`unexpected request: ${path}`) + }) + return { + did, + fetchHandler, + app: {bsky: {feed: {getFeed}}}, + com: { + atproto: { + repo: { + getRecord: jest.fn(() => Promise.resolve({data: {value: config}})), + }, + }, + }, + } +} + +// The feed APIs take a real `AtpAgent`; only the four members above are +// reachable on this path, so the fake is narrowed rather than filled in. +const asAgent = (a: FakeAgent) => a as unknown as AtpAgent + +describe('space-backed feed routing', () => { + it('reads a space feed through the private endpoint and never the standard one', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + const page = await api.fetch({cursor: undefined, limit: 30}) + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(page.feed).toHaveLength(1) + // The real space record URI survives: every later interaction (like, + // delete, permalink, thread) targets it. + expect(page.feed[0].post.uri).toBe(POST) + expect(page.feed[0].post.$type).toBe('app.bsky.feed.defs#postView') + }) + + it('peekLatest uses the same endpoint, so polling agrees with pagination', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await api.peekLatest() + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(a.fetchHandler).toHaveBeenCalled() + }) + + it('refuses logged out rather than falling back to the public appview', async () => { + const a = agent({}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await expect(api.fetch({cursor: undefined, limit: 30})).rejects.toThrow( + 'FeedSignedInOnly', + ) + await expect(api.peekLatest()).rejects.toThrow('FeedSignedInOnly') + expect(a.fetchHandler).not.toHaveBeenCalled() + }) +}) + +describe('private view type mapping', () => { + it('renames the whole tree, quote embeds included', () => { + const page = toSpaceFeedPage({ + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice'}, + record: {}, + indexedAt: '2026-08-18T00:00:00.000Z', + embed: { + $type: 'community.blacksky.feed.defs#spaceRecordView', + record: { + $type: 'community.blacksky.feed.defs#spaceViewRecord', + uri: POST, + }, + }, + }, + }, + ], + }) + const embed = page.feed[0].post.embed as unknown as Record< + string, + Record + > + expect(embed.$type).toBe('app.bsky.embed.record#view') + expect(embed.record.$type).toBe('app.bsky.embed.record#viewRecord') + // A space URI is carried through untouched; nothing parses it. + expect(embed.record.uri).toBe(POST) + }) + + it('drops a structurally invalid row instead of the whole page', () => { + const page = toSpaceFeedPage({feed: [{post: {}}, {nope: true}]}) + expect(page.feed).toEqual([]) + expect(toPostView({uri: 42})).toBeUndefined() + }) +}) diff --git a/dev-env/group-invite-fixture.ts b/dev-env/group-invite-fixture.ts new file mode 100644 index 000000000..570add77f --- /dev/null +++ b/dev-env/group-invite-fixture.ts @@ -0,0 +1,314 @@ +export type GroupInviteFixtureScenario = + | 'mixed' + | 'read-only' + | 'no-post' + | 'zero-readable' + | 'missing' + | 'unavailable' + | 'expired' + | 'consumed' + | 'capacity' + | 'auth-required' + | 'preview-outage' + | 'accept-outage' + | 'malformed-success' + | 'capability-outage' + | 'misconfigured' + | 'rate-limit' + | 'resumable' + | 'existing-unpinned' + | 'pin-update' + | 'pin-add' + | 'navigation' + | 'rapid' + +/** + * These values are deliberately synthetic and only exist in the local E2E + * fixture. They are long enough to exercise the production router's code + * validation without putting invite material in UI selectors or logs. + */ +const fixtureCode = (name: string) => `e2e-${name}`.padEnd(43, 'x') + +export const GROUP_INVITE_FIXTURE_CODES: Record< + GroupInviteFixtureScenario, + string +> = { + mixed: fixtureCode('mixed'), + 'read-only': fixtureCode('read-only'), + 'no-post': fixtureCode('no-post'), + 'zero-readable': fixtureCode('zero-readable'), + missing: fixtureCode('missing'), + unavailable: fixtureCode('unavailable'), + expired: fixtureCode('expired'), + consumed: fixtureCode('consumed'), + capacity: fixtureCode('capacity'), + 'auth-required': fixtureCode('auth-required'), + 'preview-outage': fixtureCode('preview-outage'), + 'accept-outage': fixtureCode('accept-outage'), + 'malformed-success': fixtureCode('malformed-success'), + 'capability-outage': fixtureCode('capability-outage'), + misconfigured: fixtureCode('misconfigured'), + 'rate-limit': fixtureCode('rate-limit'), + resumable: fixtureCode('resumable'), + 'existing-unpinned': fixtureCode('existing-unpinned'), + 'pin-update': fixtureCode('pin-update'), + 'pin-add': fixtureCode('pin-add'), + navigation: fixtureCode('navigation'), + rapid: fixtureCode('rapid'), +} + +export type GroupInviteFixtureFeed = { + uri: string + name: string + canView: boolean + canPost: boolean +} + +type InviteRecord = { + claimedDid?: string + grantCompleted: boolean + malformedResponseReturned: boolean + capabilityOutageReturned: boolean +} + +export type GroupInviteFixtureResponse = { + status: number + body: Record +} + +export type GroupInviteFixtureState = { + scenario: GroupInviteFixtureScenario + previewRequests: number + acceptRequests: number + acceptRequestsWithBearer: number + claimCount: number + grantCompleted: boolean + claimantCount: number + visibleFeedCount: number + inaccessibleFeedCount: number +} + +const ERROR_STATUS = { + InviteUnavailable: {status: 400, code: 'BAD_REQUEST'}, + GroupAtCapacity: {status: 409, code: 'CONFLICT'}, + AuthenticationRequired: {status: 401, code: 'UNAUTHORIZED'}, + AuthorizationUnavailable: {status: 503, code: 'SERVICE_UNAVAILABLE'}, + InviteMisconfigured: {status: 500, code: 'INTERNAL_SERVER_ERROR'}, + RateLimitExceeded: {status: 429, code: 'TOO_MANY_REQUESTS'}, +} as const + +function success(data: unknown): GroupInviteFixtureResponse { + return { + status: 200, + body: {result: {data: {json: data}}}, + } +} + +function failure( + stableCode: keyof typeof ERROR_STATUS, +): GroupInviteFixtureResponse { + const transport = ERROR_STATUS[stableCode] + return { + status: transport.status, + body: { + error: { + json: { + message: stableCode, + data: {code: transport.code}, + }, + }, + }, + } +} + +function isBearerAuthorization(value: string | undefined) { + return /^Bearer\s+\S+$/.test(value ?? '') +} + +export class GroupInviteFixture { + private readonly communityName = 'Test Community' + private readonly groupName = 'members' + private communityDid = 'did:plc:e2e-community' + private feeds: GroupInviteFixtureFeed[] = [] + private record: InviteRecord = this.newRecord() + private previewRequestCount = 0 + private acceptRequestCount = 0 + private acceptRequestsWithBearer = 0 + private claimCount = 0 + private claimants = new Set() + private scenario: GroupInviteFixtureScenario + + constructor(scenario: GroupInviteFixtureScenario = 'mixed') { + this.scenario = scenario + } + + configure({ + scenario, + communityDid, + feeds, + }: { + scenario: GroupInviteFixtureScenario + communityDid: string + feeds: GroupInviteFixtureFeed[] + }) { + this.scenario = scenario + this.communityDid = communityDid + this.feeds = feeds + this.record = this.newRecord() + this.previewRequestCount = 0 + this.acceptRequestCount = 0 + this.acceptRequestsWithBearer = 0 + this.claimCount = 0 + this.claimants = new Set() + + if (scenario === 'consumed') { + this.record.claimedDid = 'did:plc:e2e-consumed-by-other' + this.record.grantCompleted = true + this.claimants.add(this.record.claimedDid) + } + } + + get inviteCode() { + return GROUP_INVITE_FIXTURE_CODES[this.scenario] + } + + get visibleFeedUris() { + return this.responseFeeds().map(feed => feed.uri) + } + + get allFeedUris() { + return this.feeds.map(feed => feed.uri) + } + + preview(code: string): GroupInviteFixtureResponse { + this.previewRequestCount += 1 + + if (code !== this.inviteCode) return failure('InviteUnavailable') + if ( + this.scenario === 'unavailable' || + this.scenario === 'expired' || + this.scenario === 'consumed' || + this.scenario === 'missing' + ) { + return failure('InviteUnavailable') + } + if (this.scenario === 'preview-outage') { + return failure('AuthorizationUnavailable') + } + if (this.scenario === 'misconfigured') { + return failure('InviteMisconfigured') + } + + return success({ + community: {did: this.communityDid, name: this.communityName}, + group: {name: this.groupName, displayName: 'Members'}, + expiresAt: new Date(Date.now() + 86_400_000).toISOString(), + }) + } + + accept({ + code, + authorization, + memberDid, + }: { + code: string + authorization?: string + memberDid?: string + }): GroupInviteFixtureResponse { + this.acceptRequestCount += 1 + if (isBearerAuthorization(authorization)) { + this.acceptRequestsWithBearer += 1 + } + + if (code !== this.inviteCode) return failure('InviteUnavailable') + if (!isBearerAuthorization(authorization) || !memberDid) { + return failure('AuthenticationRequired') + } + if (this.scenario === 'auth-required') { + return failure('AuthenticationRequired') + } + if (this.scenario === 'accept-outage') { + return failure('AuthorizationUnavailable') + } + if (this.scenario === 'misconfigured') { + return failure('InviteMisconfigured') + } + if (this.scenario === 'rate-limit') { + return failure('RateLimitExceeded') + } + if (this.scenario === 'capacity') { + return failure('GroupAtCapacity') + } + if (this.record.claimedDid && this.record.claimedDid !== memberDid) { + return failure('InviteUnavailable') + } + + if (!this.record.claimedDid) { + this.record.claimedDid = memberDid + this.claimCount += 1 + this.claimants.add(memberDid) + this.record.grantCompleted = true + } + + if ( + this.scenario === 'malformed-success' && + !this.record.malformedResponseReturned + ) { + this.record.malformedResponseReturned = true + return success({membership: 'joined', feeds: 'malformed'}) + } + if ( + this.scenario === 'capability-outage' && + !this.record.capabilityOutageReturned + ) { + this.record.capabilityOutageReturned = true + return failure('AuthorizationUnavailable') + } + + return success({ + communityDid: this.communityDid, + groupName: this.groupName, + membership: 'joined', + feeds: this.responseFeeds(), + }) + } + + getState(): GroupInviteFixtureState { + return { + scenario: this.scenario, + previewRequests: this.previewRequestCount, + acceptRequests: this.acceptRequestCount, + acceptRequestsWithBearer: this.acceptRequestsWithBearer, + claimCount: this.claimCount, + grantCompleted: this.record.grantCompleted, + claimantCount: this.claimants.size, + visibleFeedCount: this.responseFeeds().length, + inaccessibleFeedCount: this.feeds.filter(feed => !feed.canView).length, + } + } + + private responseFeeds() { + if (this.scenario === 'zero-readable') return [] + if (this.scenario === 'read-only' || this.scenario === 'no-post') { + return this.feeds.filter(feed => feed.canView && !feed.canPost) + } + return this.feeds.filter(feed => feed.canView) + } + + private newRecord(): InviteRecord { + return { + grantCompleted: false, + malformedResponseReturned: false, + capabilityOutageReturned: false, + } + } +} + +export function isGroupInviteFixtureScenario( + value: string | string[] | undefined, +): value is GroupInviteFixtureScenario { + return ( + typeof value === 'string' && + Object.prototype.hasOwnProperty.call(GROUP_INVITE_FIXTURE_CODES, value) + ) +} diff --git a/dev-env/mock-server.ts b/dev-env/mock-server.ts index 12f5bb7ed..efbe41ad0 100644 --- a/dev-env/mock-server.ts +++ b/dev-env/mock-server.ts @@ -1,13 +1,233 @@ import {createServer as createHTTPServer} from 'node:http' import {parse} from 'node:url' +import { + GroupInviteFixture, + type GroupInviteFixtureFeed, + type GroupInviteFixtureScenario, + isGroupInviteFixtureScenario, +} from './group-invite-fixture.ts' import {createServer, type TestPDS} from './test-pds.ts' let server: TestPDS + +const GROUP_INVITE_COMMUNITY_DID = 'did:plc:e2e-community' + +async function ensureGroupInviteUsers(testPds: TestPDS) { + for (const name of ['alice', 'bob']) { + if (!testPds.mocker.users[name]) { + await testPds.mocker.createUser(name) + } + } +} + +async function seedGroupInviteFixture( + testPds: TestPDS, + scenario: GroupInviteFixtureScenario, +) { + await ensureGroupInviteUsers(testPds) + + const post = await testPds.mocker.createPost( + 'alice', + 'Synthetic group invite feed post', + ) + const postUris = [post.uri] + const readOnly = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-read', + postUris, + ) + const postable = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-post', + postUris, + ) + const inaccessible = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-hidden', + postUris, + ) + + const feeds: GroupInviteFixtureFeed[] = [ + { + uri: readOnly.uri, + name: 'Read only feed', + canView: scenario !== 'zero-readable', + canPost: false, + }, + { + uri: postable.uri, + name: 'Postable feed', + canView: scenario !== 'zero-readable', + canPost: true, + }, + { + uri: inaccessible.uri, + name: 'Inaccessible feed', + canView: false, + canPost: false, + }, + ] + + const fixture = new GroupInviteFixture(scenario) + fixture.configure({ + scenario, + communityDid: GROUP_INVITE_COMMUNITY_DID, + feeds, + }) + testPds.groupInviteFixture = fixture + + if ( + scenario === 'existing-unpinned' || + scenario === 'pin-update' || + scenario === 'pin-add' + ) { + await testPds.mocker.users.alice.agent.overwriteSavedFeeds([ + {id: readOnly.uri, type: 'feed', value: readOnly.uri, pinned: false}, + ]) + } + + // Ensure the local AppView has indexed the feed-generator records before a + // client can navigate to one from the invite dialog. + await testPds.mocker.testNet.processAll() +} + +function decodeServiceAuthIssuer(authorization: string | undefined) { + if (!authorization || !/^Bearer\s+\S+$/.test(authorization)) { + return undefined + } + const token = authorization.split(/\s+/)[1] + const payload = token?.split('.')[1] + if (!payload) return undefined + try { + const parsed = JSON.parse( + Buffer.from(payload, 'base64url').toString('utf8'), + ) as {iss?: unknown; sub?: unknown} + if (typeof parsed.iss === 'string') return parsed.iss + if (typeof parsed.sub === 'string') return parsed.sub + } catch { + // The fixture intentionally treats an undecodable token as unauthenticated. + } + return undefined +} + +async function readRequestBody(req: import('node:http').IncomingMessage) { + const chunks: Buffer[] = [] + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) + } + return Buffer.concat(chunks).toString('utf8') +} + +function sendJson( + res: import('node:http').ServerResponse, + status: number, + body: Record, +) { + res.writeHead(status, {'content-type': 'application/json'}) + res.end(JSON.stringify(body)) +} + +function inputCode(value: unknown) { + if (!value || typeof value !== 'object') return undefined + const wrapped = (value as {json?: unknown}).json + const input = wrapped && typeof wrapped === 'object' ? wrapped : value + const code = (input as {code?: unknown}).code + return typeof code === 'string' ? code : undefined +} + +async function handleGroupInviteRequest( + req: import('node:http').IncomingMessage, + res: import('node:http').ServerResponse, + procedure: 'preview' | 'accept', + query: Record, +) { + const fixture = server?.groupInviteFixture + if (!fixture) { + sendJson(res, 503, { + error: { + json: { + message: 'AuthorizationUnavailable', + data: {code: 'SERVICE_UNAVAILABLE'}, + }, + }, + }) + return + } + + let input: unknown + if (req.method === 'GET') { + const rawInput = query.input + if (typeof rawInput === 'string') { + try { + input = JSON.parse(rawInput) + } catch { + input = undefined + } + } + } else { + try { + input = JSON.parse(await readRequestBody(req)) + } catch { + input = undefined + } + } + + const code = inputCode(input) ?? '' + const result = + procedure === 'preview' + ? fixture.preview(code) + : fixture.accept({ + code, + authorization: + typeof req.headers.authorization === 'string' + ? req.headers.authorization + : undefined, + memberDid: decodeServiceAuthIssuer( + typeof req.headers.authorization === 'string' + ? req.headers.authorization + : undefined, + ), + }) + sendJson(res, result.status, result.body) +} + +async function handleGroupInviteState(res: import('node:http').ServerResponse) { + const fixture = server?.groupInviteFixture + if (!fixture) { + sendJson(res, 404, {error: 'No group invite fixture is active'}) + return + } + const fixtureState = fixture.getState() + const savedFeeds = await server.mocker.getSavedFeedSummary( + 'alice', + fixture.visibleFeedUris, + fixture.allFeedUris, + ) + sendJson(res, 200, {...fixtureState, savedFeeds}) +} + // eslint-disable-next-line @typescript-eslint/no-misused-promises createHTTPServer(async (req, res) => { const url = parse(req.url || '/', true) - if (req.method !== 'POST') { + const pathname = url.pathname || '/' + if (pathname === '/__e2e/group-invite/state' && req.method === 'GET') { + try { + await handleGroupInviteState(res) + } catch { + sendJson(res, 503, {error: 'Unable to read fixture state'}) + } + return + } + if (pathname === '/api/trpc/groupInvites.preview') { + await handleGroupInviteRequest(req, res, 'preview', url.query) + return + } + if (pathname === '/api/trpc/groupInvites.accept') { + await handleGroupInviteRequest(req, res, 'accept', url.query) + return + } + if (req.method !== 'POST' || pathname !== '/') { return res.writeHead(200).end() } try { @@ -18,6 +238,14 @@ createHTTPServer(async (req, res) => { server = await createServer({inviteRequired}) console.log('Listening at', server.pdsUrl) if (url?.query) { + const requestedGroupInvite = url.query.groupInvite + if ( + typeof requestedGroupInvite === 'string' && + isGroupInviteFixtureScenario(requestedGroupInvite) + ) { + console.log('Generating group invite fixture') + await seedGroupInviteFixture(server, requestedGroupInvite) + } if ('users' in url.query) { console.log('Generating mock users') await server.mocker.createUser('alice') @@ -97,8 +325,8 @@ createHTTPServer(async (req, res) => { await server.mocker.follow('alice', 'bob') await server.mocker.follow('alice', 'carla') console.log('Generating mock posts') - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let posts: Record = { + + let posts: Record = { alice: [], bob: [], carla: [], @@ -501,6 +729,13 @@ createHTTPServer(async (req, res) => { JSON.stringify({ pdsUrl: server.pdsUrl, appviewDid: server.appviewDid, + groupInvite: server.groupInviteFixture + ? { + scenario: server.groupInviteFixture.getState().scenario, + code: server.groupInviteFixture.inviteCode, + acornUrl: 'http://localhost:1986', + } + : undefined, }), ) } catch (e) { diff --git a/dev-env/test-pds.ts b/dev-env/test-pds.ts index 669686886..f0590194e 100644 --- a/dev-env/test-pds.ts +++ b/dev-env/test-pds.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import http from 'node:http' import net from 'node:net' import path from 'node:path' @@ -13,10 +14,19 @@ export interface TestUser { agent: BskyAgent } +export type SavedFeedSummary = { + total: number + pinned: number + visible: number + visiblePinned: number + inaccessible: number +} + export interface TestPDS { appviewDid: string pdsUrl: string mocker: Mocker + groupInviteFixture?: import('./group-invite-fixture.ts').GroupInviteFixture close: () => Promise } @@ -58,30 +68,103 @@ class StringIdGenerator { const ids = new StringIdGenerator() +type PdsProxy = { + close: () => Promise +} + +function sendJson( + res: http.ServerResponse, + status: number, + body: Record, +) { + res.writeHead(status, {'content-type': 'application/json'}) + res.end(JSON.stringify(body)) +} + +async function createPdsProxy( + port: number, + pdsTarget: string, +): Promise { + const server = http.createServer((req, res) => { + const pathname = new URL(req.url || '/', `http://${req.headers.host}`) + .pathname + const upstreamUrl = new URL(req.url || '/', pdsTarget) + const headers: http.OutgoingHttpHeaders = { + ...req.headers, + host: upstreamUrl.host, + } + if ( + pathname === '/xrpc/app.bsky.actor.getPreferences' || + pathname === '/xrpc/app.bsky.actor.putPreferences' + ) { + delete headers['atproto-proxy'] + } + const upstream = http.request( + upstreamUrl, + {method: req.method, headers}, + upstreamRes => { + res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers) + upstreamRes.pipe(res) + }, + ) + upstream.on('error', () => { + if (!res.headersSent) { + sendJson(res, 502, { + error: 'UpstreamUnavailable', + message: 'PDS unavailable', + }) + } else { + res.destroy() + } + }) + req.pipe(upstream) + }) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, 'localhost', resolve) + }) + return { + close: () => + new Promise((resolve, reject) => { + server.close(error => (error ? reject(error) : resolve())) + }), + } +} + export async function createServer( {inviteRequired}: {inviteRequired: boolean} = { inviteRequired: false, }, ): Promise { - const port = 3000 - const port2 = await getPort(port + 1) - const port3 = await getPort(port2 + 1) - const pdsUrl = `http://localhost:${port}` + const publicPdsPort = 3000 + const pdsPort = await getPort(publicPdsPort + 1) + const plcPort = await getPort(pdsPort + 1) + const bskyPort = await getPort(plcPort + 1) + const pdsUrl = `http://localhost:${publicPdsPort}` const id = ids.next() - const testNet = await TestNetwork.create({ pds: { - port, + port: pdsPort, hostname: 'localhost', inviteRequired, }, bsky: { dbPostgresSchema: `bsky_${id}`, - port: port3, + port: bskyPort, publicUrl: 'http://localhost:2584', }, - plc: {port: port2}, + plc: {port: plcPort}, }) + let pdsProxy: PdsProxy + try { + pdsProxy = await createPdsProxy( + publicPdsPort, + `http://localhost:${pdsPort}`, + ) + } catch (error) { + await testNet.close() + throw error + } // DISABLED - looks like dev-env added this and now it conflicts // add the test mod authority @@ -120,6 +203,7 @@ export async function createServer( pdsUrl, mocker: new Mocker(testNet, pdsUrl, pic), async close() { + await pdsProxy.close() await testNet.close() }, } @@ -351,6 +435,34 @@ class Mocker { ) } + async getSavedFeedSummary( + user: string, + visibleUris: readonly string[], + allUris: readonly string[], + ): Promise { + const agent = this.users[user]?.agent + if (!agent) { + throw new Error(`Not a user: ${user}`) + } + const preferences = await agent.getPreferences() + const savedFeeds = preferences.savedFeeds.filter( + feed => feed.type === 'feed', + ) + const visible = new Set(visibleUris) + const all = new Set(allUris) + return { + total: savedFeeds.length, + pinned: savedFeeds.filter(feed => feed.pinned).length, + visible: savedFeeds.filter(feed => visible.has(feed.value)).length, + visiblePinned: savedFeeds.filter( + feed => visible.has(feed.value) && feed.pinned, + ).length, + inaccessible: savedFeeds.filter( + feed => all.has(feed.value) && !visible.has(feed.value), + ).length, + } + } + async labelAccount(label: string, user: string) { const did = this.users[user]?.did if (!did) { diff --git a/docs/testing.md b/docs/testing.md index 763b267eb..2bf329e34 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -21,8 +21,29 @@ You will need to allow your device access to the port that the mock server is ru ``` adb reverse tcp:3000 tcp:3000 +adb reverse tcp:1986 tcp:1986 +adb reverse tcp:8082 tcp:8082 ``` +### Group invite Maestro suite + +The production-shaped group invite flows live in +`__e2e__/flows/group-invite/`. They reset the existing dev-env manager with a +scenario-specific local fixture and use real local feed-generator records. +Point the client at that fixture while starting Metro; the value is read by +the app at runtime and does not change the existing build commands. + +```sh +EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 pnpm e2e:start +EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 pnpm e2e:run __e2e__/flows/group-invite +``` + +Build the E2E app once with the existing `pnpm e2e:build` command. The local +fixture checks that accept requests carry a Bearer header, but it does not +validate the production service-auth signature. A disposable real Acorn, +OpenFGA, and feed-service journey is still required for that enforcement +boundary. + ### Running Maestro tests - In one tab, run `pnpm e2e:mock-server` @@ -30,6 +51,7 @@ adb reverse tcp:3000 tcp:3000 - In a third tab, run `pnpm e2e:run __e2e__` ## Using Flashlight for Performance Testing + 1. Make sure Maestro is installed (optional: only for automated testing) by following the instructions above 2. Install Flashlight by following [these instructions](https://docs.flashlight.dev/) 3. The simplest way to get started is by running `pnpm perf:measure` which will run a live preview of the performance test results. You can [see a demo here](https://github.com/bamlab/flashlight/assets/4534323/4038a342-f145-4c3b-8cde-17949bf52612) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 68dfa075a..8b0fb9df9 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -856,7 +856,7 @@ }, "src/lib/hooks/useIntentHandler.ts": { "@typescript-eslint/no-floating-promises": { - "count": 2 + "count": 1 } }, "src/lib/hooks/useNonReactiveCallback.ts": { diff --git a/jest/jestSetup.js b/jest/jestSetup.js index ca04d5426..402bb09eb 100644 --- a/jest/jestSetup.js +++ b/jest/jestSetup.js @@ -106,3 +106,8 @@ jest.mock('expo-modules-core', () => ({ jest.mock('expo-localization', () => ({ getLocales: () => [], })) + +// Lingui throws on any `t` outside an activated locale, so a message string is +// unreachable in tests until one is set — including the guard messages. +const {i18n} = require('@lingui/core') +i18n.loadAndActivate({locale: 'en', messages: {}}) diff --git a/package.json b/package.json index d13487e37..fb1e99fff 100644 --- a/package.json +++ b/package.json @@ -66,9 +66,9 @@ "lint-native:fix": "swiftlint --fix ./modules && ktlint --format ./modules", "typecheck": "tsgo --project ./tsconfig.check.json", "e2e:mock-server": "cd dev-env && pnpm start", - "e2e:build": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios", - "e2e:build-android": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:android", - "e2e:start": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start -c --port 8082", + "e2e:build": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios", + "e2e:build-android": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:android", + "e2e:start": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start -c --port 8082", "e2e:run": "maestro test", "perf:test": "NODE_ENV=test maestro test", "perf:test:run": "NODE_ENV=test maestro test __e2e__/perf-test.yml", diff --git a/src/Navigation.tsx b/src/Navigation.tsx index e1f93e2a6..5bfbc7e8d 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -44,7 +44,11 @@ import { type State, } from '#/lib/routes/types' import {bskyTitle} from '#/lib/strings/headings' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + getDeepLinkAnalyticsTarget, + GROUP_INVITE_CODE_REGEX, +} from '#/lib/strings/url-helpers' import {useUnreadNotifications} from '#/state/queries/notifications/unread' import {useSession} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' @@ -849,7 +853,11 @@ const LINKING = { // react-navigation strips the `bluesky://` prefix and passes the path // without a leading slash, so normalize before matching. const normalizedPath = path.startsWith('/') ? path : `/${path}` - if (CHAT_INVITE_CODE_REGEX.test(normalizedPath.split('?')[0])) { + const pathWithoutQuery = normalizedPath.split('?')[0] + if ( + CHAT_INVITE_CODE_REGEX.test(pathWithoutQuery) || + GROUP_INVITE_CODE_REGEX.test(pathWithoutQuery) + ) { if (IS_NATIVE) { return buildStateObject('HomeTab', 'Home', params) } @@ -1033,7 +1041,7 @@ function RoutesContainer({children}: React.PropsWithChildren<{}>) { const referrerInfo = Referrer.getReferrerInfo() if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { ax.metric('deepLink:referrerReceived', { - to: window.location.href, + to: getDeepLinkAnalyticsTarget(window.location.href), referrer: referrerInfo?.referrer, hostname: referrerInfo?.hostname, }) diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 794908e50..3390d314b 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -57,6 +57,7 @@ export type Events = { | 'Deactivated' | 'Takendown' | 'AgeAssuranceNoAccessScreen' + | 'GroupInvite' scope: 'current' | 'every' } // OAuth session lifecycle. These are silent client-side events used to @@ -682,6 +683,19 @@ export type Events = { } 'groupchat:inviteLink:redeem': {} + // Group invite deep links + 'groupInvite:opened': { + hasSession: boolean + } + 'groupInvite:signInRequested': {} + 'groupInvite:acceptAttempted': {} + 'groupInvite:joined': { + hasPosting: boolean + } + 'groupInvite:failure': { + errorName: string + } + // Group chat user interactions 'groupchat:message:send': { convoId: string diff --git a/src/components/CommunityOnlyBadge.tsx b/src/components/CommunityOnlyBadge.tsx index 5ecc0a8a2..a3d94c931 100644 --- a/src/components/CommunityOnlyBadge.tsx +++ b/src/components/CommunityOnlyBadge.tsx @@ -7,19 +7,25 @@ import {Trans} from '@lingui/react/macro' import {Logo as BlackskyLogo} from '#/view/icons/Logo' import {atoms as a, useTheme} from '#/alf' import {ChevronBottom_Stroke2_Corner0_Rounded as ChevronDown} from '#/components/icons/Chevron' +import {Group3_Stroke2_Corner0_Rounded as GroupIcon} from '#/components/icons/Group' import * as Tooltip from '#/components/Tooltip' import {Text} from '#/components/Typography' -const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' - -export function isCommunityPostUri(uri: string | undefined): boolean { - return !!uri && uri.includes(COMMUNITY_POST_COLLECTION) -} - -export function CommunityOnlyBadge() { +export function CommunityOnlyBadge({ + communitySpace, +}: { + communitySpace?: string +}) { const t = useTheme() const {_} = useLingui() const [visible, setVisible] = useState(false) + const isTenant = !!communitySpace + const label = isTenant + ? _(msg`Community-only post`) + : _(msg`Blacksky-only post`) + const hint = isTenant + ? _(msg`Only visible to members of this community`) + : _(msg`Only visible to members of the Blacksky community`) useEffect(() => { return () => setVisible(false) @@ -33,10 +39,8 @@ export function CommunityOnlyBadge() { setVisible(v => !v)} style={[ a.flex_row, @@ -47,19 +51,33 @@ export function CommunityOnlyBadge() { a.rounded_full, {backgroundColor: t.palette.primary_500}, ]}> - + {isTenant ? ( + + ) : ( + + )} - + - Blacksky Only + {isTenant ? ( + Community Only + ) : ( + Blacksky Only + )} - - This post is only visible to members of the Blacksky community. - + {isTenant ? ( + + This post is only visible to members of its community. + + ) : ( + + This post is only visible to members of the Blacksky community. + + )} diff --git a/src/components/Dialog/index.tsx b/src/components/Dialog/index.tsx index bd23e566a..bec939b0a 100644 --- a/src/components/Dialog/index.tsx +++ b/src/components/Dialog/index.tsx @@ -396,9 +396,11 @@ export function FlatListFooter({ export function Handle({ difference = false, fill, + testID, }: { difference?: boolean fill?: string + testID?: string }) { const t = useTheme() const {_} = useLingui() @@ -408,6 +410,7 @@ export function Handle({ return ( close()} accessibilityLabel={_(msg`Dismiss`)} diff --git a/src/components/Dialog/index.web.tsx b/src/components/Dialog/index.web.tsx index 37c893be1..879d008f4 100644 --- a/src/components/Dialog/index.web.tsx +++ b/src/components/Dialog/index.web.tsx @@ -321,7 +321,7 @@ export function Close() { ) } -export function Handle() { +export function Handle(_props?: {testID?: string}) { return null } diff --git a/src/components/Post/Embed/index.tsx b/src/components/Post/Embed/index.tsx index 914ffc65c..2fe377379 100644 --- a/src/components/Post/Embed/index.tsx +++ b/src/components/Post/Embed/index.tsx @@ -4,14 +4,13 @@ import { type $Typed, type AppBskyFeedDefs, AppBskyFeedPost, - AtUri, moderatePost, RichText as RichTextAPI, } from '@atproto/api' import {Trans} from '@lingui/react/macro' import {useQueryClient} from '@tanstack/react-query' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {getChatInviteCodeFromUrl} from '#/lib/strings/url-helpers' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useEmbedFallback} from '#/state/queries/embed-fallback' @@ -326,12 +325,7 @@ export function QuoteEmbed({ const t = useTheme() const queryClient = useQueryClient() - const itemUrip = new AtUri(quote.uri) - const isCommunityQuote = - itemUrip.collection === 'community.blacksky.feed.post' - const itemHref = isCommunityQuote - ? `${makeProfileLink(quote.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` - : makeProfileLink(quote.author, 'post', itemUrip.rkey) + const itemHref = postPermalink(quote.author, quote.uri) const itemTitle = `Post by ${quote.author.handle}` const richText = useMemo(() => { diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index 8b0c4651c..a7f700074 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -17,8 +17,10 @@ import {plural} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' +import {getCommunitySpaceUri} from '#/lib/api/community-post' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {getCurrentRoute} from '#/lib/routes/helpers' -import {makeProfileLink} from '#/lib/routes/links' +import {makeProfileLink, postPermalink} from '#/lib/routes/links' import { type CommonNavigatorParams, type NavigationProp, @@ -162,7 +164,8 @@ let PostMenuItems = ({ [postUri], ) const {data: peerModPerms} = useMyPeerModPermissions() - const canLabelPost = !!peerModPerms?.isPeerMod && isCommunityPost + const canLabelPost = + !!peerModPerms?.isPeerMod && isCommunityPost && !getCommunitySpaceUri(post) const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue( post, rootUri, @@ -175,6 +178,10 @@ let PostMenuItems = ({ }) const isReplyHiddenByThreadgate = threadgateHiddenReplies.has(postUri) const isPinned = post.viewer?.pinned + // Pinning writes the post's URI into the public profile record, so a space + // post cannot be pinned: the URI alone publishes that the private post + // exists, and who wrote it. + const canPin = !isSpaceRecordUri(postUri) const {mutateAsync: toggleQuoteDetachment, isPending: isDetachPending} = useToggleQuoteDetachmentMutation() @@ -188,10 +195,7 @@ let PostMenuItems = ({ }) const href = useMemo(() => { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const onDeletePost = () => { @@ -491,7 +495,7 @@ let PostMenuItems = ({ return ( <> - {isAuthor && ( + {isAuthor && canPin && ( <> { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx index 963c5bb04..ad10bcafd 100644 --- a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx +++ b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx @@ -1,11 +1,10 @@ import {memo, useMemo} from 'react' -import {AtUri} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {type NavigationProp} from '#/lib/routes/types' import {shareText, shareUrl} from '#/lib/sharing' import {toShareUrl} from '#/lib/strings/url-helpers' @@ -45,10 +44,7 @@ let ShareMenuItems = ({ const postAuthor = useProfileShadow(post.author) const href = useMemo(() => { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/index.tsx b/src/components/PostControls/ShareMenu/index.tsx index 6464d0dd3..7d9536818 100644 --- a/src/components/PostControls/ShareMenu/index.tsx +++ b/src/components/PostControls/ShareMenu/index.tsx @@ -4,13 +4,12 @@ import { type AppBskyFeedDefs, type AppBskyFeedPost, type AppBskyFeedThreadgate, - AtUri, type RichText as RichTextAPI, } from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {shareUrl} from '#/lib/sharing' import {toShareUrl} from '#/lib/strings/url-helpers' import {type Shadow} from '#/state/cache/post-shadow' @@ -85,10 +84,7 @@ let ShareMenuButton = ({ const onNativeLongPress = () => { ax.metric('share:press:nativeShare', {}) - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - const href = isCommunity ? `${link}?collection=${urip.collection}` : link + const href = postPermalink(post.author, post.uri) const url = toShareUrl(href) shareUrl(url) onShare() diff --git a/src/components/PostControls/index.tsx b/src/components/PostControls/index.tsx index 240a4256c..47c1a70e8 100644 --- a/src/components/PostControls/index.tsx +++ b/src/components/PostControls/index.tsx @@ -9,6 +9,10 @@ import { import {plural} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro' +import { + getCommunitySpaceUri, + isCommunityPostUri, +} from '#/lib/api/community-post' import {CountWheel} from '#/lib/custom-animations/CountWheel' import {AnimatedLikeIcon} from '#/lib/custom-animations/LikeIcon' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -24,10 +28,7 @@ import { useProgressGuideControls, } from '#/state/shell/progress-guide' import {atoms as a, useBreakpoints, useTheme} from '#/alf' -import { - CommunityOnlyBadge, - isCommunityPostUri, -} from '#/components/CommunityOnlyBadge' +import {CommunityOnlyBadge} from '#/components/CommunityOnlyBadge' import {Reply as Bubble} from '#/components/icons/Reply' import {useFormatPostStatCount} from '#/components/PostControls/util' import * as Skele from '#/components/Skeleton' @@ -267,7 +268,7 @@ let PostControls = ({ onQuote={onQuote} big={big} embeddingDisabled={Boolean(post.viewer?.embeddingDisabled)} - repostDisabled={post.uri.includes('community.blacksky.feed.post')} + repostDisabled={isCommunityPostUri(post.uri)} /> @@ -323,7 +324,9 @@ let PostControls = ({ a.align_center, secondaryControlSpacingStyles, ]}> - {isCommunityPostUri(post.uri) && } + {isCommunityPostUri(post.uri) && ( + + )} { - const actual = jest.requireActual('react-native') - - Object.defineProperty(actual.Platform, 'OS', { - value: 'ios', - configurable: true, - }) - Object.defineProperty(actual.Platform, 'Version', { - value: '17.0', - configurable: true, - }) - - return actual -}) - -jest.mock('react-native-uitextview', () => { - const React = require('react') - const {Text: RNText} = require('react-native') - - return { - UITextView: jest.fn(({children, ...props}) => ( - - {children} - - )), - } -}) - -describe('Text', () => { - it('renders non-selectable text without UITextView', () => { - const {getByText, queryByTestId} = render(Normal text) - - expect(getByText('Normal text')).toBeTruthy() - expect(queryByTestId('ui-text-view')).toBeNull() - }) - - it('uses UITextView for selectable iOS text', () => { - const {getByTestId} = render(Selectable text) - - expect(getByTestId('ui-text-view')).toBeTruthy() - }) - - it('does not nest UITextView inside selectable emoji text', () => { - const {getAllByTestId, getByText} = render( - - 😀 popular post - , - ) - - expect(getByText('😀 popular post')).toBeTruthy() - expect(getAllByTestId('ui-text-view')).toHaveLength(1) - }) - - it('still allows native Text children inside non-selectable text', () => { - const {getByText, queryByTestId} = render( - - Nested text - , - ) - - expect(getByText('Nested text')).toBeTruthy() - expect(queryByTestId('ui-text-view')).toBeNull() - }) -}) diff --git a/src/components/forms/Toggle/index.tsx b/src/components/forms/Toggle/index.tsx index a62a82b62..8bca96ead 100644 --- a/src/components/forms/Toggle/index.tsx +++ b/src/components/forms/Toggle/index.tsx @@ -72,6 +72,7 @@ export type GroupProps = React.PropsWithChildren<{ }> export type ItemProps = ViewStyleProp & { + testID?: string type?: 'radio' | 'checkbox' name: string label: string diff --git a/src/components/hooks/useLandingEntry.native.ts b/src/components/hooks/useLandingEntry.native.ts index c5950a646..5a7558be6 100644 --- a/src/components/hooks/useLandingEntry.native.ts +++ b/src/components/hooks/useLandingEntry.native.ts @@ -6,7 +6,10 @@ import { createStarterPackLinkFromAndroidReferrer, httpStarterPackUriToAtUri, } from '#/lib/strings/starter-pack' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + GROUP_INVITE_CODE_REGEX, +} from '#/lib/strings/url-helpers' import {useHasCheckedForStarterPack} from '#/state/preferences/used-starter-packs' import { useSetActiveLanding, @@ -38,6 +41,18 @@ export function useLandingEntry() { setReady(true) return } + const groupInviteMatch = urlp.pathname.match(GROUP_INVITE_CODE_REGEX) + if (groupInviteMatch) { + setActiveLanding({ + type: 'groupinvite', + // The code is sufficient to resume this flow. Do not retain the + // bearer-bearing URL in landing state across auth transitions. + uri: '', + code: groupInviteMatch[1], + }) + setReady(true) + return + } } // On Android, we cannot clear the referral link. It gets stored for 90 days and all we can do is query for it. So, diff --git a/src/components/intents/GroupInviteDialog.tsx b/src/components/intents/GroupInviteDialog.tsx new file mode 100644 index 000000000..80104d896 --- /dev/null +++ b/src/components/intents/GroupInviteDialog.tsx @@ -0,0 +1,502 @@ +import {useCallback, useEffect, useRef, useState} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' +import {useNavigation} from '@react-navigation/native' + +import { + isGroupInviteE2EFailure, + maybeFailGroupInviteE2E, +} from '#/lib/api/group-invite-e2e' +import { + getDefaultGroupInviteFeedUris, + getFirstSelectedGroupInviteFeed, + getGroupInviteFeedMutations, + getGroupInviteMembershipCopy, + getGroupInviteNoPostCopy, + groupInviteErrorCopy, + groupInviteFailureName, + shouldOpenGroupInviteFeedAfterPinning, + shouldResetGroupInvitePinning, + shouldTrackGroupInviteOpened, + summarizeGroupInviteFeeds, +} from '#/lib/api/group-invite-ui' +import { + type GroupInviteAcceptance, + GroupInviteClientError, + GroupInviteError, +} from '#/lib/api/group-invites' +import {type NavigationProp} from '#/lib/routes/types' +import {logger} from '#/logger' +import { + useAcceptGroupInviteMutation, + useGroupInvitePreviewQuery, +} from '#/state/queries/group-invites' +import { + useAddSavedFeedsMutation, + usePreferencesQuery, + useUpdateSavedFeedsMutation, +} from '#/state/queries/preferences' +import {useSessionApi} from '#/state/session' +import {useSetActiveLanding} from '#/state/shell/landing' +import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useSetSelectedFeed} from '#/state/shell/selected-feed' +import {atoms as a, useTheme, web} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import * as Toggle from '#/components/forms/Toggle' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' +import {useIntentDialogs} from './IntentDialogs' + +export function GroupInviteDialog() { + const {groupInviteDialogControl, groupInviteState, setGroupInviteState} = + useIntentDialogs() + return ( + setGroupInviteState(undefined)} + nativeOptions={{preventExpansion: true}}> + + + + + ) +} + +export function GroupInviteDialogContent({code}: {code?: string}) { + const {t: l} = useLingui() + const ax = useAnalytics() + const t = useTheme() + const navigation = useNavigation() + const {groupInviteDialogControl} = useIntentDialogs() + const {logoutCurrentAccount} = useSessionApi() + const {requestSwitchToAccount} = useLoggedOutViewControls() + const setActiveLanding = useSetActiveLanding() + const { + data: preview, + error: previewError, + isPending: isPreviewPending, + refetch: refetchPreview, + } = useGroupInvitePreviewQuery(code) + const { + mutateAsync: acceptInvite, + isPending: isAcceptPending, + error: acceptError, + reset: resetAccept, + } = useAcceptGroupInviteMutation() + const {mutateAsync: addSavedFeeds} = useAddSavedFeedsMutation() + const {mutateAsync: updateSavedFeeds} = useUpdateSavedFeedsMutation() + const preferencesQuery = usePreferencesQuery() + const {data: preferences} = preferencesQuery + const savedFeeds = preferences?.savedFeeds + const preferencesReady = preferencesQuery.isSuccess + const setSelectedFeed = useSetSelectedFeed() + const [acceptance, setAcceptance] = useState() + const [selectedFeedUris, setSelectedFeedUris] = useState([]) + const [hasPinned, setHasPinned] = useState(false) + const [pinError, setPinError] = useState<'pinning' | 'navigation'>() + const [isPinning, setIsPinning] = useState(false) + const reportedPreviewError = useRef(undefined) + const acceptingRef = useRef(false) + + useEffect(() => { + if (code && shouldTrackGroupInviteOpened(code)) { + ax.metric('groupInvite:opened', {hasSession: true}) + } + }, [ax, code]) + + useEffect(() => { + if (!previewError || reportedPreviewError.current === previewError) return + reportedPreviewError.current = previewError + ax.metric('groupInvite:failure', { + errorName: groupInviteFailureName(previewError), + }) + }, [ax, previewError]) + + const openSelectedFeed = useCallback(() => { + if (!acceptance) return + const feed = getFirstSelectedGroupInviteFeed( + acceptance.feeds, + new Set(selectedFeedUris), + ) + if (!feed?.uri) return + maybeFailGroupInviteE2E('navigation') + setSelectedFeed(`feedgen|${feed.uri}`) + groupInviteDialogControl.close() + navigation.navigate('HomeTab') + }, [ + acceptance, + groupInviteDialogControl, + navigation, + selectedFeedUris, + setSelectedFeed, + ]) + + const pinAndOpen = useCallback(async () => { + if (!acceptance || isPinning || !preferencesReady) return + const selectedUris = new Set(selectedFeedUris) + const {readable} = summarizeGroupInviteFeeds(acceptance.feeds) + const selectedReadable = readable.filter( + feed => feed.uri && selectedUris.has(feed.uri), + ) + if (selectedReadable.length === 0) return + + setIsPinning(true) + try { + const {toAdd, toUpdate} = getGroupInviteFeedMutations( + acceptance.feeds, + savedFeeds, + selectedUris, + ) + if (toUpdate.length) { + maybeFailGroupInviteE2E('saved-feed-update') + await updateSavedFeeds(toUpdate) + } + if (toAdd.length) { + maybeFailGroupInviteE2E('saved-feed-add') + await addSavedFeeds(toAdd) + } + setHasPinned(true) + setPinError(undefined) + if ( + shouldOpenGroupInviteFeedAfterPinning(acceptance.feeds, selectedUris) + ) { + openSelectedFeed() + } + } catch (error) { + setPinError( + isGroupInviteE2EFailure(error, 'navigation') ? 'navigation' : 'pinning', + ) + ax.metric('groupInvite:failure', { + errorName: isGroupInviteE2EFailure(error, 'navigation') + ? 'NavigationFailed' + : 'PinningFailed', + }) + logger.error('Failed to complete group invite feed setup', { + errorName: isGroupInviteE2EFailure(error, 'navigation') + ? 'NavigationFailed' + : 'PinningFailed', + }) + } finally { + setIsPinning(false) + } + }, [ + acceptance, + addSavedFeeds, + ax, + openSelectedFeed, + isPinning, + selectedFeedUris, + updateSavedFeeds, + savedFeeds, + preferencesReady, + ]) + + const reauthenticate = useCallback(() => { + if (!code) return + setActiveLanding({type: 'groupinvite', uri: '', code}) + groupInviteDialogControl.close() + logoutCurrentAccount('GroupInvite') + requestSwitchToAccount({requestedAccount: 'groupinvite'}) + }, [ + code, + groupInviteDialogControl, + logoutCurrentAccount, + requestSwitchToAccount, + setActiveLanding, + ]) + + const onAccept = async () => { + if (!code || !preview || acceptingRef.current || isAcceptPending) return + acceptingRef.current = true + resetAccept() + setPinError(undefined) + setHasPinned(false) + try { + ax.metric('groupInvite:acceptAttempted', {}) + const result = await acceptInvite({ + code, + communityDid: preview.community.did, + }) + setAcceptance(result) + setSelectedFeedUris(getDefaultGroupInviteFeedUris(result.feeds)) + ax.metric('groupInvite:joined', { + hasPosting: result.feeds.some(feed => feed.canView && feed.canPost), + }) + } catch (error) { + ax.metric('groupInvite:failure', { + errorName: groupInviteFailureName(error), + }) + logger.info('Group invite acceptance failed', { + errorName: groupInviteFailureName(error), + }) + } finally { + acceptingRef.current = false + } + } + + const error = previewError || acceptError + const isPending = isPreviewPending || isAcceptPending + const onSelectedFeedUrisChange = useCallback( + (nextUris: string[]) => { + if ( + hasPinned && + shouldResetGroupInvitePinning(selectedFeedUris, nextUris) + ) { + setHasPinned(false) + setPinError(undefined) + } + setSelectedFeedUris(nextUris) + }, + [hasPinned, selectedFeedUris], + ) + + return ( + + + {isPending && !preview ? ( + + ) : error ? ( + { + if (previewError) void refetchPreview() + else if ( + acceptError instanceof GroupInviteClientError && + acceptError.code === GroupInviteError.AuthenticationRequired + ) + reauthenticate() + else void onAccept() + }} + /> + ) : preview ? ( + <> + + + Group invite + + + {preview.group.displayName} + + + {preview.community.name} + + + {acceptance ? ( + void preferencesQuery.refetch()} + onPinAndOpen={() => void pinAndOpen()} + onOpenFeed={() => { + try { + openSelectedFeed() + } catch { + setPinError('navigation') + ax.metric('groupInvite:failure', { + errorName: 'NavigationFailed', + }) + } + }} + /> + ) : ( + + )} + + ) : null} + + + ) +} + +function AcceptedState({ + acceptance, + pinError, + hasPinned, + isPinning, + selectedFeedUris, + onSelectedFeedUrisChange, + preferencesPending, + preferencesError, + onRetryPreferences, + onPinAndOpen, + onOpenFeed, +}: { + acceptance: GroupInviteAcceptance + pinError: 'pinning' | 'navigation' | undefined + hasPinned: boolean + isPinning: boolean + selectedFeedUris: string[] + onSelectedFeedUrisChange: (uris: string[]) => void + preferencesPending: boolean + preferencesError: boolean + onRetryPreferences: () => void + onPinAndOpen: () => void + onOpenFeed: () => void +}) { + const {t: l} = useLingui() + const readable = acceptance.feeds.filter(feed => feed.canView) + const membershipCopy = getGroupInviteMembershipCopy(acceptance.feeds) + const hasSelectedReadable = readable.some( + feed => feed.uri && selectedFeedUris.includes(feed.uri), + ) + return ( + + + You joined {acceptance.groupName}. + + {readable.length > 0 ? ( + + {readable.map((feed, index) => { + const capability = feed.canPost ? 'Post + read' : 'Read only' + const label = `${feed.name} — ${capability}` + return ( + + + {label} + + ) + })} + + ) : null} + {membershipCopy && ( + + {membershipCopy} + + )} + {preferencesPending && ( + + Loading your saved feeds… + + )} + {preferencesError && ( + + )} + {readable.length === 0 && ( + + {getGroupInviteNoPostCopy()} + + )} + {readable.length > 0 && !hasPinned && ( + + )} + {pinError === 'pinning' && ( + + )} + {pinError === 'navigation' && ( + + )} + {hasPinned && hasSelectedReadable && ( + + )} + + ) +} + +function InviteErrorState({ + message, + onRetry, + retryLabel, + testID, + retryTestID, +}: { + message: string + onRetry: () => void + retryLabel?: string + testID?: string + retryTestID?: string +}) { + const {t: l} = useLingui() + return ( + + {message} + + + ) +} diff --git a/src/components/intents/IntentDialogs.tsx b/src/components/intents/IntentDialogs.tsx index 76809b366..9a712272c 100644 --- a/src/components/intents/IntentDialogs.tsx +++ b/src/components/intents/IntentDialogs.tsx @@ -7,15 +7,18 @@ import { useState, } from 'react' +import {usePrefetchGroupInvitePreview} from '#/state/queries/group-invites' import {usePrefetchJoinLinkPreviews} from '#/state/queries/join-links' import {useSession} from '#/state/session' import { useActiveGroupChatJoinRequest, + useActiveGroupInvite, useSetActiveLanding, } from '#/state/shell/landing' import * as Dialog from '#/components/Dialog' import {type DialogControlProps} from '#/components/Dialog' import {GroupChatJoinDialog} from '#/components/intents/GroupChatJoinDialog' +import {GroupInviteDialog} from '#/components/intents/GroupInviteDialog' import {VerifyEmailIntentDialog} from '#/components/intents/VerifyEmailIntentDialog' interface Context { @@ -25,6 +28,9 @@ interface Context { groupChatJoinDialogControl: DialogControlProps groupChatJoinState: {code: string} | undefined setGroupChatJoinState: (state: {code: string} | undefined) => void + groupInviteDialogControl: DialogControlProps + groupInviteState: {code: string} | undefined + setGroupInviteState: (state: {code: string} | undefined) => void } const Context = createContext({} as Context) @@ -40,12 +46,19 @@ export function Provider({children}: {children: React.ReactNode}) { const [groupChatJoinState, setGroupChatJoinState] = useState< {code: string} | undefined >() + const groupInviteDialogControl = Dialog.useDialogControl() + const [groupInviteState, setGroupInviteState] = useState< + {code: string} | undefined + >() const {hasSession} = useSession() const groupChatLanding = useActiveGroupChatJoinRequest() + const groupInviteLanding = useActiveGroupInvite() const setActiveLanding = useSetActiveLanding() const prefetchJoinLinkPreviews = usePrefetchJoinLinkPreviews() + const prefetchGroupInvitePreview = usePrefetchGroupInvitePreview() const landingHandledRef = useRef(false) + const groupInviteLandingHandledRef = useRef(false) useEffect(() => { if (hasSession && groupChatLanding && !landingHandledRef.current) { @@ -67,6 +80,26 @@ export function Provider({children}: {children: React.ReactNode}) { if (!groupChatLanding) { landingHandledRef.current = false } + if ( + hasSession && + groupInviteLanding && + !groupInviteLandingHandledRef.current + ) { + groupInviteLandingHandledRef.current = true + const code = groupInviteLanding.code + setActiveLanding(undefined) + const prefetch = prefetchGroupInvitePreview(code) + void Promise.race([ + prefetch, + new Promise(res => setTimeout(res, 200)), + ]).finally(() => { + setGroupInviteState({code}) + groupInviteDialogControl.open() + }) + } + if (!groupInviteLanding) { + groupInviteLandingHandledRef.current = false + } }, [ hasSession, groupChatLanding, @@ -74,6 +107,10 @@ export function Provider({children}: {children: React.ReactNode}) { setGroupChatJoinState, prefetchJoinLinkPreviews, groupChatJoinDialogControl, + groupInviteLanding, + prefetchGroupInvitePreview, + groupInviteDialogControl, + setGroupInviteState, ]) const value = useMemo( @@ -84,6 +121,9 @@ export function Provider({children}: {children: React.ReactNode}) { groupChatJoinDialogControl, groupChatJoinState, setGroupChatJoinState, + groupInviteDialogControl, + groupInviteState, + setGroupInviteState, }), [ verifyEmailDialogControl, @@ -92,6 +132,9 @@ export function Provider({children}: {children: React.ReactNode}) { groupChatJoinDialogControl, groupChatJoinState, setGroupChatJoinState, + groupInviteDialogControl, + groupInviteState, + setGroupInviteState, ], ) @@ -100,6 +143,7 @@ export function Provider({children}: {children: React.ReactNode}) { {children} + ) } diff --git a/src/env/common.ts b/src/env/common.ts index 0318842f0..5a79e68eb 100644 --- a/src/env/common.ts +++ b/src/env/common.ts @@ -17,6 +17,7 @@ export const ENV: string = process.env.EXPO_PUBLIC_ENV as | 'production' | 'testflight' | 'development' + | 'staging' | 'e2e' | (string & {}) @@ -153,6 +154,21 @@ export const BRAND_SERVICE_URL: string = process.env.EXPO_PUBLIC_BRAND_SERVICE_URL || 'https://brand.acorn.blacksky.community' +/** Acorn Web endpoint for community invitation previews and acceptance. */ +export const ACORN_SERVICE_URL: string = + process.env.EXPO_PUBLIC_ACORN_SERVICE_URL || + (ENV === 'production' || ENV === 'testflight' + ? 'https://acorn.blacksky.community' + : ENV === 'e2e' + ? 'http://localhost:1986' + : ENV === 'staging' + ? (() => { + throw new Error( + 'EXPO_PUBLIC_ACORN_SERVICE_URL is required for staging builds', + ) + })() + : 'http://localhost:3000') + /** * Stripe publishable key for embedded checkout */ diff --git a/src/lib/api/__tests__/community-feed.test.ts b/src/lib/api/__tests__/community-feed.test.ts new file mode 100644 index 000000000..55380c4bb --- /dev/null +++ b/src/lib/api/__tests__/community-feed.test.ts @@ -0,0 +1,175 @@ +import {type AtpAgent, XRPCError} from '@atproto/api' + +import { + ADMIT_FEED_POST, + admitFeedPost, + CHECK_FEED_PERMISSIONS, + fetchCommunityFeedConfig, + fetchCommunityFeedConfigStrict, + fetchCommunityFeedTarget, + fetchFeedPermissions, + fetchFeedServiceDid, +} from '../community-feed' +import {getServiceAuthToken} from '../service-auth' + +jest.mock('../service-auth', () => ({ + getServiceAuthToken: jest.fn(), +})) + +const feed = 'at://did:plc:community/app.bsky.feed.generator/3m2communityfeed' +const serviceDid = 'did:web:feeds.example.com' +const config = { + $type: 'community.blacksky.feed.config', + contentType: 'publicRecord', + visibility: 'public', + policyMode: 'public', + group: 'at://did:plc:community/community.blacksky.group/community', + createdAt: '2026-08-06T12:00:00.000Z', +} as const + +function mockAgent() { + const getRecord = jest.fn(({collection}: {collection: string}) => { + if (collection === 'community.blacksky.feed.config') { + return Promise.resolve({data: {value: config}}) + } + return Promise.resolve({ + data: {value: {$type: collection, did: serviceDid}}, + }) + }) + const fetchHandler = jest.fn, [string, RequestInit?]>() + return { + agent: { + com: {atproto: {repo: {getRecord}}}, + fetchHandler, + } as unknown as AtpAgent, + fetchHandler, + getRecord, + } +} + +describe('community feed API', () => { + beforeEach(() => { + jest.mocked(getServiceAuthToken).mockReset() + jest.mocked(getServiceAuthToken).mockResolvedValue('service-token') + }) + + it('loads config and generator records from the feed owner at the same rkey', async () => { + const {agent, getRecord} = mockAgent() + + await expect(fetchCommunityFeedConfig(agent, feed)).resolves.toEqual(config) + await expect(fetchFeedServiceDid(agent, feed)).resolves.toBe(serviceDid) + + expect(getRecord).toHaveBeenNthCalledWith(1, { + repo: 'did:plc:community', + collection: 'community.blacksky.feed.config', + rkey: '3m2communityfeed', + }) + expect(getRecord).toHaveBeenNthCalledWith(2, { + repo: 'did:plc:community', + collection: 'app.bsky.feed.generator', + rkey: '3m2communityfeed', + }) + }) + + it('distinguishes an absent config from a failed config read', async () => { + const {agent, getRecord} = mockAgent() + getRecord.mockRejectedValueOnce(new XRPCError(400, 'RecordNotFound')) + + await expect( + fetchCommunityFeedConfigStrict(agent, feed), + ).resolves.toBeNull() + + getRecord.mockRejectedValueOnce(new XRPCError(503, 'UpstreamFailure')) + await expect(fetchCommunityFeedConfigStrict(agent, feed)).rejects.toThrow( + 'UpstreamFailure', + ) + }) + + it('checks self-scoped permissions with exact service auth and filters unknown values', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + permissions: ['canView', 'futurePermission', 'canPost'], + }), + ), + ) + + await expect(fetchFeedPermissions(agent, feed)).resolves.toEqual([ + 'canView', + 'canPost', + ]) + expect(getServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ + agent, + aud: serviceDid, + lxm: CHECK_FEED_PERMISSIONS, + }), + ) + expect(fetchHandler).toHaveBeenCalledWith( + `/xrpc/${CHECK_FEED_PERMISSIONS}?feed=${encodeURIComponent(feed)}`, + { + headers: { + Authorization: 'Bearer service-token', + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + }, + ) + }) + + it('fails closed when the permission service rejects the request', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response('{}', {status: 403})) + + await expect(fetchFeedPermissions(agent, feed)).resolves.toEqual([]) + }) + + it('resolves a post target only when the user can post', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({permissions: ['canView', 'canPost']})), + ) + + await expect(fetchCommunityFeedTarget(agent, feed)).resolves.toEqual({ + feed, + name: feed, + serviceDid, + config, + }) + }) + + it('fails closed when resolving a post target without canPost', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({permissions: ['canView']})), + ) + + await expect(fetchCommunityFeedTarget(agent, feed)).resolves.toBeNull() + }) + + it('admits a canonical record through the feed generator service', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response('{}')) + const post = 'at://did:plc:author/app.bsky.feed.post/3m2post' + + await admitFeedPost( + agent, + {feed, name: 'Community', serviceDid, config}, + post, + 'bafyrecordcid', + ) + + expect(getServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({agent, aud: serviceDid, lxm: ADMIT_FEED_POST}), + ) + expect(fetchHandler).toHaveBeenCalledWith(`/xrpc/${ADMIT_FEED_POST}`, { + method: 'POST', + headers: { + Authorization: 'Bearer service-token', + 'Content-Type': 'application/json', + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + body: JSON.stringify({feed, post, cid: 'bafyrecordcid'}), + }) + }) +}) diff --git a/src/lib/api/__tests__/community-post-uri.test.ts b/src/lib/api/__tests__/community-post-uri.test.ts new file mode 100644 index 000000000..1b1176e78 --- /dev/null +++ b/src/lib/api/__tests__/community-post-uri.test.ts @@ -0,0 +1,20 @@ +import {isCommunityPostUri} from '../community-post' + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +describe(isCommunityPostUri, () => { + it.each([ + ['a stub post', 'at://did:plc:alice/community.blacksky.feed.post/3kabc'], + ['a space post', `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc`], + ['a space like', `${SPACE}/did:plc:alice/app.bsky.feed.like/3klike`], + ])('treats %s as community content', (_name, uri) => { + expect(isCommunityPostUri(uri)).toBe(true) + }) + + it.each([undefined, 'at://did:plc:alice/app.bsky.feed.post/3kabc', SPACE])( + 'leaves public content alone: %p', + uri => { + expect(isCommunityPostUri(uri)).toBe(false) + }, + ) +}) diff --git a/src/lib/api/__tests__/community-post.test.ts b/src/lib/api/__tests__/community-post.test.ts new file mode 100644 index 000000000..775949210 --- /dev/null +++ b/src/lib/api/__tests__/community-post.test.ts @@ -0,0 +1,29 @@ +import {getCommunitySpaceUri} from '../community-post' + +const post = (communitySpace?: unknown) => + ({ + uri: 'at://did:plc:author/community.blacksky.feed.post/3m2post', + communitySpace, + }) as never + +describe(getCommunitySpaceUri, () => { + it('accepts a space URI', () => { + const space = 'at://did:plc:community/space/community.blacksky.feed/private' + + expect(getCommunitySpaceUri(post(space))).toBe(space) + }) + + it.each([ + undefined, + 42, + 'not-an-at-uri', + // A feed generator URI is not a space: the field names where content + // lives, and a feed is only a view over it. + 'at://did:plc:community/app.bsky.feed.generator/3m2communityfeed', + 'at://did:plc:community/community.blacksky.feed.config/3m2communityfeed', + // A record inside a space is not the space itself. + 'at://did:plc:c/space/community.blacksky.feed/main/did:plc:a/app.bsky.feed.post/3k', + ])('rejects absent or invalid space context: %p', communitySpace => { + expect(getCommunitySpaceUri(post(communitySpace))).toBeUndefined() + }) +}) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index 28b2539f1..3ab2c7e8c 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -1,11 +1,23 @@ import {type BskyAgent} from '@atproto/api' +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) + import { BLUESKY_FALLBACK_PROXY_HEADER, BLUESKY_PROXY_HEADER, HOME_PROXY_HEADER, } from '#/lib/constants' -import {communityXrpc} from '../community' +import { + communityXrpc, + getSpacePostLikes, + getSpacePostQuotes, +} from '../community' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kpost` describe('communityXrpc', () => { const originalHeader = BLUESKY_PROXY_HEADER.get() @@ -34,4 +46,89 @@ describe('communityXrpc', () => { BLUESKY_FALLBACK_PROXY_HEADER, ) }) + + it('can target a configured content store', async () => { + const {agent, fetchHandler} = mockAgent() + + await communityXrpc(agent, 'community.blacksky.feed.submitPost', { + body: {text: 'hello'}, + serviceDid: 'did:web:content.example.com', + }) + + const init = fetchHandler.mock.calls[0][1] as { + headers: Record + } + expect(init.headers['atproto-proxy']).toBe( + 'did:web:content.example.com#bsky_appview', + ) + }) + + it('fetches space likes through the permission-aware endpoint', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + uri: SPACE_POST, + cursor: 'next', + likes: [ + { + indexedAt: '2026-08-27T12:00:00.000Z', + createdAt: '2026-08-27T11:00:00.000Z', + actor: {did: 'did:plc:bob', handle: 'bob.test'}, + }, + ], + }), + ), + ) + + const page = await getSpacePostLikes(agent, { + uri: SPACE_POST, + limit: 30, + cursor: 'before', + }) + + expect(page.cursor).toBe('next') + expect(page.likes[0].actor.did).toBe('did:plc:bob') + expect(fetchHandler).toHaveBeenCalledWith( + expect.stringContaining( + '/xrpc/community.blacksky.feed.getSpacePostLikes?', + ), + expect.objectContaining({method: 'GET'}), + ) + const url = new URL(fetchHandler.mock.calls[0][0], 'https://example.test') + expect(Object.fromEntries(url.searchParams)).toEqual({ + uri: SPACE_POST, + limit: '30', + cursor: 'before', + }) + }) + + it('converts custom space quote views into standard renderer views', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + cursor: 'next', + posts: [ + { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: `${SPACE}/did:plc:bob/app.bsky.feed.post/3kquote`, + cid: 'bafyquote', + author: {did: 'did:plc:bob', handle: 'bob.test'}, + record: {$type: 'app.bsky.feed.post', text: 'quote'}, + indexedAt: '2026-08-27T12:00:00.000Z', + }, + ], + }), + ), + ) + + const page = await getSpacePostQuotes(agent, { + uri: SPACE_POST, + limit: 30, + }) + + expect(page.uri).toBe(SPACE_POST) + expect(page.posts[0].$type).toBe('app.bsky.feed.defs#postView') + }) }) diff --git a/src/lib/api/__tests__/group-invite-fixture.test.ts b/src/lib/api/__tests__/group-invite-fixture.test.ts new file mode 100644 index 000000000..2e235e43e --- /dev/null +++ b/src/lib/api/__tests__/group-invite-fixture.test.ts @@ -0,0 +1,132 @@ +import {describe, expect, it} from '@jest/globals' + +import { + GROUP_INVITE_FIXTURE_CODES, + GroupInviteFixture, +} from '../../../../dev-env/group-invite-fixture' + +const COMMUNITY = 'did:plc:e2e-community' +const FEEDS = [ + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/read', + name: 'Read only feed', + canView: true, + canPost: false, + }, + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/post', + name: 'Postable feed', + canView: true, + canPost: true, + }, + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/hidden', + name: 'Inaccessible feed', + canView: false, + canPost: false, + }, +] + +function fixture( + scenario: ConstructorParameters[0] = 'mixed', +) { + const value = new GroupInviteFixture(scenario) + value.configure({scenario, communityDid: COMMUNITY, feeds: FEEDS}) + return value +} + +function bearerFor(did: string) { + return `Bearer ${did}` +} + +describe('group invite E2E fixture contract', () => { + it('returns the public preview envelope without invite material', () => { + const value = fixture() + const result = value.preview(value.inviteCode) + + expect(result).toMatchObject({status: 200}) + expect(result.body).toMatchObject({ + result: { + data: { + json: { + community: {did: COMMUNITY, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + }, + }, + }, + }) + expect(JSON.stringify(result.body)).not.toContain(value.inviteCode) + }) + + it('requires Bearer auth and makes claims resumable for one DID only', () => { + const value = fixture('resumable') + const code = GROUP_INVITE_FIXTURE_CODES.resumable + + expect(value.accept({code}).status).toBe(401) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }), + ).toMatchObject({status: 200}) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }), + ).toMatchObject({status: 200}) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:bob'), + memberDid: 'did:plc:bob', + }), + ).toMatchObject({status: 400}) + + expect(value.getState()).toMatchObject({ + acceptRequests: 4, + acceptRequestsWithBearer: 3, + claimCount: 1, + claimantCount: 1, + }) + }) + + it('preserves adversarial feed order while omitting inaccessible feeds', () => { + const value = fixture() + const result = value.accept({ + code: value.inviteCode, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }) + const feeds = (result.body.result as {data: {json: {feeds: unknown[]}}}) + .data.json.feeds as Array<{name: string}> + + expect(feeds.map(feed => feed.name)).toEqual([ + 'Read only feed', + 'Postable feed', + ]) + expect(value.getState()).toMatchObject({ + visibleFeedCount: 2, + inaccessibleFeedCount: 1, + }) + }) + + it('retains membership when capability lookup fails and recovers on same-DID retry', () => { + const value = fixture('capability-outage') + const request = { + code: value.inviteCode, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + } + + expect(value.accept(request).status).toBe(503) + expect(value.accept(request).status).toBe(200) + expect(value.getState()).toMatchObject({ + claimCount: 1, + grantCompleted: true, + acceptRequestsWithBearer: 2, + }) + }) +}) diff --git a/src/lib/api/__tests__/group-invite-ui.test.ts b/src/lib/api/__tests__/group-invite-ui.test.ts new file mode 100644 index 000000000..ab0d66426 --- /dev/null +++ b/src/lib/api/__tests__/group-invite-ui.test.ts @@ -0,0 +1,200 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getDefaultGroupInviteFeedUris, + getFirstSelectedGroupInviteFeed, + getGroupInviteFeedMutations, + getGroupInviteMembershipCopy, + getGroupInviteNoPostCopy, + groupInviteErrorCopy, + groupInviteFailureName, + shouldOpenGroupInviteFeedAfterPinning, + shouldResetGroupInvitePinning, + shouldTrackGroupInviteOpened, + summarizeGroupInviteFeeds, +} from '../group-invite-ui' +import {GroupInviteClientError, GroupInviteError} from '../group-invites' + +describe('group invite UI state', () => { + it('uses friendly stable copy for backend failures', () => { + expect( + groupInviteErrorCopy( + new GroupInviteClientError(GroupInviteError.InviteUnavailable), + ), + ).toBe('This invite is no longer available.') + expect(groupInviteErrorCopy(new Error('database password'))).not.toContain( + 'database password', + ) + }) + + it('separates readable postable and read-only feeds', () => { + const result = summarizeGroupInviteFeeds([ + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + {uri: 'at://feed/hidden', name: 'Hidden', canView: false, canPost: false}, + ]) + expect(result.postable.map(feed => feed.uri)).toEqual(['at://feed/post']) + expect(result.readOnly.map(feed => feed.uri)).toEqual(['at://feed/read']) + expect(result.readable).not.toContainEqual( + expect.objectContaining({uri: 'at://feed/hidden'}), + ) + }) + + it('pins missing and previously saved-but-unpinned feeds without duplicating pinned feeds', () => { + const result = getGroupInviteFeedMutations( + [ + { + uri: 'at://feed/missing', + name: 'Missing', + canView: true, + canPost: true, + }, + {uri: 'at://feed/pinned', name: 'Pinned', canView: true, canPost: true}, + { + uri: 'at://feed/unpinned', + name: 'Unpinned', + canView: true, + canPost: false, + }, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ], + [ + {id: '1', type: 'feed', value: 'at://feed/pinned', pinned: true}, + {id: '2', type: 'feed', value: 'at://feed/unpinned', pinned: false}, + ], + ) + expect(result.toAdd).toEqual([ + {type: 'feed', value: 'at://feed/missing', pinned: true}, + ]) + expect(result.toUpdate).toEqual([ + {id: '2', type: 'feed', value: 'at://feed/unpinned', pinned: true}, + ]) + }) + + it('defaults selection to accessible feeds and never includes hidden feeds', () => { + expect( + getDefaultGroupInviteFeedUris([ + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ]), + ).toEqual(['at://feed/post', 'at://feed/read']) + }) + + it('selects the first postable feed before an earlier readable fallback', () => { + const feeds = [ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + ] + expect( + getFirstSelectedGroupInviteFeed( + feeds, + new Set(['at://feed/read', 'at://feed/post']), + )?.uri, + ).toBe('at://feed/post') + expect( + getFirstSelectedGroupInviteFeed(feeds, new Set(['at://feed/read']))?.uri, + ).toBe('at://feed/read') + }) + + it('opens a selected read-only feed after pinning when no postable feed is selected', () => { + expect( + shouldOpenGroupInviteFeedAfterPinning( + [ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: false, + }, + ], + new Set(['at://feed/read']), + ), + ).toBe(true) + }) + + it('pins only selected accessible feeds', () => { + const result = getGroupInviteFeedMutations( + [ + { + uri: 'at://feed/selected', + name: 'Selected', + canView: true, + canPost: true, + }, + {uri: 'at://feed/other', name: 'Other', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ], + [], + new Set(['at://feed/selected']), + ) + expect(result.toAdd).toEqual([ + {type: 'feed', value: 'at://feed/selected', pinned: true}, + ]) + }) + + it('uses the required membership copy for no-post and no-readable outcomes', () => { + expect( + getGroupInviteMembershipCopy([ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + ]), + ).toBe( + "You joined the group, but you don't currently have access to a feed you can post in. Please let your admins know if you think this is a mistake.", + ) + expect( + getGroupInviteMembershipCopy([ + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: false, + }, + ]), + ).toBe('No feeds available.') + expect(getGroupInviteNoPostCopy()).toContain( + 'Please let your admins know if you think this is a mistake.', + ) + }) + + it('invalidates completed pinning when feed selection changes', () => { + expect( + shouldResetGroupInvitePinning(['at://feed/one'], ['at://feed/one']), + ).toBe(false) + expect( + shouldResetGroupInvitePinning(['at://feed/one'], ['at://feed/two']), + ).toBe(true) + }) + + it('returns only stable failure names for analytics', () => { + expect( + groupInviteFailureName( + new GroupInviteClientError(GroupInviteError.InviteMisconfigured), + ), + ).toBe('InviteMisconfigured') + expect(groupInviteFailureName(new Error('invite-code-secret'))).toBe( + 'Unknown', + ) + }) + + it('deduplicates opened analytics for the same invite', () => { + const code = `analytics-${Date.now()}-${Math.random()}` + expect(shouldTrackGroupInviteOpened(code)).toBe(true) + expect(shouldTrackGroupInviteOpened(code)).toBe(false) + }) +}) diff --git a/src/lib/api/__tests__/group-invites.test.ts b/src/lib/api/__tests__/group-invites.test.ts new file mode 100644 index 000000000..6e9ebfcde --- /dev/null +++ b/src/lib/api/__tests__/group-invites.test.ts @@ -0,0 +1,183 @@ +import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals' + +import { + acceptGroupInvite, + GroupInviteError, + previewGroupInvite, +} from '../group-invites' +import {getServiceAuthToken} from '../service-auth' + +jest.mock('../service-auth', () => ({ + getServiceAuthToken: jest.fn(), +})) + +const mockGetServiceAuthToken = jest.mocked(getServiceAuthToken) +const fetchMock = jest.fn() +const CODE = 'a'.repeat(43) +const COMMUNITY_DID = 'did:plc:community' + +function response(body: unknown, ok = true, status = 200) { + return {ok, status, json: () => Promise.resolve(body)} as Response +} + +describe('group invite client API', () => { + beforeEach(() => { + global.fetch = fetchMock + fetchMock.mockReset() + mockGetServiceAuthToken.mockReset() + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('previews through the public Acorn tRPC query', async () => { + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: { + community: {did: COMMUNITY_DID, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + expiresAt: new Date().toISOString(), + }, + }, + }, + }), + ) + + await expect(previewGroupInvite(CODE)).resolves.toEqual({ + community: {did: COMMUNITY_DID, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + expiresAt: expect.any(String), + }) + expect(fetchMock).toHaveBeenCalledWith( + expect.not.stringContaining('?input='), + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({code: CODE}), + }), + ) + }) + + it('requests method-bound service auth for the invite community and sends it', async () => { + mockGetServiceAuthToken.mockResolvedValue('service-token') + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: { + communityDid: COMMUNITY_DID, + groupName: 'members', + membership: 'joined', + feeds: [ + { + uri: 'at://feed/one', + name: 'One', + canView: true, + canPost: false, + }, + ], + }, + }, + }, + }), + ) + const agent = {} as Parameters[0]['agent'] + + await expect( + acceptGroupInvite({code: CODE, communityDid: COMMUNITY_DID, agent}), + ).resolves.toMatchObject({membership: 'joined'}) + expect(mockGetServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ + agent, + aud: COMMUNITY_DID, + lxm: 'community.blacksky.group.acceptInvite', + }), + ) + expect(fetchMock.mock.calls[0][1]).toEqual( + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ + Authorization: 'Bearer service-token', + }), + }), + ) + }) + + it('turns an expired-session service-auth response into reauthentication', async () => { + mockGetServiceAuthToken.mockRejectedValue({status: 401}) + + await expect( + acceptGroupInvite({ + code: CODE, + communityDid: COMMUNITY_DID, + agent: {} as Parameters[0]['agent'], + }), + ).rejects.toMatchObject({code: GroupInviteError.AuthenticationRequired}) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('normalizes stable Acorn errors without exposing raw server messages', async () => { + fetchMock.mockResolvedValue( + response( + { + error: { + json: { + data: {code: 'INVITE_UNAVAILABLE'}, + message: 'internal row details', + }, + }, + }, + false, + 410, + ), + ) + + await expect(previewGroupInvite(CODE)).rejects.toMatchObject({ + code: GroupInviteError.InviteUnavailable, + }) + }) + + it('prefers Acorn stable messages over generic tRPC transport codes', async () => { + fetchMock.mockResolvedValue( + response( + { + error: { + json: { + message: 'InviteMisconfigured', + data: {code: 'INTERNAL_SERVER_ERROR'}, + }, + }, + }, + false, + 500, + ), + ) + + await expect(previewGroupInvite(CODE)).rejects.toMatchObject({ + code: 'InviteMisconfigured', + }) + }) + + it('rejects a malformed successful acceptance payload as unavailable', async () => { + mockGetServiceAuthToken.mockResolvedValue('service-token') + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: {membership: 'joined', feeds: 'not-an-array'}, + }, + }, + }), + ) + + await expect( + acceptGroupInvite({ + code: CODE, + communityDid: COMMUNITY_DID, + agent: {} as Parameters[0]['agent'], + }), + ).rejects.toMatchObject({code: GroupInviteError.AuthorizationUnavailable}) + }) +}) diff --git a/src/lib/api/__tests__/post-routing.test.ts b/src/lib/api/__tests__/post-routing.test.ts new file mode 100644 index 000000000..f9af8adac --- /dev/null +++ b/src/lib/api/__tests__/post-routing.test.ts @@ -0,0 +1,258 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {post, quotedSpace, resolveReply} from '../index' +import {postToSpace} from '../space-post' + +// `post()`'s module graph reaches the image picker, which pulls in native UI +// modules that cannot load under jest. Only the write routing is under test. +jest.mock('react-native-uuid', () => ({default: {v4: () => 'test-device-id'}})) +jest.mock('#/state/gallery', () => ({compressImage: jest.fn()})) +jest.mock('#/state/queries/resolve-link', () => ({ + fetchResolveGifQuery: jest.fn(), + fetchResolveLinkQuery: jest.fn(), +})) +jest.mock('#/state/queries/threadgate', () => ({ + createThreadgateRecord: jest.fn(), + threadgateAllowUISettingToAllowRecordValue: jest.fn(() => []), +})) + +jest.mock('../space-post', () => ({ + postToSpace: jest.fn(() => Promise.resolve({uris: ['at://space/post']})), +})) + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +const feedConfig = (space?: string) => ({ + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + group: 'at://did:plc:community/community.blacksky.group/community', + createdAt: '2026-08-09T12:00:00.000Z', + ...(space ? {space} : {}), +}) + +const threadWith = (space?: string) => + ({ + posts: [], + postgate: {}, + threadgate: [], + blackskyOnly: false, + communityFeed: { + feed: 'at://did:plc:community/app.bsky.feed.generator/3m2feed', + name: 'Private', + serviceDid: 'did:web:feeds.example.com', + config: feedConfig(space), + }, + }) as never + +function mockAgent() { + const fetchHandler = jest.fn() + const applyWrites = jest.fn(() => Promise.resolve({})) + return { + agent: { + assertDid: 'did:plc:alice', + fetchHandler, + com: {atproto: {repo: {applyWrites}}}, + } as unknown as AtpAgent, + fetchHandler, + applyWrites, + } +} + +const queryClient = {invalidateQueries: jest.fn()} as unknown as QueryClient + +describe('post routing', () => { + beforeEach(() => jest.clearAllMocks()) + + it('sends a space-backed feed down the space write path', async () => { + const {agent, fetchHandler, applyWrites} = mockAgent() + + await post(agent, queryClient, {thread: threadWith(SPACE)}) + + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread: threadWith(SPACE), + }) + // Nothing may reach the appview or the public repo on this path. + expect(fetchHandler).not.toHaveBeenCalled() + expect(applyWrites).not.toHaveBeenCalled() + }) + + it('leaves a feed without a space on the community path', async () => { + const {agent, applyWrites} = mockAgent() + + await post(agent, queryClient, {thread: threadWith(undefined)}) + + expect(postToSpace).not.toHaveBeenCalled() + expect(applyWrites).toHaveBeenCalled() + }) +}) + +describe('quoting a space post from outside the space', () => { + const SPACE_POST = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kabc` + const permalink = `https://blacksky.community/profile/did:plc:bob/post/3kabc?space=${encodeURIComponent( + SPACE, + )}` + + const threadQuoting = (uri: string, space?: string) => + ({ + ...(threadWith(space) as object), + posts: [ + { + richtext: {text: '', facets: []}, + shortenedGraphemeLength: 0, + labels: [], + embed: {quote: {type: 'link', uri}}, + }, + ], + }) as never + + beforeEach(() => jest.clearAllMocks()) + + // The link form is what the composer actually holds: it is only expanded to + // the at:// form at publish, after routing has already decided. + it.each([ + ['a pasted permalink', permalink], + ['an at:// space record uri', SPACE_POST], + ])( + 'refuses %s rather than writing it to the public repo', + async (_n, uri) => { + const {agent, applyWrites, fetchHandler} = mockAgent() + + await expect( + post(agent, queryClient, {thread: threadQuoting(uri)}), + ).rejects.toThrow(/private post/) + + expect(applyWrites).not.toHaveBeenCalled() + expect(fetchHandler).not.toHaveBeenCalled() + expect(postToSpace).not.toHaveBeenCalled() + }, + ) + + it.each([ + ['opened from the space post', {communitySpaceUri: SPACE}], + ['composing into the space-backed feed', {}], + ])( + 'allows the quote when the post goes into that space (%s)', + async (_n, extra) => { + const {agent} = mockAgent() + + await post(agent, queryClient, { + thread: { + ...(threadQuoting(permalink, SPACE) as object), + ...extra, + } as never, + }) + + expect(postToSpace).toHaveBeenCalled() + }, + ) +}) + +describe('quotedSpace', () => { + const OTHER = 'at://did:plc:community/space/community.blacksky.feed/other' + + it('reads the space out of either form', () => { + expect(quotedSpace(`${SPACE}/did:plc:bob/app.bsky.feed.post/3kabc`)).toBe( + SPACE, + ) + expect( + quotedSpace( + `/profile/did:plc:bob/post/3kabc?space=${encodeURIComponent(OTHER)}`, + ), + ).toBe(OTHER) + }) + + it.each([ + ['a public post', 'at://did:plc:bob/app.bsky.feed.post/3kabc'], + ['a community stub', 'at://did:plc:bob/community.blacksky.feed.post/3kabc'], + ['a bare space uri with no record', SPACE], + ['nothing', undefined], + ])('returns null for %s', (_n, uri) => { + expect(quotedSpace(uri)).toBeNull() + }) +}) + +describe('space replies', () => { + it('passes the reply target down to the space write path', async () => { + const {agent} = mockAgent() + const parent = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kparent` + + await post(agent, queryClient, { + thread: threadWith(SPACE), + replyTo: parent, + }) + + // postToSpace resolves the parent itself; what matters here is that the + // reply is routed into the space at all rather than posted publicly. + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread: threadWith(SPACE), + replyTo: parent, + }) + }) + + it('reconstructs the space target when the reply view omitted it', async () => { + const {agent} = mockAgent() + const parent = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kparent` + const thread = threadWith(undefined) + + await post(agent, queryClient, {thread, replyTo: parent}) + + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread, + replyTo: parent, + }) + }) +}) + +describe('resolveReply public-path guard', () => { + const publicParent = 'at://did:plc:bob/app.bsky.feed.post/3kparent' + const spaceRecord = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kroot` + + const agentReturningRoot = (rootUri: string) => + ({ + app: { + bsky: { + feed: { + getPosts: jest.fn(() => + Promise.resolve({ + data: { + posts: [ + { + uri: publicParent, + cid: 'bafyreiparent', + record: { + $type: 'app.bsky.feed.post', + text: 'hi', + createdAt: '2026-08-09T12:00:00.000Z', + reply: { + root: {uri: rootUri, cid: 'bafyreiroot'}, + parent: {uri: publicParent, cid: 'bafyreiparent'}, + }, + }, + }, + ], + }, + }), + ), + }, + }, + }, + }) as unknown as AtpAgent + + it('refuses to hand a space thread root to the public write path', async () => { + await expect( + resolveReply(agentReturningRoot(spaceRecord), publicParent), + ).rejects.toThrow(/private post/i) + }) + + it('passes an ordinary thread root through', async () => { + const root = 'at://did:plc:bob/app.bsky.feed.post/3kroot' + await expect( + resolveReply(agentReturningRoot(root), publicParent), + ).resolves.toEqual({ + root: {uri: root, cid: 'bafyreiroot'}, + parent: {uri: publicParent, cid: 'bafyreiparent'}, + }) + }) +}) diff --git a/src/lib/api/__tests__/space-permalink.test.ts b/src/lib/api/__tests__/space-permalink.test.ts new file mode 100644 index 000000000..62cc2b4fa --- /dev/null +++ b/src/lib/api/__tests__/space-permalink.test.ts @@ -0,0 +1,138 @@ +import {postPermalink} from '#/lib/routes/links' +import {postUriToRelativePath} from '#/lib/strings/url-helpers' +import { + isSpacePostUrl, + postUriAuthor, + spacePostUriFromRoute, +} from '../space-permalink' + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const AUTHOR = {did: 'did:plc:alice', handle: 'alice.test'} +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc` + +describe('space permalinks', () => { + it('keeps the ordinary post url and attaches the space', () => { + expect(postPermalink(AUTHOR, SPACE_POST)).toBe( + `/profile/did:plc:alice/post/3kabc?space=${encodeURIComponent(SPACE)}`, + ) + }) + + it('carries a suffix segment before the query', () => { + expect(postPermalink(AUTHOR, SPACE_POST, 'liked-by')).toBe( + `/profile/did:plc:alice/post/3kabc/liked-by?space=${encodeURIComponent( + SPACE, + )}`, + ) + }) + + it.each([ + ['a public post', 'at://did:plc:alice/app.bsky.feed.post/3kabc', ''], + [ + 'the community stub', + 'at://did:plc:alice/community.blacksky.feed.post/3kabc', + '?collection=community.blacksky.feed.post', + ], + ])('leaves %s alone', (_name, uri, query) => { + expect(postPermalink(AUTHOR, uri)).toBe( + `/profile/did:plc:alice/post/3kabc${query}`, + ) + }) + + it('round-trips back to the record uri', () => { + expect(spacePostUriFromRoute(SPACE, 'did:plc:alice', '3kabc')).toBe( + SPACE_POST, + ) + }) + + it.each([ + ['no space', undefined, 'did:plc:alice'], + [ + 'a malformed space', + 'at://did:plc:community/space/onlythree', + 'did:plc:alice', + ], + // A handle cannot stand in for the author: the URI form admits only DIDs, + // so the caller has to resolve it first. + ['an unresolved handle', SPACE, 'alice.test'], + ])('refuses %s', (_name, space, author) => { + expect(spacePostUriFromRoute(space, author, '3kabc')).toBeNull() + }) +}) + +describe('post uri authors', () => { + it.each([ + [ + 'a public post', + 'at://did:plc:public/app.bsky.feed.post/3kroot', + 'did:plc:public', + ], + [ + 'a legacy community post', + 'at://did:plc:community/community.blacksky.feed.post/3kroot', + 'did:plc:community', + ], + ['a permissioned-space post', SPACE_POST, AUTHOR.did], + ])('finds the author of %s', (_name, uri, expected) => { + expect(postUriAuthor(uri)).toBe(expected) + }) + + it('does not feed malformed input through as an author', () => { + expect(postUriAuthor('not-an-at-uri')).toBeNull() + }) +}) + +describe('recognising a space link before it is expanded', () => { + const encoded = encodeURIComponent(SPACE) + + it.each([ + [ + 'a full url', + `https://blacksky.community/profile/did:plc:alice/post/3kabc?space=${encoded}`, + ], + ['a relative path', `/profile/did:plc:alice/post/3kabc?space=${encoded}`], + [ + 'a suffix route', + `https://bsky.app/profile/did:plc:alice/post/3kabc/liked-by?space=${encoded}`, + ], + [ + 'an unencoded space param', + `/profile/did:plc:alice/post/3kabc?space=${SPACE}`, + ], + ])('spots %s', (_name, url) => { + expect(isSpacePostUrl(url)).toBe(true) + }) + + it.each([ + ['a public post url', 'https://bsky.app/profile/alice.test/post/3kabc'], + [ + 'a community stub url', + '/profile/did:plc:alice/post/3kabc?collection=community.blacksky.feed.post', + ], + [ + 'a space param that is not a space uri', + '/profile/did:plc:alice/post/3kabc?space=nonsense', + ], + ['nothing', undefined], + ])('ignores %s', (_name, url) => { + expect(isSpacePostUrl(url)).toBe(false) + }) +}) + +describe('space post urls survive the composer round trip', () => { + it('encodes and decodes back to the same record uri', () => { + const path = postUriToRelativePath(SPACE_POST) + expect(path).toBe( + `/profile/did:plc:alice/post/3kabc?space=${encodeURIComponent(SPACE)}`, + ) + // What resolveLink does on the way back: read the parts out of the url. + const url = new URL(path!, 'http://_') + const [, user, , rkey] = url.pathname.split('/').filter(Boolean) + expect( + spacePostUriFromRoute( + url.searchParams.get('space') ?? undefined, + user, + rkey, + ), + ).toBe(SPACE_POST) + }) +}) diff --git a/src/lib/api/__tests__/space-post.test.ts b/src/lib/api/__tests__/space-post.test.ts new file mode 100644 index 000000000..a31b20e23 --- /dev/null +++ b/src/lib/api/__tests__/space-post.test.ts @@ -0,0 +1,124 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {resolveEmbed} from '../index' +import {postToSpace} from '../space-post' +import {spaceCreateRecord} from '../space-write' + +jest.mock('../index', () => ({ + quotedSpace: jest.fn((uri?: string) => + uri?.includes('/space/') ? uri.split('/did:plc:author/')[0] : null, + ), + resolveEmbed: jest.fn(), + resolveReply: jest.fn(), + resolveRT: jest.fn((_agent, richtext) => Promise.resolve(richtext)), +})) + +jest.mock('../space-write', () => ({ + POST_COLLECTION: 'app.bsky.feed.post', + spaceCreateRecord: jest.fn(() => + Promise.resolve({ + uri: 'at://space/post', + cid: 'bafyspace', + }), + ), +})) + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/private' +const OTHER = 'at://did:plc:other/space/community.blacksky.feed/private' +const agent = {} as AtpAgent +const queryClient = {} as QueryClient + +const thread = (embed: object = {}, id = 'draft-operation-1') => + ({ + posts: [ + { + id, + richtext: {text: 'hello', facets: []}, + shortenedGraphemeLength: 5, + labels: [], + embed, + }, + ], + postgate: {}, + threadgate: [], + blackskyOnly: false, + communitySpaceUri: SPACE, + }) as never + +describe(postToSpace, () => { + beforeEach(() => jest.clearAllMocks()) + + it.each(['images', 'gallery', 'video', 'gif'])( + 'blocks %s before embed resolution or a write', + async type => { + await expect( + postToSpace(agent, queryClient, SPACE, { + thread: thread({media: {type}}), + }), + ).rejects.toThrow(/not available in private spaces/i) + + expect(resolveEmbed).not.toHaveBeenCalled() + expect(spaceCreateRecord).not.toHaveBeenCalled() + }, + ) + + it('refuses a quote from another space before embed resolution', async () => { + await expect( + postToSpace(agent, queryClient, SPACE, { + thread: thread({ + quote: { + uri: `${OTHER}/did:plc:author/app.bsky.feed.post/3kquote`, + }, + }), + }), + ).rejects.toThrow(/another space/i) + + expect(resolveEmbed).not.toHaveBeenCalled() + expect(spaceCreateRecord).not.toHaveBeenCalled() + }) + + it('uses the stable protocol-valid draft id as the record key', async () => { + await postToSpace(agent, queryClient, SPACE, {thread: thread()}) + + expect(spaceCreateRecord).toHaveBeenCalledWith( + agent, + SPACE, + 'app.bsky.feed.post', + expect.objectContaining({text: 'hello'}), + 'draft-operation-1', + ) + }) + + it('derives a stable record key from a saved draft id and post index', async () => { + const opts = {thread: thread(), draftId: '3mabcde234567'} + + await postToSpace(agent, queryClient, SPACE, opts) + await postToSpace(agent, queryClient, SPACE, opts) + + expect(spaceCreateRecord).toHaveBeenNthCalledWith( + 1, + agent, + SPACE, + 'app.bsky.feed.post', + expect.any(Object), + '3mabcde234567-0', + ) + expect(spaceCreateRecord).toHaveBeenNthCalledWith( + 2, + agent, + SPACE, + 'app.bsky.feed.post', + expect.any(Object), + '3mabcde234567-0', + ) + }) + + it('rejects an invalid draft id before writing', async () => { + await expect( + postToSpace(agent, queryClient, SPACE, {thread: thread({}, 'bad/id')}), + ).rejects.toThrow(/record key/i) + + expect(spaceCreateRecord).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/api/__tests__/space-write.test.ts b/src/lib/api/__tests__/space-write.test.ts new file mode 100644 index 000000000..2aa5885df --- /dev/null +++ b/src/lib/api/__tests__/space-write.test.ts @@ -0,0 +1,274 @@ +import {type BskyAgent} from '@atproto/api' +import {describe, expect, it} from '@jest/globals' + +import { + LIKE_COLLECTION, + POST_COLLECTION, + spaceCreateRecord, + spaceDeleteIfSpace, + spaceDeleteRecord, + spaceLike, + spaceLikeIfSpace, + spaceUnlike, + spaceUnlikeIfSpace, + SpaceUnsupportedError, +} from '#/lib/api/space-write' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const SUBJECT = { + uri: `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc`, + cid: 'bafyreisubject', +} + +type Call = { + path: string + method?: string + headers: Record + body: string +} +type MockResponse = {status?: number; body?: unknown} + +function agentWith( + response: MockResponse | MockResponse[] = {}, + signedIn = true, +) { + const calls: Call[] = [] + const responses = Array.isArray(response) ? response : [response] + let responseIndex = 0 + const agent = { + ...(signedIn ? {session: {did: 'did:plc:me'}} : {}), + fetchHandler(path: string, init: RequestInit) { + const current = responses[Math.min(responseIndex++, responses.length - 1)] + const status = current.status ?? 200 + calls.push({ + path, + method: init.method, + headers: (init.headers ?? {}) as Record, + body: typeof init.body === 'string' ? init.body : '', + }) + return Promise.resolve({ + ok: status < 400, + status, + json: () => + Promise.resolve( + current.body ?? {uri: 'at://space/record', cid: 'bafyreinew'}, + ), + } as unknown as Response) + }, + } as unknown as BskyAgent + return {agent, calls} +} + +const bodyOf = (call: Call): Record => + JSON.parse(call.body) as Record + +describe('space writes', () => { + it('posts to the account’s own pds without a proxy header', async () => { + const {agent, calls} = agentWith() + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, { + $type: POST_COLLECTION, + text: 'hello', + }) + + expect(calls).toHaveLength(1) + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + // The write belongs to the PDS, not the appview. Proxying it would send + // private content to the wrong service entirely. + expect(calls[0].headers['atproto-proxy']).toBeUndefined() + expect(bodyOf(calls[0])).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + record: {$type: POST_COLLECTION, text: 'hello'}, + rkey: expect.any(String), + }) + }) + + it('uses an explicit stable rkey or generates a protocol key', async () => { + const {agent, calls} = agentWith() + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}, '3kxyz') + expect(bodyOf(calls[0]).rkey).toBe('3kxyz') + + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}) + expect(bodyOf(calls[1]).rkey).toEqual(expect.any(String)) + }) + + it('recovers a same-rkey retry from RecordExists by authoritative readback', async () => { + const record = { + $type: POST_COLLECTION, + text: 'hello', + createdAt: '2026-08-26T12:00:00.000Z', + } + const original = {uri: 'at://space/original', cid: 'bafyreioriginal'} + const {agent, calls} = agentWith([ + {body: original}, + {status: 400, body: {error: 'RecordExists'}}, + {body: {...original, value: record}}, + ]) + + const first = await spaceCreateRecord( + agent, + SPACE, + POST_COLLECTION, + {...record, createdAt: '2026-08-26T12:00:01.000Z'}, + '3mstablekey', + ) + const retry = await spaceCreateRecord( + agent, + SPACE, + POST_COLLECTION, + record, + '3mstablekey', + ) + + expect(retry).toEqual(first) + expect(bodyOf(calls[0]).rkey).toBe('3mstablekey') + expect(bodyOf(calls[1]).rkey).toBe('3mstablekey') + expect(calls[2].method).toBe('GET') + const readback = new URL(calls[2].path, 'https://pds.example') + expect(readback.pathname).toBe('/xrpc/com.atproto.space.getRecord') + expect(Object.fromEntries(readback.searchParams)).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + rkey: '3mstablekey', + }) + }) + + it('writes a like into the permissioned repo, never the public one', async () => { + const {agent, calls} = agentWith() + await spaceLike(agent, SPACE, SUBJECT) + + // The one thing that must never happen: com.atproto.repo.createRecord with + // a space-uri subject, which would publish that the private post exists. + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + expect(calls[0].path).not.toContain('com.atproto.repo') + expect(bodyOf(calls[0])).toMatchObject({ + space: SPACE, + collection: LIKE_COLLECTION, + record: {$type: LIKE_COLLECTION, subject: SUBJECT}, + }) + }) + + it('unlikes by the rkey of the like record', async () => { + const {agent, calls} = agentWith({body: {}}) + await spaceUnlike( + agent, + SPACE, + `${SPACE}/did:plc:me/${LIKE_COLLECTION}/3klike`, + ) + + expect(calls[0].path).toBe('/xrpc/com.atproto.space.deleteRecord') + expect(bodyOf(calls[0])).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: LIKE_COLLECTION, + rkey: '3klike', + }) + }) + + it('deletes one of the caller’s own records', async () => { + const {agent, calls} = agentWith({body: {}}) + await spaceDeleteRecord(agent, SPACE, POST_COLLECTION, '3kpost') + expect(bodyOf(calls[0]).rkey).toBe('3kpost') + expect(bodyOf(calls[0]).repo).toBe('did:plc:me') + }) + + it('fails before issuing a request when the agent is signed out', async () => { + const {agent, calls} = agentWith({}, false) + + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow(/sign in/i) + await expect( + spaceDeleteRecord(agent, SPACE, POST_COLLECTION, '3kpost'), + ).rejects.toThrow(/sign in/i) + expect(calls).toHaveLength(0) + }) + + it('reads a 404 as “this pds has no space support”', async () => { + const {agent} = agentWith({status: 404}) + // A PDS that never heard of the method answers 404 rather than an XRPC + // error; that is how a foreign-PDS account is recognised so the UI can + // offer migration instead of a generic failure. + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toBeInstanceOf(SpaceUnsupportedError) + }) + + it('surfaces the host’s own message on other failures', async () => { + const {agent} = agentWith({ + status: 429, + body: {error: 'RateLimitExceeded', message: 'records quota exceeded'}, + }) + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow('records quota exceeded') + }) + + it('refuses a response that names no record', async () => { + const {agent} = agentWith({body: {cid: 'bafyreinew'}}) + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow(/no record reference/) + }) +}) + +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kabc' +const PUBLIC_LIKE = 'at://did:plc:alice/app.bsky.feed.like/3klike' + +describe('interaction routing', () => { + it('likes a space post into its own space', async () => { + const {agent, calls} = agentWith() + + await spaceLikeIfSpace(agent, SUBJECT.uri, SUBJECT.cid) + + // The leak this prevents: a like in the public repo whose subject is a + // space URI announces that the private post exists. + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + expect(bodyOf(calls[0])).toMatchObject({ + space: SPACE, + collection: LIKE_COLLECTION, + }) + }) + + it('unlikes and deletes within the space the record belongs to', async () => { + const {agent, calls} = agentWith({body: {}}) + + await spaceUnlikeIfSpace( + agent, + `${SPACE}/did:plc:alice/${LIKE_COLLECTION}/3klike`, + ) + await spaceDeleteIfSpace( + agent, + `${SPACE}/did:plc:alice/${POST_COLLECTION}/3kpost`, + ) + + expect(calls.map(bodyOf)).toEqual([ + { + space: SPACE, + repo: 'did:plc:me', + collection: LIKE_COLLECTION, + rkey: '3klike', + }, + { + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + rkey: '3kpost', + }, + ]) + }) + + it.each([ + ['like', (a: BskyAgent) => spaceLikeIfSpace(a, PUBLIC_POST, 'bafy')], + ['unlike', (a: BskyAgent) => spaceUnlikeIfSpace(a, PUBLIC_LIKE)], + ['delete', (a: BskyAgent) => spaceDeleteIfSpace(a, PUBLIC_POST)], + ])('leaves a public %s to the public repo', (_name, run) => { + const {agent, calls} = agentWith() + + // null means "not mine" — the caller falls back to the ordinary agent call. + expect(run(agent)).toBeNull() + expect(calls).toHaveLength(0) + }) +}) diff --git a/src/lib/api/community-feed.ts b/src/lib/api/community-feed.ts new file mode 100644 index 000000000..374a9c55b --- /dev/null +++ b/src/lib/api/community-feed.ts @@ -0,0 +1,264 @@ +import {type AtpAgent, AtUri, XRPCError} from '@atproto/api' + +import {getServiceAuthToken} from '#/lib/api/service-auth' +import {isSpaceUri} from '#/lib/api/space-uri' + +export const COMMUNITY_FEED_CONFIG_COLLECTION = 'community.blacksky.feed.config' +export const CHECK_FEED_PERMISSIONS = 'community.blacksky.feed.checkPermissions' +export const ADMIT_FEED_POST = 'community.blacksky.feed.admitPost' + +export const COMMUNITY_FEED_PERMISSIONS = [ + 'canView', + 'canPost', + 'canRemovePost', + 'canRemoveMember', + 'canConfigure', + 'canModerate', +] as const + +export type CommunityFeedPermission = + (typeof COMMUNITY_FEED_PERMISSIONS)[number] + +export type CommunityFeedConfig = { + $type: 'community.blacksky.feed.config' + contentType: 'publicRecord' | 'communityRecord' + visibility: 'public' | 'gated' + authorization?: { + serviceDid: string + method?: string + } + policyMode?: 'memberList' | 'managingApp' | 'public' + /** + * Present when the feed's content lives in a permissioned space rather than + * in an appview table. A plain string, never `format: at-uri` — a space URI + * is not a valid at-uri. + */ + space?: string + group: string + createdAt: string +} + +/** + * Whether this feed's content lives in a permissioned space. + * + * This is the discriminator, and the only one. `visibility: 'gated'` is an + * invariant the config must satisfy to parse at all, not an input to the + * decision; access itself is always decided by the space authority, never read + * off the record. + */ +export function isSpaceBackedFeed( + config: CommunityFeedConfig | null | undefined, +): config is CommunityFeedConfig & {space: string} { + return !!config?.space && isSpaceUri(config.space) +} + +export type CommunityFeedTarget = { + feed: string + name: string + serviceDid: string + config: CommunityFeedConfig +} + +type CommunityFeedGenerator = { + serviceDid: string + name: string +} + +function parseCommunityFeedConfig(value: unknown): CommunityFeedConfig | null { + if (!value || typeof value !== 'object') return null + const config = value as Record + const authorization = config.authorization as + | Record + | undefined + if ( + config.$type !== COMMUNITY_FEED_CONFIG_COLLECTION || + (config.contentType !== 'publicRecord' && + config.contentType !== 'communityRecord') || + (config.visibility !== 'public' && config.visibility !== 'gated') || + (authorization !== undefined && + typeof authorization.serviceDid !== 'string') || + typeof config.group !== 'string' || + typeof config.createdAt !== 'string' || + (config.space !== undefined && typeof config.space !== 'string') + ) { + return null + } + return config as CommunityFeedConfig +} + +export async function fetchCommunityFeedConfig( + agent: AtpAgent, + feed: string, +): Promise { + try { + return await fetchCommunityFeedConfigStrict(agent, feed) + } catch { + return null + } +} + +/** + * Distinguishes "no config record exists" (null) from a failed read (throws). + * The feed dispatch must not treat a transient config-read failure as "not + * space-backed" and route a private feed down the standard path. + */ +export async function fetchCommunityFeedConfigStrict( + agent: AtpAgent, + feed: string, +): Promise { + let uri: AtUri + try { + uri = new AtUri(feed) + } catch { + return null + } + if (!uri.rkey) return null + try { + const {data} = await agent.com.atproto.repo.getRecord({ + repo: uri.hostname, + collection: COMMUNITY_FEED_CONFIG_COLLECTION, + rkey: uri.rkey, + }) + return parseCommunityFeedConfig(data.value) + } catch (e) { + if (e instanceof XRPCError && e.error === 'RecordNotFound') { + return null + } + throw e + } +} + +async function fetchFeedGenerator( + agent: AtpAgent, + feed: string, +): Promise { + try { + const uri = new AtUri(feed) + if (!uri.rkey) return null + const {data} = await agent.com.atproto.repo.getRecord({ + repo: uri.hostname, + collection: 'app.bsky.feed.generator', + rkey: uri.rkey, + }) + const value = data.value as Record + return typeof value.did === 'string' + ? { + serviceDid: value.did, + name: + typeof value.displayName === 'string' ? value.displayName : feed, + } + : null + } catch { + return null + } +} + +export async function fetchFeedServiceDid( + agent: AtpAgent, + feed: string, +): Promise { + return (await fetchFeedGenerator(agent, feed))?.serviceDid ?? null +} + +function isCommunityFeedPermission( + value: unknown, +): value is CommunityFeedPermission { + return ( + typeof value === 'string' && + COMMUNITY_FEED_PERMISSIONS.includes(value as CommunityFeedPermission) + ) +} + +async function fetchFeedPermissionsFromService( + agent: AtpAgent, + feed: string, + serviceDid: string, +): Promise { + try { + const token = await getServiceAuthToken({ + agent, + aud: serviceDid, + lxm: CHECK_FEED_PERMISSIONS, + exp: Math.floor(Date.now() / 1000) + 60, + }) + const response = await agent.fetchHandler( + `/xrpc/${CHECK_FEED_PERMISSIONS}?${new URLSearchParams({feed})}`, + { + headers: { + Authorization: `Bearer ${token}`, + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + }, + ) + if (!response.ok) return [] + const body = (await response.json()) as {permissions?: unknown} + return Array.isArray(body.permissions) + ? body.permissions.filter(isCommunityFeedPermission) + : [] + } catch { + return [] + } +} + +export async function fetchFeedPermissions( + agent: AtpAgent, + feed: string, +): Promise { + const config = await fetchCommunityFeedConfig(agent, feed) + if (!config) return [] + const serviceDid = await fetchFeedServiceDid(agent, feed) + return serviceDid + ? fetchFeedPermissionsFromService(agent, feed, serviceDid) + : [] +} + +export async function fetchCommunityFeedTarget( + agent: AtpAgent, + feed: string, +): Promise { + const [config, generator] = await Promise.all([ + fetchCommunityFeedConfig(agent, feed), + fetchFeedGenerator(agent, feed), + ]) + if (!config || !generator) return null + const permissions = await fetchFeedPermissionsFromService( + agent, + feed, + generator.serviceDid, + ) + return permissions.includes('canPost') + ? { + feed, + name: generator.name, + serviceDid: generator.serviceDid, + config, + } + : null +} + +export async function admitFeedPost( + agent: AtpAgent, + target: CommunityFeedTarget, + post: string, + cid: string, +): Promise { + const token = await getServiceAuthToken({ + agent, + aud: target.serviceDid, + lxm: ADMIT_FEED_POST, + exp: Math.floor(Date.now() / 1000) + 60, + }) + const response = await agent.fetchHandler(`/xrpc/${ADMIT_FEED_POST}`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'atproto-proxy': `${target.serviceDid}#bsky_fg`, + }, + body: JSON.stringify({feed: target.feed, post, cid}), + }) + if (!response.ok) { + const body = (await response.json().catch(() => ({}))) as {message?: string} + throw new Error(body.message || `HTTP ${response.status}`) + } +} diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts new file mode 100644 index 000000000..4eb41154a --- /dev/null +++ b/src/lib/api/community-post.ts @@ -0,0 +1,92 @@ +import { + type AppBskyFeedDefs, + AppBskyFeedPost, + type BskyAgent, + jsonToLex, +} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {isSpaceRecordUri, parseSpaceUri} from '#/lib/api/space-uri' +import {toPostView} from '#/lib/api/space-views' +import * as bsky from '#/types/bsky' + +export const GET_COMMUNITY_POST = 'community.blacksky.feed.getCommunityPost' + +const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' + +/** + * Whether this post is community content — the appview-stored stub, or a + * record living in a permissioned space. Keyed structurally rather than by + * collection, so a new kind of space record is covered the day it appears. + */ +export function isCommunityPostUri(uri: string | undefined): boolean { + return ( + !!uri && (uri.includes(COMMUNITY_POST_COLLECTION) || isSpaceRecordUri(uri)) + ) +} + +/** + * Space records use the same post record shape as public posts, but their + * reply and quote refs are permissioned-space URIs rather than AT-URIs. The + * public lexicon validator therefore cannot validate those otherwise valid + * records. Space responses are already validated by the AppView endpoint; + * retain the fields the renderer requires here while keeping strict lexicon + * validation for public posts. + */ +export function isRenderablePostRecord( + post: AppBskyFeedDefs.PostView, +): post is AppBskyFeedDefs.PostView & {record: AppBskyFeedPost.Record} { + if (!AppBskyFeedPost.isRecord(post.record)) return false + if (!isSpaceRecordUri(post.uri)) { + return bsky.validate(post.record, AppBskyFeedPost.validateRecord) + } + return ( + typeof post.record.text === 'string' && + typeof post.record.createdAt === 'string' + ) +} + +export type CommunityPostView = AppBskyFeedDefs.PostView & { + communitySpace?: string +} + +/** + * The permissioned space a post lives in, which is its authorization + * boundary. A feed is only a view over a space, so the post view carries the + * space; never fed to `AtUri`, which misparses a space URI. + */ +export function getCommunitySpaceUri( + post: AppBskyFeedDefs.PostView | undefined, +): string | undefined { + const space = (post as unknown as {communitySpace?: unknown} | undefined) + ?.communitySpace + // The 4-segment pointer only: a record inside a space is not the space. + return typeof space === 'string' && parseSpaceUri(space) !== null + ? space + : undefined +} + +/** + * Read one community post by URI. + * + * The standard `getPosts` cannot serve these: its `uris` are at-uris, and a + * space record URI is not one. This endpoint takes a plain string, and gates + * on membership before returning anything. + */ +export async function fetchCommunityPostView( + agent: BskyAgent, + uri: string, +): Promise { + const res = await communityXrpc(agent, GET_COMMUNITY_POST, {params: {uri}}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post +} diff --git a/src/lib/api/community-thread.ts b/src/lib/api/community-thread.ts new file mode 100644 index 000000000..f3c6743a5 --- /dev/null +++ b/src/lib/api/community-thread.ts @@ -0,0 +1,81 @@ +import {type BskyAgent} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {toSpaceThreadBody} from '#/lib/api/space-views' + +export const GET_COMMUNITY_THREAD = 'community.blacksky.feed.getCommunityThread' + +export type CommunityThreadResponse = { + thread: unknown[] + hasOtherReplies: boolean + /** Space feeds carry no threadgates (they are deferred), so never set. */ + threadgate?: undefined +} + +/** + * Fetch a thread anchored on a permissioned-space record. + * + * The standard thread endpoint cannot be used: its anchor is declared + * `format: at-uri`, and a space URI is not one, so the request is refused + * before it reaches a handler. This endpoint takes the anchor as a plain + * string and answers with the same item shape. + */ +export async function fetchCommunityThread( + agent: BskyAgent, + params: { + anchor: string + above?: boolean + below?: number + branchingFactor?: number + }, +): Promise { + const query: Record = {anchor: params.anchor} + if (params.above !== undefined) query.above = String(params.above) + if (params.below !== undefined) query.below = String(params.below) + if (params.branchingFactor !== undefined) { + query.branchingFactor = String(params.branchingFactor) + } + const res = await communityXrpc(agent, GET_COMMUNITY_THREAD, {params: query}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + // The wire types are community.blacksky.feed.defs; the thread renderer + // consumes the standard threadItem shapes, which are structurally identical. + const data = toSpaceThreadBody( + await res.json(), + ) as Partial + return { + thread: data.thread ?? [], + hasOtherReplies: !!data.hasOtherReplies, + } +} + +export const SET_THREAD_MUTE = 'community.blacksky.feed.setThreadMute' + +/** + * Mute or unmute a thread rooted at a space record. + * + * The standard mute methods take an at-uri, which a space URI is not. Mute + * state itself is keyed by plain URI on both sides, so nothing else differs. + */ +export async function setSpaceThreadMute( + agent: BskyAgent, + root: string, + mute: boolean, +): Promise<{}> { + const res = await communityXrpc(agent, SET_THREAD_MUTE, { + body: {root, mute}, + }) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + return {} +} diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts index cd0aa72f2..817580059 100644 --- a/src/lib/api/community.ts +++ b/src/lib/api/community.ts @@ -1,22 +1,20 @@ -import {type BskyAgent} from '@atproto/api' +import { + type AppBskyFeedGetLikes, + type AppBskyFeedGetQuotes, + type BskyAgent, + jsonToLex, +} from '@atproto/api' import {HOME_PROXY_HEADER} from '#/lib/constants' +import {toPostView} from './space-views' -/** - * Make an XRPC call to a community.blacksky.feed.* endpoint. - * - * Calls through the PDS using the agent's session auth and atproto-proxy - * header. The PDS validates the user's credentials, creates a service auth - * JWT signed by the user's keypair, and forwards the request to the appview. - * - * Pinned: community.blacksky.* endpoints only exist on the home appview. - */ export async function communityXrpc( agent: BskyAgent, method: string, opts?: { params?: Record body?: unknown + serviceDid?: string }, ): Promise { const qs = opts?.params @@ -25,7 +23,9 @@ export async function communityXrpc( const path = `/xrpc/${method}${qs}` const headers: Record = { - 'atproto-proxy': HOME_PROXY_HEADER, + 'atproto-proxy': opts?.serviceDid + ? `${opts.serviceDid}#bsky_appview` + : HOME_PROXY_HEADER, } const init: RequestInit = { method: opts?.body ? 'POST' : 'GET', @@ -37,3 +37,58 @@ export async function communityXrpc( } return agent.fetchHandler(path, init) } + +export async function getSpacePostLikes( + agent: BskyAgent, + params: {uri: string; limit: number; cursor?: string}, +): Promise { + const response = await communityXrpc( + agent, + 'community.blacksky.feed.getSpacePostLikes', + { + params: { + uri: params.uri, + limit: String(params.limit), + ...(params.cursor ? {cursor: params.cursor} : {}), + }, + }, + ) + if (!response.ok) { + throw new Error(`getSpacePostLikes ${response.status}`) + } + return jsonToLex(await response.json()) as AppBskyFeedGetLikes.OutputSchema +} + +export async function getSpacePostQuotes( + agent: BskyAgent, + params: {uri: string; limit: number; cursor?: string}, +): Promise { + const response = await communityXrpc( + agent, + 'community.blacksky.feed.getSpacePostQuotes', + { + params: { + uri: params.uri, + limit: String(params.limit), + ...(params.cursor ? {cursor: params.cursor} : {}), + }, + }, + ) + if (!response.ok) { + throw new Error(`getSpacePostQuotes ${response.status}`) + } + const data = jsonToLex(await response.json()) as { + cursor?: string + posts?: unknown[] + } + return { + uri: params.uri, + cursor: data.cursor, + posts: (data.posts ?? []) + .map(toPostView) + .filter( + (post): post is AppBskyFeedGetQuotes.OutputSchema['posts'][number] => + Boolean(post), + ), + } +} diff --git a/src/lib/api/feed-manip.ts b/src/lib/api/feed-manip.ts index 335bf28c8..501e12573 100644 --- a/src/lib/api/feed-manip.ts +++ b/src/lib/api/feed-manip.ts @@ -6,7 +6,7 @@ import { AppBskyFeedPost, } from '@atproto/api' -import * as bsky from '#/types/bsky' +import {isRenderablePostRecord} from '#/lib/api/community-post' import {isPostInLanguage} from '../../locale/helpers' import {FALLBACK_MARKER_POST} from './feed/home' import {type ReasonFeedSource} from './feed/types' @@ -68,10 +68,7 @@ export class FeedViewPostsSlice { this.isFallbackMarker = true return } - if ( - !AppBskyFeedPost.isRecord(post.record) || - !bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ) { + if (!isRenderablePostRecord(post)) { return } const parent = reply?.parent @@ -101,8 +98,7 @@ export class FeedViewPostsSlice { } if ( !AppBskyFeedDefs.isPostView(parent) || - !AppBskyFeedPost.isRecord(parent.record) || - !bsky.validate(parent.record, AppBskyFeedPost.validateRecord) + !isRenderablePostRecord(parent) ) { this.isOrphan = true return @@ -141,11 +137,7 @@ export class FeedViewPostsSlice { // Keep going, it might still have a root, and we need this for thread // de-deduping } - if ( - !AppBskyFeedDefs.isPostView(root) || - !AppBskyFeedPost.isRecord(root.record) || - !bsky.validate(root.record, AppBskyFeedPost.validateRecord) - ) { + if (!AppBskyFeedDefs.isPostView(root) || !isRenderablePostRecord(root)) { this.isOrphan = true return } diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index d751629b3..00065bc6f 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -5,6 +5,14 @@ import { jsonStringToLex, } from '@atproto/api' +import { + type CommunityFeedConfig, + fetchCommunityFeedConfigStrict, + fetchFeedServiceDid, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import {getServiceAuthToken} from '#/lib/api/service-auth' +import {fetchSpaceFeed, signInRequiredError} from '#/lib/api/space-feed' import { getAppLanguageAsContentLanguage, getContentLanguages, @@ -20,6 +28,8 @@ export class CustomFeedAPI implements FeedAPI { agent: AtpAgent params: GetCustomFeed.QueryParams userInterests?: string + communityConfig: Promise + feedServiceDid: Promise constructor({ agent, @@ -33,10 +43,54 @@ export class CustomFeedAPI implements FeedAPI { this.agent = agent this.params = feedParams this.userInterests = userInterests + this.communityConfig = fetchCommunityFeedConfigStrict( + agent, + feedParams.feed, + ) + this.feedServiceDid = this.communityConfig + .then(config => + config ? fetchFeedServiceDid(agent, feedParams.feed) : null, + ) + .catch(() => null) + } + + async communityAuthHeaders(): Promise> { + const [config, serviceDid] = await Promise.all([ + this.communityConfig, + this.feedServiceDid, + ]) + if (!config || !serviceDid) return {} + const token = await getServiceAuthToken({ + agent: this.agent, + aud: serviceDid, + lxm: 'app.bsky.feed.getFeedSkeleton', + exp: Math.floor(Date.now() / 1000) + 60, + }) + return {Authorization: `Bearer ${token}`} + } + + /** + * A space-backed feed never reaches the standard route, in either method. + * `app.bsky.feed.getFeed` now refuses it outright, so a poller that skipped + * this branch would error on every tick, and the logged-out fallback below + * would ask the public appview for private content. + */ + private async spaceFeed(): Promise { + const config = await this.communityConfig + return isSpaceBackedFeed(config) ? this.params.feed : null } async peekLatest(): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {limit: 1}) + return page.feed[0] + } const contentLangs = getContentLanguages().join(',') + const communityAuthHeaders = this.agent.did + ? await this.communityAuthHeaders() + : {} const res = await this.agent.app.bsky.feed.getFeed( { ...this.params, @@ -45,6 +99,7 @@ export class CustomFeedAPI implements FeedAPI { { headers: { ...getProxyHeadersForFeed(this.params.feed), + ...communityAuthHeaders, 'Accept-Language': contentLangs, }, }, @@ -59,9 +114,22 @@ export class CustomFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {cursor, limit}) + return { + cursor: page.feed.length ? page.cursor : undefined, + feed: page.feed, + } + } + const contentLangs = getContentLanguages().join(',') const agent = this.agent const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) + const communityAuthHeaders = agent.did + ? await this.communityAuthHeaders() + : {} const res = agent.did ? await this.agent.app.bsky.feed.getFeed( @@ -73,6 +141,7 @@ export class CustomFeedAPI implements FeedAPI { { headers: { ...getProxyHeadersForFeed(this.params.feed), + ...communityAuthHeaders, ...(isBlueskyOwned ? createBskyTopicsHeader(this.userInterests) : {}), diff --git a/src/lib/api/group-invite-e2e.e2e.ts b/src/lib/api/group-invite-e2e.e2e.ts new file mode 100644 index 000000000..153cf18cd --- /dev/null +++ b/src/lib/api/group-invite-e2e.e2e.ts @@ -0,0 +1,33 @@ +type GroupInviteE2EFailureStage = + | 'saved-feed-update' + | 'saved-feed-add' + | 'navigation' + +let pendingFailure: GroupInviteE2EFailureStage | undefined + +class GroupInviteE2EInjectedFailure extends Error { + readonly stage: GroupInviteE2EFailureStage + + constructor(stage: GroupInviteE2EFailureStage) { + super(`Injected group invite E2E failure: ${stage}`) + this.name = 'GroupInviteE2EInjectedFailure' + this.stage = stage + } +} + +export function setGroupInviteE2EFailure(stage: GroupInviteE2EFailureStage) { + pendingFailure = stage +} + +export function maybeFailGroupInviteE2E(stage: GroupInviteE2EFailureStage) { + if (pendingFailure !== stage) return + pendingFailure = undefined + throw new GroupInviteE2EInjectedFailure(stage) +} + +export function isGroupInviteE2EFailure( + error: unknown, + stage: GroupInviteE2EFailureStage, +) { + return error instanceof GroupInviteE2EInjectedFailure && error.stage === stage +} diff --git a/src/lib/api/group-invite-e2e.ts b/src/lib/api/group-invite-e2e.ts new file mode 100644 index 000000000..5771fdbfd --- /dev/null +++ b/src/lib/api/group-invite-e2e.ts @@ -0,0 +1,20 @@ +export type GroupInviteE2EFailureStage = + | 'saved-feed-update' + | 'saved-feed-add' + | 'navigation' + +/** Production builds never inject client-side failures. */ +export function setGroupInviteE2EFailure( + _stage: GroupInviteE2EFailureStage, +): void {} + +export function maybeFailGroupInviteE2E( + _stage: GroupInviteE2EFailureStage, +): void {} + +export function isGroupInviteE2EFailure( + _error: unknown, + _stage: GroupInviteE2EFailureStage, +): boolean { + return false +} diff --git a/src/lib/api/group-invite-ui.ts b/src/lib/api/group-invite-ui.ts new file mode 100644 index 000000000..87fe3986a --- /dev/null +++ b/src/lib/api/group-invite-ui.ts @@ -0,0 +1,124 @@ +import {type AppBskyActorDefs} from '@atproto/api' + +import { + GroupInviteClientError, + GroupInviteError, + type GroupInviteFeed, +} from './group-invites' + +const openedGroupInviteCodes = new Set() +const MAX_TRACKED_GROUP_INVITES = 1_000 + +export function shouldTrackGroupInviteOpened(code: string) { + if (openedGroupInviteCodes.has(code)) return false + if (openedGroupInviteCodes.size >= MAX_TRACKED_GROUP_INVITES) { + const oldest = openedGroupInviteCodes.values().next().value + if (oldest) openedGroupInviteCodes.delete(oldest) + } + openedGroupInviteCodes.add(code) + return true +} + +export function groupInviteErrorCopy(error: unknown): string { + const code = + error instanceof GroupInviteClientError + ? error.code + : GroupInviteError.AuthorizationUnavailable + switch (code) { + case GroupInviteError.InviteUnavailable: + return 'This invite is no longer available.' + case GroupInviteError.GroupAtCapacity: + return 'This group is currently at capacity.' + case GroupInviteError.RateLimitExceeded: + return 'Too many attempts. Please try again shortly.' + case GroupInviteError.AuthenticationRequired: + return 'Please sign in again to accept this invite.' + case GroupInviteError.InviteMisconfigured: + return 'This invite is temporarily unavailable.' + case GroupInviteError.AuthorizationUnavailable: + default: + return 'We could not contact the group service. Please try again.' + } +} + +export function summarizeGroupInviteFeeds(feeds: GroupInviteFeed[]) { + const readable = feeds.filter(feed => feed.canView) + return { + readable, + postable: readable.filter(feed => feed.canPost), + readOnly: readable.filter(feed => !feed.canPost), + } +} + +export function getDefaultGroupInviteFeedUris(feeds: GroupInviteFeed[]) { + return feeds + .filter(feed => feed.canView && Boolean(feed.uri)) + .map(feed => feed.uri) +} + +export function getFirstSelectedGroupInviteFeed( + feeds: GroupInviteFeed[], + selectedUris: ReadonlySet, +) { + const selected = feeds.filter( + feed => feed.canView && Boolean(feed.uri) && selectedUris.has(feed.uri), + ) + return selected.find(feed => feed.canPost) ?? selected[0] +} + +export function shouldOpenGroupInviteFeedAfterPinning( + feeds: GroupInviteFeed[], + selectedUris: ReadonlySet, +) { + return Boolean(getFirstSelectedGroupInviteFeed(feeds, selectedUris)) +} + +export function getGroupInviteMembershipCopy(feeds: GroupInviteFeed[]) { + const {readable, postable} = summarizeGroupInviteFeeds(feeds) + if (readable.length === 0) return 'No feeds available.' + if (postable.length === 0) return getGroupInviteNoPostCopy() + return undefined +} + +export function getGroupInviteNoPostCopy() { + return "You joined the group, but you don't currently have access to a feed you can post in. Please let your admins know if you think this is a mistake." +} + +export function shouldResetGroupInvitePinning( + previousUris: string[], + nextUris: string[], +) { + return ( + previousUris.length !== nextUris.length || + previousUris.some(uri => !nextUris.includes(uri)) + ) +} + +export function groupInviteFailureName(error: unknown) { + return error instanceof GroupInviteClientError ? error.code : 'Unknown' +} + +export function getGroupInviteFeedMutations( + feeds: GroupInviteFeed[], + savedFeeds: AppBskyActorDefs.SavedFeed[] = [], + selectedUris?: ReadonlySet, +) { + const savedByValue = new Map(savedFeeds.map(feed => [feed.value, feed])) + const readable = feeds.filter( + feed => + feed.canView && + Boolean(feed.uri) && + (selectedUris === undefined || selectedUris.has(feed.uri)), + ) + return { + toAdd: readable + .filter(feed => !savedByValue.has(feed.uri)) + .map(feed => ({type: 'feed' as const, value: feed.uri, pinned: true})), + toUpdate: readable + .map(feed => savedByValue.get(feed.uri)) + .filter((feed): feed is AppBskyActorDefs.SavedFeed => + Boolean(feed && !feed.pinned), + ) + .map(feed => ({...feed, pinned: true})), + } +} diff --git a/src/lib/api/group-invites.ts b/src/lib/api/group-invites.ts new file mode 100644 index 000000000..b1819d76e --- /dev/null +++ b/src/lib/api/group-invites.ts @@ -0,0 +1,280 @@ +import {type AtpAgent} from '@atproto/api' + +import {ACORN_SERVICE_URL} from '#/env' +import {getServiceAuthToken} from './service-auth' + +export const GROUP_INVITE_LXM = 'community.blacksky.group.acceptInvite' + +export const GroupInviteError = { + InviteUnavailable: 'InviteUnavailable', + GroupAtCapacity: 'GroupAtCapacity', + AuthenticationRequired: 'AuthenticationRequired', + AuthorizationUnavailable: 'AuthorizationUnavailable', + InviteMisconfigured: 'InviteMisconfigured', + RateLimitExceeded: 'RateLimitExceeded', +} as const + +export type GroupInviteErrorCode = + (typeof GroupInviteError)[keyof typeof GroupInviteError] + +export class GroupInviteClientError extends Error { + readonly code: GroupInviteErrorCode + + constructor(code: GroupInviteErrorCode) { + super(code) + this.name = 'GroupInviteClientError' + this.code = code + } +} + +export type GroupInvitePreview = { + community: {did: string; name: string} + group: {name: string; displayName: string} + expiresAt: string +} + +export type GroupInviteFeed = { + uri: string + name: string + canView: boolean + canPost: boolean +} + +export type GroupInviteAcceptance = { + communityDid: string + groupName: string + membership: 'joined' + feeds: GroupInviteFeed[] +} + +type TrpcEnvelope = { + result?: {data?: unknown} + error?: { + message?: string + json?: {message?: string; data?: {code?: string}} + } +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)) +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 +} + +function isAuthenticationError(error: unknown): boolean { + if (!error || typeof error !== 'object') return false + const value = error as { + status?: unknown + error?: unknown + name?: unknown + } + return ( + value.status === 401 || + value.error === 'AuthenticationRequired' || + value.name === 'AuthenticationRequired' + ) +} + +function parsePreview(value: unknown): GroupInvitePreview { + if (!isRecord(value)) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + const community = value.community + const group = value.group + if ( + !isRecord(community) || + !isNonEmptyString(community.did) || + !isNonEmptyString(community.name) || + !isRecord(group) || + !isNonEmptyString(group.name) || + !isNonEmptyString(group.displayName) || + !isNonEmptyString(value.expiresAt) + ) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + return { + community: {did: community.did, name: community.name}, + group: {name: group.name, displayName: group.displayName}, + expiresAt: value.expiresAt, + } +} + +function parseAcceptance(value: unknown): GroupInviteAcceptance { + if (!isRecord(value) || value.membership !== 'joined') { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + if ( + !isNonEmptyString(value.communityDid) || + !isNonEmptyString(value.groupName) || + !Array.isArray(value.feeds) + ) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + const feeds: GroupInviteFeed[] = [] + for (const feed of value.feeds) { + if ( + !isRecord(feed) || + !isNonEmptyString(feed.uri) || + !isNonEmptyString(feed.name) || + typeof feed.canView !== 'boolean' || + typeof feed.canPost !== 'boolean' || + (!feed.canView && feed.canPost) + ) { + throw new GroupInviteClientError( + GroupInviteError.AuthorizationUnavailable, + ) + } + feeds.push({ + uri: feed.uri, + name: feed.name, + canView: feed.canView, + canPost: feed.canPost, + }) + } + return { + communityDid: value.communityDid, + groupName: value.groupName, + membership: 'joined', + feeds, + } +} + +function unwrapResult(value: unknown): unknown { + if (!value || typeof value !== 'object') return undefined + const data = (value as {result?: {data?: unknown}}).result?.data + if (data && typeof data === 'object' && 'json' in data) { + return data.json + } + return data +} + +function stableCodeFromResponse(body: TrpcEnvelope): GroupInviteErrorCode { + const message = body.error?.json?.message || body.error?.message + const stableMessage = mapStableCode(message) + if (stableMessage) return stableMessage + return ( + mapStableCode(body.error?.json?.data?.code) ?? + GroupInviteError.AuthorizationUnavailable + ) +} + +function mapStableCode( + raw: string | undefined, +): GroupInviteErrorCode | undefined { + switch (raw) { + case 'InviteUnavailable': + case 'INVITE_UNAVAILABLE': + case 'BAD_REQUEST': + case 'NOT_FOUND': + return GroupInviteError.InviteUnavailable + case 'GroupAtCapacity': + case 'GROUP_AT_CAPACITY': + case 'CONFLICT': + return GroupInviteError.GroupAtCapacity + case 'AuthenticationRequired': + case 'AUTHENTICATION_REQUIRED': + case 'UNAUTHORIZED': + return GroupInviteError.AuthenticationRequired + case 'RateLimitExceeded': + case 'RATE_LIMIT_EXCEEDED': + case 'TOO_MANY_REQUESTS': + return GroupInviteError.RateLimitExceeded + case 'InviteMisconfigured': + case 'INVITE_MISCONFIGURED': + return GroupInviteError.InviteMisconfigured + case 'AuthorizationUnavailable': + case 'AUTHORIZATION_UNAVAILABLE': + case 'SERVICE_UNAVAILABLE': + case 'INTERNAL_SERVER_ERROR': + return GroupInviteError.AuthorizationUnavailable + default: + return undefined + } +} + +async function request({ + procedure, + input, + method, + headers, +}: { + procedure: string + input: Record + method: 'GET' | 'POST' + headers?: Record +}): Promise { + const endpoint = `${ACORN_SERVICE_URL.replace(/\/$/, '')}/api/trpc/${procedure}` + // Invite codes are bearer credentials. Keep them in a POST body so they do + // not enter URL/access/referrer logs or browser history. + const url = endpoint + + let response: Response + try { + response = await fetch(url, { + method, + headers: { + Accept: 'application/json', + ...(method === 'POST' ? {'Content-Type': 'application/json'} : {}), + ...headers, + }, + ...(method === 'POST' ? {body: JSON.stringify(input)} : undefined), + }) + } catch { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + + const body = (await response.json().catch(() => ({}))) as TrpcEnvelope + if (!response.ok || body.error) { + throw new GroupInviteClientError(stableCodeFromResponse(body)) + } + + const result = unwrapResult(body) + if (result === undefined) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + return result as T +} + +export function previewGroupInvite(code: string) { + return request({ + procedure: 'groupInvites.preview', + input: {code}, + method: 'POST', + }).then(parsePreview) +} + +export async function acceptGroupInvite({ + code, + communityDid, + agent, +}: { + code: string + communityDid: string + agent: AtpAgent +}) { + let token: string + try { + token = await getServiceAuthToken({ + agent, + aud: communityDid, + lxm: GROUP_INVITE_LXM, + exp: Math.floor(Date.now() / 1000) + 60, + }) + } catch (error) { + throw new GroupInviteClientError( + isAuthenticationError(error) + ? GroupInviteError.AuthenticationRequired + : GroupInviteError.AuthorizationUnavailable, + ) + } + + const result = await request({ + procedure: 'groupInvites.accept', + input: {code}, + method: 'POST', + headers: {Authorization: `Bearer ${token}`}, + }) + return parseAcceptance(result) +} diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 46a2d8789..8a1f279e2 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -26,6 +26,15 @@ import {CID} from 'multiformats/cid' import * as Hasher from 'multiformats/hashes/hasher' import {communityXrpc} from '#/lib/api/community' +import { + admitFeedPost, + fetchCommunityFeedTarget, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {spaceOfPostUrl} from '#/lib/api/space-permalink' +import {postToSpace} from '#/lib/api/space-post' +import {isSpaceRecordUri, spaceOfRecordUri} from '#/lib/api/space-uri' import {IMAGE_SIZE_CONFIG_POSTS} from '#/lib/constants' import {isNetworkError} from '#/lib/strings/errors' import {shortenLinks, stripInvalidMentions} from '#/lib/strings/rich-text-manip' @@ -52,8 +61,28 @@ export {uploadBlob} const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' -interface PostOpts { +/** + * The space a quote belongs to, whichever form it is in — a pasted permalink + * carries the space in `?space=` and is only expanded to its at:// form at + * publish, long after routing has decided where the post goes. + */ +export function quotedSpace(uri?: string | null): string | null { + return spaceOfRecordUri(uri) ?? spaceOfPostUrl(uri) +} + +function embedNamesSpaceRecord(embed: unknown): boolean { + if (!embed || typeof embed !== 'object') return false + const record = (embed as {record?: unknown}).record + if (!record || typeof record !== 'object') return false + const uri = + (record as {uri?: unknown}).uri ?? + (record as {record?: {uri?: unknown}}).record?.uri + return typeof uri === 'string' && isSpaceRecordUri(uri) +} + +export interface PostOpts { thread: ThreadDraft + draftId?: string replyTo?: string onStateChange?: (state: string) => void langs?: string[] @@ -64,9 +93,60 @@ export async function post( queryClient: QueryClient, opts: PostOpts, ) { - const thread = opts.thread + let thread = opts.thread + const replySpace = spaceOfRecordUri(opts.replyTo) + // Replying to or quoting a space post: the parent's space is the target, and + // no feed needs resolving — a feed is only a view over the space. + if (thread.communitySpaceUri || replySpace) { + const space = thread.communitySpaceUri ?? replySpace! + if ( + thread.communitySpaceUri && + replySpace && + thread.communitySpaceUri !== replySpace + ) { + throw new Error( + t`This reply targets a different private space than its parent.`, + ) + } + return postToSpace(agent, queryClient, space, opts) + } + + if (!thread.communityFeed && thread.communityFeedUri) { + const target = await fetchCommunityFeedTarget( + agent, + thread.communityFeedUri, + ) + if (!target) { + throw new Error( + t`You no longer have permission to post to this community.`, + ) + } + thread = {...thread, communityFeed: target} + opts = {...opts, thread} + } opts.onStateChange?.(t`Processing...`) + // A space-backed feed keeps its content in the author's permissioned repo, + // so it takes an entirely different write path and must be checked before + // the community routing below, which would otherwise claim it. + const config = thread.communityFeed?.config + if (isSpaceBackedFeed(config)) { + return postToSpace(agent, queryClient, config.space, opts) + } + + // Past this point the post is going to a public or community repo, not into + // any space, so nothing it carries may name one. A quote reaches the composer + // as a pasted link and is only expanded to its at:// form at publish, by + // which time the routing decision is made — so both forms are refused here, + // together. Without this a pasted space permalink rides `postCommunity`'s + // stub embed into the author's public repo, publishing the existence of a + // private post. + if (thread.posts.some(p => quotedSpace(p.embed.quote?.uri))) { + throw new Error( + t`This is a private post. You can only quote it in a post to that space.`, + ) + } + // Route to community post endpoint if the user explicitly toggled // Blacksky-Only, is replying to a community post, or is quoting one. const isReplyToCommunityPost = @@ -74,17 +154,28 @@ export async function post( const isQuoteOfCommunityPost = thread.posts.some(p => p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), ) + const selectedCommunityRecordFeed = + thread.communityFeed?.config.contentType === 'communityRecord' - if (thread.blackskyOnly || isReplyToCommunityPost || isQuoteOfCommunityPost) { + if ( + thread.blackskyOnly || + selectedCommunityRecordFeed || + isReplyToCommunityPost || + isQuoteOfCommunityPost + ) { return postCommunity(agent, queryClient, opts) } // A public post must never carry a community post in its embed; the // routing above sends those to postCommunity, so reaching here with one - // is a bug we refuse rather than leak community content publicly. + // is a bug we refuse rather than leak community content publicly. A space + // record is refused for the same reason, and its URI would leak the space + // even if the appview declined to hydrate it. if ( - thread.posts.some(p => - p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), + thread.posts.some( + p => + p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION) || + isSpaceRecordUri(p.embed.quote?.uri), ) ) { throw new Error('Public posts cannot embed a community post') @@ -108,6 +199,7 @@ export async function post( const did = agent.assertDid const writes: $Typed[] = [] const uris: string[] = [] + const admissions: Array<{post: string; cid: string}> = [] let now = new Date() let tid: TID | undefined @@ -196,6 +288,9 @@ export async function post( cid: await computeCid(record), uri, } + if (thread.communityFeed?.config.contentType === 'publicRecord') { + admissions.push({post: uri, cid: ref.cid}) + } replyPromise = { root: reply?.root ?? ref, parent: ref, @@ -222,6 +317,14 @@ export async function post( } } + if (thread.communityFeed?.config.contentType === 'publicRecord') { + await Promise.all( + admissions.map(({post, cid}) => + admitFeedPost(agent, thread.communityFeed!, post, cid), + ), + ) + } + return {uris} } @@ -248,6 +351,7 @@ async function postCommunity( const did = agent.assertDid const writes: $Typed[] = [] const uris: string[] = [] + const admissions: Array<{post: string; cid: string}> = [] let now = new Date() let tid: TID | undefined @@ -362,6 +466,10 @@ async function postCommunity( const submitRes = await communityXrpc( agent, 'community.blacksky.feed.submitPost', + // No serviceDid: submitPost serves the Blacksky community feed, whose + // content lives on the home appview. `contentStore` named a per-feed + // appview for the retired multi-tenant path and was always undefined + // here, so the proxy target is unchanged. {body: submitBody}, ) if (!submitRes.ok) { @@ -404,6 +512,14 @@ async function postCommunity( // stub so external-thumb / image / video / gallery blobs stay alive for // the post's lifetime. Text / facets / langs / reply remain appview-only. if (embed) { + // The stub goes to the author's public repo, so it is the last place a + // space URI could leak from. The routing guard in `post` already refuses + // these; this is the invariant restated where the write happens. + if (embedNamesSpaceRecord(embed)) { + throw new Error( + t`This is a private post. You can only quote it in a post to that space.`, + ) + } stubRecord.embed = embed } @@ -419,6 +535,9 @@ async function postCommunity( cid: await computeCid(stubRecord as unknown as AppBskyFeedPost.Record), uri, } + if (thread.communityFeed) { + admissions.push({post: uri, cid: ref.cid}) + } replyPromise = { root: reply?.root ?? ref, parent: ref, @@ -445,13 +564,21 @@ async function postCommunity( } } + if (thread.communityFeed) { + await Promise.all( + admissions.map(({post, cid}) => + admitFeedPost(agent, thread.communityFeed!, post, cid), + ), + ) + } + void queryClient.invalidateQueries({queryKey: ['community-timeline']}) void queryClient.invalidateQueries({queryKey: ['community-feed']}) return {uris} } -async function resolveRT(agent: AtpAgent, richtext: RichText) { +export async function resolveRT(agent: AtpAgent, richtext: RichText) { const trimmedText = richtext.text // Trim leading whitespace-only lines (but don't break ASCII art). .replace(/^(\s*\n)+/, '') @@ -471,7 +598,39 @@ export class ReplyDeletedError extends Error { } } -async function resolveReply(agent: AtpAgent, replyTo: string) { +/** + * The reply refs a caller gets back from the non-space branches go straight + * into a public `app.bsky.feed.post`, so a thread root that turns out to name a + * space has to stop here: the space branch above is the only one allowed to + * return one. + */ +function refusePublicSpaceRefs< + T extends {root: {uri: string}; parent: {uri: string}}, +>(refs: T): T { + if (isSpaceRecordUri(refs.root.uri) || isSpaceRecordUri(refs.parent.uri)) { + throw new Error( + t`This is a private post. You can only reply to it in that space.`, + ) + } + return refs +} + +export async function resolveReply(agent: AtpAgent, replyTo: string) { + // Space records first: they are not at-uris, so AtUri would misparse one. + // The parent is read back through the appview, which is the only read path + // the client has into a space, and carries the root of its own thread. + if (isSpaceRecordUri(replyTo)) { + const post = await fetchCommunityPostView(agent, replyTo) + const parent = {uri: post.uri, cid: post.cid} + const root = ( + post.record as {reply?: {root?: {uri?: string; cid?: string}}} + )?.reply?.root + return { + root: root?.uri && root?.cid ? {uri: root.uri, cid: root.cid} : parent, + parent, + } + } + const replyToUrip = new AtUri(replyTo) // Community posts are fetched from the appview, not the standard feed API. @@ -503,7 +662,7 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { parentRootRef?.uri && parentRootRef?.cid ? {uri: parentRootRef.uri, cid: parentRootRef.cid} : parentRef - return {root: rootRef, parent: parentRef} + return refusePublicSpaceRefs({root: rootRef, parent: parentRef}) } return undefined } @@ -534,13 +693,13 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { } } - return { + return refusePublicSpaceRefs({ root: rootRef, parent: parentRef, - } + }) } -async function resolveEmbed( +export async function resolveEmbed( agent: AtpAgent, queryClient: QueryClient, draft: PostDraft, diff --git a/src/lib/api/resolve.ts b/src/lib/api/resolve.ts index 2c97afbee..5b3bc961d 100644 --- a/src/lib/api/resolve.ts +++ b/src/lib/api/resolve.ts @@ -7,6 +7,9 @@ import { import {AtUri, jsonToLex} from '@atproto/api' import {communityXrpc} from '#/lib/api/community' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {DM_SERVICE_HEADERS, IMAGE_SIZE_CONFIG_2K_1MB} from '#/lib/constants' import {getLinkMeta, type LinkMeta} from '#/lib/link-meta/link-meta' import {resolveShortLink} from '#/lib/link-meta/resolve-short-link' @@ -100,12 +103,17 @@ const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' // Pull the path portion (without ?query) and the collection from a bsky-style // post URL. Community posts share the /profile//post/ shape with a // ?collection=community.blacksky.feed.post tail. -function splitPostUrl(url: string): {path: string; collection: string} { +function splitPostUrl(url: string): { + path: string + collection: string + space?: string +} { const stripped = convertBskyAppUrlIfNeeded(url) try { const u = new URL(stripped, 'http://_') const collection = u.searchParams.get('collection') || 'app.bsky.feed.post' - return {path: u.pathname, collection} + const space = u.searchParams.get('space') || undefined + return {path: u.pathname, collection, space} } catch { const [path] = stripped.split('?') return {path, collection: 'app.bsky.feed.post'} @@ -116,6 +124,10 @@ async function getCommunityPost( agent: AtpAgent, uri: string, ): Promise { + // A space record URI is already fully qualified — and would misparse here. + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { const res = await agent.resolveHandle({handle: urip.host}) @@ -145,11 +157,14 @@ export async function resolveLink( uri = await resolveShortLink(uri) } if (isBskyPostUrl(uri)) { - const {path, collection} = splitPostUrl(uri) + const {path, collection, space} = splitPostUrl(uri) const [_0, user, _1, rkey] = path.split('/').filter(Boolean) - const recordUri = makeRecordUri(user, collection, rkey) + // A `?space=` link addresses a record inside a permissioned space, which + // is read back through the appview like any other community post. + const spaceUri = spacePostUriFromRoute(space, user, rkey, collection) + const recordUri = spaceUri ?? makeRecordUri(user, collection, rkey) const post = - collection === COMMUNITY_POST_COLLECTION + spaceUri || collection === COMMUNITY_POST_COLLECTION ? await getCommunityPost(agent, recordUri) : await getPost({uri: recordUri}) if (post.viewer?.embeddingDisabled) { diff --git a/src/lib/api/service-auth.ts b/src/lib/api/service-auth.ts new file mode 100644 index 000000000..8806de5c3 --- /dev/null +++ b/src/lib/api/service-auth.ts @@ -0,0 +1,26 @@ +import {type AtpAgent} from '@atproto/api' + +import {getServiceAuthAudFromUrl} from '#/lib/strings/url-helpers' + +export async function getServiceAuthToken({ + agent, + aud, + lxm, + exp, +}: { + agent: AtpAgent + aud?: string + lxm: string + exp?: number +}) { + const pdsAud = getServiceAuthAudFromUrl(agent.dispatchUrl) + if (!pdsAud) { + throw new Error('Agent does not have a PDS URL') + } + const {data: serviceAuth} = await agent.com.atproto.server.getServiceAuth({ + aud: aud ?? pdsAud, + lxm, + exp, + }) + return serviceAuth.token +} diff --git a/src/lib/api/space-feed.ts b/src/lib/api/space-feed.ts new file mode 100644 index 000000000..99d27338d --- /dev/null +++ b/src/lib/api/space-feed.ts @@ -0,0 +1,45 @@ +import {type BskyAgent, jsonToLex} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {type SpaceFeedPage, toSpaceFeedPage} from '#/lib/api/space-views' + +export const GET_SPACE_FEED = 'community.blacksky.feed.getSpaceFeed' + +/** + * Thrown when a space-backed feed is opened without a session. The message is + * the `KnownError.FeedSignedInOnly` token so `detectKnownError` renders the + * sign-in-required state; the alternative — falling through to the public + * `api.bsky.app` fetch the standard custom-feed path uses when logged out — + * would ask a public appview for private content and leave the feed spinning. + */ +export const signInRequiredError = () => new Error('FeedSignedInOnly') + +/** + * The private read for a space-backed feed. + * + * `feed` is still the ordinary public `app.bsky.feed.generator` at-uri: the + * generator record remains the feed's identity, so no saved-feed preference + * needs migrating. Only the query chosen for that URI changes. The record URIs + * inside the response are space URIs and are never parsed here. + */ +export async function fetchSpaceFeed( + agent: BskyAgent, + feed: string, + {cursor, limit}: {cursor?: string; limit?: number} = {}, +): Promise { + const params: Record = {feed} + if (cursor) params.cursor = cursor + if (limit) params.limit = String(limit) + + const res = await communityXrpc(agent, GET_SPACE_FEED, {params}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + error?: string + message?: string + } + // Surfaced verbatim so an access refusal stays an access refusal: an empty + // page here would report "no posts" for "no access". + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + return toSpaceFeedPage(jsonToLex(await res.json())) +} diff --git a/src/lib/api/space-permalink.ts b/src/lib/api/space-permalink.ts new file mode 100644 index 000000000..af3c9db45 --- /dev/null +++ b/src/lib/api/space-permalink.ts @@ -0,0 +1,61 @@ +import {AtUri} from '@atproto/api' + +import { + parseSpaceUri, + spaceRecordAuthor, + spaceRecordUri, +} from '#/lib/api/space-uri' +import {POST_COLLECTION} from '#/lib/api/space-write' + +/** + * Rebuild a space post's URI from the parts a route carries. + * + * A space record URI has seven segments, of which the path supplies only the + * author and the rkey; the space itself rides in `?space=`. Returns null when + * the pieces do not add up — including when `author` is still a handle, which + * the caller must resolve to a DID first, since the URI form admits only DIDs. + */ +/** + * True when a link addresses a post inside a permissioned space. + * + * A space permalink is an ordinary-looking post URL — the space rides in + * `?space=`, so nothing about the path distinguishes it. Anything that decides + * where a post is written has to test the link form as well as the at:// form, + * because a pasted link is still a link when it reaches the composer. + */ +export function spaceOfPostUrl(url?: string | null): string | null { + if (!url) return null + try { + const space = new URL(url, 'http://_').searchParams.get('space') + return parseSpaceUri(space) ? space : null + } catch { + return null + } +} + +export function isSpacePostUrl(url?: string | null): boolean { + return !!spaceOfPostUrl(url) +} + +export function spacePostUriFromRoute( + space: string | undefined, + author: string, + rkey: string, + collection: string = POST_COLLECTION, +): string | null { + if (!space) return null + const ref = parseSpaceUri(space) + if (!ref || !author.startsWith('did:')) return null + return spaceRecordUri({...ref, authorDid: author, collection, rkey}) +} + +/** Read the author from either an ordinary post URI or a space record URI. */ +export function postUriAuthor(uri: string): string | null { + const spaceAuthor = spaceRecordAuthor(uri) + if (spaceAuthor) return spaceAuthor + try { + return new AtUri(uri).host + } catch { + return null + } +} diff --git a/src/lib/api/space-post.ts b/src/lib/api/space-post.ts new file mode 100644 index 000000000..535d89cc9 --- /dev/null +++ b/src/lib/api/space-post.ts @@ -0,0 +1,130 @@ +import {type AppBskyFeedPost, type AtpAgent} from '@atproto/api' +import {ensureValidRecordKey} from '@atproto/syntax' +import {t} from '@lingui/core/macro' +import {type QueryClient} from '@tanstack/react-query' + +import { + type PostOpts, + quotedSpace, + resolveEmbed, + resolveReply, + resolveRT, +} from '#/lib/api/index' +import {POST_COLLECTION, spaceCreateRecord} from '#/lib/api/space-write' + +/** + * Post a thread into a permissioned space. + * + * Deliberately not a branch inside `postCommunity`: that function implements + * the Blacksky community feed's three-step write (submit to the appview, write + * a public stub, admit to the feed generator), and none of those steps exist + * here. A space post is one ordinary `app.bsky.feed.post` written into the + * author's own permissioned repo; the syncer materialises it into the feed. + * + * Records are built as raw JSON rather than through typed builders, because a + * reply within a space refers to space URIs, which are not valid at-uris and + * would fail SDK-side validation. + */ +export async function postToSpace( + agent: AtpAgent, + queryClient: QueryClient, + space: string, + opts: PostOpts, +): Promise<{uris: string[]}> { + const thread = opts.thread + const langs = opts.langs?.slice(0, 3) + const uris: string[] = [] + + if (thread.posts.some(draft => draft.embed.media)) { + throw new Error( + t`Photos, videos, and GIFs are not available in private spaces yet.`, + ) + } + + // Read access is uniform within a space but not across spaces, so quoting + // another space's post here would name a private post to people who cannot + // see it. Same space is fine — everyone reading this record can already read + // the quoted one. + const foreign = thread.posts + .map(p => quotedSpace(p.embed.quote?.uri)) + .find(quoted => quoted && quoted !== space) + if (foreign) { + throw new Error( + t`This is a private post from another space. You can only quote it in a post to that space.`, + ) + } + + // Threads are written in order: each reply refers to the space URI the host + // returned for the post before it, so they cannot be batched. + let root: {uri: string; cid: string} | undefined + let parent: {uri: string; cid: string} | undefined + + // Replying into the space: the first draft hangs off the post being replied + // to, and everything after it hangs off its predecessor as usual. + if (opts.replyTo) { + const replyRef = await resolveReply(agent, opts.replyTo) + if (replyRef) { + root = replyRef.root + parent = replyRef.parent + } + } + + for (const [index, draft] of thread.posts.entries()) { + const rt = await resolveRT(agent, draft.richtext) + const embed = await resolveEmbed( + agent, + queryClient, + draft, + opts.onStateChange, + ) + + const record: Record = { + $type: POST_COLLECTION, + text: rt.text, + createdAt: new Date().toISOString(), + } + if (rt.facets?.length) record.facets = rt.facets + if (langs?.length) record.langs = langs + if (embed) record.embed = embed + if (draft.labels.length) { + record.labels = { + $type: 'com.atproto.label.defs#selfLabels', + values: draft.labels.map(val => ({val})), + } + } + if (root && parent) { + record.reply = {root, parent} + } + + opts.onStateChange?.(t`Posting to the private feed...`) + const rkey = opts.draftId ? `${opts.draftId}-${index}` : draft.id + ensureValidRecordKey(rkey) + const written = await spaceCreateRecord( + agent, + space, + POST_COLLECTION, + record, + rkey, + ) + + uris.push(written.uri) + root ??= written + parent = written + } + + return {uris} +} + +/** + * Threadgates and postgates are not written into a space. + * + * The public gate records address posts by at-uri and are enforced where + * public content is hydrated, neither of which applies here. The composer + * hides the controls; this exists so a caller that still holds gate state + * knows it is intentionally dropped rather than silently lost. + */ +export function spacePostsIgnoreGates(): true { + return true +} + +export type {AppBskyFeedPost} diff --git a/src/lib/api/space-uri.ts b/src/lib/api/space-uri.ts new file mode 100644 index 000000000..6fe54f8ad --- /dev/null +++ b/src/lib/api/space-uri.ts @@ -0,0 +1,117 @@ +/** + * Permissioned-space URIs (proposal 0016 addressing). + * + * space: at://{spaceDid}/space/{spaceType}/{skey} + * record: at://{spaceDid}/space/{spaceType}/{skey}/{authorDid}/{collection}/{rkey} + * + * These are NOT valid at-uris. `@atproto/syntax` caps an at-uri at + * authority/collection/rkey and requires the collection to be an NSID, and + * `space` has no dots — so both forms fail `format: at-uri` validation and + * misparse in `AtUri`. Never hand a space URI to `AtUri`; use this instead. + * + * Deliberately dependency-free: the appview, the client and both syncers need + * the same parser, and a copy that imports nothing can be vendored verbatim. + * The appview keeps the same parser at + * `packages/bsky/src/api/community/blacksky/space-uri.ts`; the two differ only + * where each repo's formatter differs. Any behavioral change goes in both. + */ + +/** The literal segment that marks a URI as addressing permissioned data. */ +export const SPACE_MARKER = 'space' + +const AT_PREFIX = 'at://' + +export type SpaceRef = { + spaceDid: string + spaceType: string + skey: string +} + +export type SpaceRecordRef = SpaceRef & { + authorDid: string + collection: string + rkey: string +} + +/** + * True when `uri` addresses permissioned data, in either form. + * + * A public at-uri can never collide: its second segment is a collection NSID, + * which always contains at least one dot, and `space` contains none. + */ +export const isSpaceUri = (uri?: string | null): boolean => { + if (!uri || !uri.startsWith(AT_PREFIX)) return false + const parts = uri.slice(AT_PREFIX.length).split('/') + return (parts.length === 4 || parts.length === 7) && parts[1] === SPACE_MARKER +} + +/** True only for the 7-segment record form. */ +export const isSpaceRecordUri = (uri?: string | null): boolean => + parseSpaceRecordUri(uri) !== null + +const looksLikeDid = (value: string): boolean => + /^did:[a-z]+:[A-Za-z0-9._:%-]*[A-Za-z0-9._-]$/.test(value) + +const isNonEmpty = (value: string): boolean => value.length > 0 + +/** Parse the 4-segment space form. Returns null for anything else. */ +export const parseSpaceUri = (uri?: string | null): SpaceRef | null => { + if (!uri || !uri.startsWith(AT_PREFIX)) return null + const parts = uri.slice(AT_PREFIX.length).split('/') + if (parts.length !== 4 || parts[1] !== SPACE_MARKER) return null + const [spaceDid, , spaceType, skey] = parts + if (!looksLikeDid(spaceDid) || !isNonEmpty(spaceType) || !isNonEmpty(skey)) { + return null + } + return {spaceDid, spaceType, skey} +} + +/** + * Parse the 7-segment record form. Returns null for anything else — including + * the 4-segment space form, a public at-uri, and near-misses at 6 or 8 + * segments. + */ +export const parseSpaceRecordUri = ( + uri?: string | null, +): SpaceRecordRef | null => { + if (!uri || !uri.startsWith(AT_PREFIX)) return null + const parts = uri.slice(AT_PREFIX.length).split('/') + if (parts.length !== 7 || parts[1] !== SPACE_MARKER) return null + const [spaceDid, , spaceType, skey, authorDid, collection, rkey] = parts + if ( + !looksLikeDid(spaceDid) || + !looksLikeDid(authorDid) || + !isNonEmpty(spaceType) || + !isNonEmpty(skey) || + !isNonEmpty(collection) || + !isNonEmpty(rkey) + ) { + return null + } + return {spaceDid, spaceType, skey, authorDid, collection, rkey} +} + +/** The space a record belongs to, as a URI. */ +export const spaceUriOf = (ref: SpaceRef): string => + `${AT_PREFIX}${ref.spaceDid}/${SPACE_MARKER}/${ref.spaceType}/${ref.skey}` + +/** Build a record URI inside a space. */ +export const spaceRecordUri = (ref: SpaceRecordRef): string => + `${spaceUriOf(ref)}/${ref.authorDid}/${ref.collection}/${ref.rkey}` + +/** + * The author of a space record. Authorship comes from the URI's own + * `authorDid` segment, never from a repo the URI was fetched from. + */ +export const spaceRecordAuthor = (uri?: string | null): string | null => + parseSpaceRecordUri(uri)?.authorDid ?? null + +/** The collection of a space record. */ +export const spaceRecordCollection = (uri?: string | null): string | null => + parseSpaceRecordUri(uri)?.collection ?? null + +/** The space a record URI belongs to, or null if it is not one. */ +export const spaceOfRecordUri = (uri?: string | null): string | null => { + const parsed = parseSpaceRecordUri(uri) + return parsed ? spaceUriOf(parsed) : null +} diff --git a/src/lib/api/space-views.ts b/src/lib/api/space-views.ts new file mode 100644 index 000000000..0a27dc4ca --- /dev/null +++ b/src/lib/api/space-views.ts @@ -0,0 +1,93 @@ +import {type AppBskyFeedDefs} from '@atproto/api' + +/** + * The private read contract's wire types, mapped back onto the shapes the feed + * UI already renders. + * + * A permissioned-space record URI is not an at-uri, so the appview cannot + * return one inside `app.bsky.feed.defs#postView`, whose `uri` is declared + * `format: at-uri`. Its private endpoints therefore answer in + * `community.blacksky.feed.defs`, which is structurally the same but declares + * every URI-bearing field a plain string. + * + * These are the same objects under different `$type`s, so the mapping is a + * rename: the alternative is a parallel renderer for private posts, which + * would drift from the public one. Nothing here parses a URI — the whole point + * of the custom types is that these URIs must never reach `AtUri`. + */ + +const DEFS = 'community.blacksky.feed.defs' + +const TYPE_MAP: Record = { + [`${DEFS}#spacePostView`]: 'app.bsky.feed.defs#postView', + [`${DEFS}#spaceRecordView`]: 'app.bsky.embed.record#view', + [`${DEFS}#spaceViewRecord`]: 'app.bsky.embed.record#viewRecord', + [`${DEFS}#spaceViewNotFound`]: 'app.bsky.embed.record#viewNotFound', + [`${DEFS}#spaceViewBlocked`]: 'app.bsky.embed.record#viewBlocked', + [`${DEFS}#spaceRecordWithMediaView`]: 'app.bsky.embed.recordWithMedia#view', + [`${DEFS}#spaceThreadItemPost`]: 'app.bsky.unspecced.defs#threadItemPost', + [`${DEFS}#spaceThreadItemNotFound`]: + 'app.bsky.unspecced.defs#threadItemNotFound', + [`${DEFS}#spaceThreadItemBlocked`]: + 'app.bsky.unspecced.defs#threadItemBlocked', +} + +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) +} + +function rename(value: unknown): unknown { + if (Array.isArray(value)) return value.map(rename) + if (!isPlainObject(value)) return value + const out: Record = {} + for (const [key, entry] of Object.entries(value)) { + out[key] = + key === '$type' && typeof entry === 'string' + ? (TYPE_MAP[entry] ?? entry) + : rename(entry) + } + return out +} + +/** + * A single item of a private feed page. Returns undefined when the item is not + * structurally a feed item, so one malformed row cannot take a page down. + */ +export function toFeedViewPost( + item: unknown, +): AppBskyFeedDefs.FeedViewPost | undefined { + if (!isPlainObject(item)) return undefined + const post = item.post + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(item) as AppBskyFeedDefs.FeedViewPost +} + +/** A private post view, from `getCommunityPost` or a private feed row. */ +export function toPostView( + post: unknown, +): AppBskyFeedDefs.PostView | undefined { + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(post) as AppBskyFeedDefs.PostView +} + +export type SpaceFeedPage = { + cursor?: string + feed: AppBskyFeedDefs.FeedViewPost[] +} + +/** The whole `getSpaceFeed` / community-feed body. */ +export function toSpaceFeedPage(body: unknown): SpaceFeedPage { + const source = isPlainObject(body) ? body : {} + const feed = Array.isArray(source.feed) ? source.feed : [] + return { + cursor: typeof source.cursor === 'string' ? source.cursor : undefined, + feed: feed + .map(toFeedViewPost) + .filter((item): item is AppBskyFeedDefs.FeedViewPost => !!item), + } +} + +/** The `thread`/`hasOtherReplies` body of a private thread read. */ +export function toSpaceThreadBody(body: unknown): unknown { + return rename(body) +} diff --git a/src/lib/api/space-write.ts b/src/lib/api/space-write.ts new file mode 100644 index 000000000..a541356ea --- /dev/null +++ b/src/lib/api/space-write.ts @@ -0,0 +1,233 @@ +import {type BskyAgent} from '@atproto/api' +import {TID} from '@atproto/common-web' + +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' + +/** + * Writes into a permissioned space. + * + * A space record goes to the account's **own PDS**. The local stack does not + * implement the 0016 PDS methods yet, so development may point these requests + * at its same-origin edge instead. That means **no `atproto-proxy` header**: + * proxying would send the write to the appview, which is not where this + * content lives. The request remains DPoP-signed by the agent, and the space + * host verifies that token itself. + * + * Records are sent as raw JSON rather than through typed builders. A like or a + * reply inside a space refers to other space records, whose URIs are not valid + * at-uris, so SDK-side lexicon validation would reject them; the receiving + * host stores records shape-agnostically and the syncers validate instead. + */ + +export const SPACE_CREATE_RECORD = 'com.atproto.space.createRecord' +export const SPACE_DELETE_RECORD = 'com.atproto.space.deleteRecord' +export const SPACE_GET_RECORD = 'com.atproto.space.getRecord' + +export const POST_COLLECTION = 'app.bsky.feed.post' +export const LIKE_COLLECTION = 'app.bsky.feed.like' + +const LOCAL_SPACE_XRPC_ORIGIN = + __DEV__ && + process.env.NODE_ENV !== 'test' && + process.env.EXPO_PUBLIC_SPACE_XRPC_ORIGIN + +export type SpaceWriteResult = { + uri: string + cid: string +} + +/** Raised when the PDS does not serve the space methods at all. */ +export class SpaceUnsupportedError extends Error { + constructor() { + super('This account’s server does not support private feeds yet') + this.name = 'SpaceUnsupportedError' + } +} + +async function spaceXrpc( + agent: BskyAgent, + method: string, + body: unknown, +): Promise { + const path = `/xrpc/${method}` + const url = LOCAL_SPACE_XRPC_ORIGIN + ? `${LOCAL_SPACE_XRPC_ORIGIN}${path}` + : path + return agent.fetchHandler(url, { + method: 'POST', + // Deliberately no `atproto-proxy`: this write belongs to the account's own + // PDS, not the appview. + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(body), + }) +} + +async function spaceQuery( + agent: BskyAgent, + method: string, + params: Record, +): Promise { + const path = `/xrpc/${method}?${new URLSearchParams(params)}` + const url = LOCAL_SPACE_XRPC_ORIGIN + ? `${LOCAL_SPACE_XRPC_ORIGIN}${path}` + : path + return agent.fetchHandler(url, {method: 'GET'}) +} + +function authenticatedRepo(agent: BskyAgent): string { + const repo = agent.session?.did + if (!repo) { + throw new Error('Sign in before writing to a private space') + } + return repo +} + +type XrpcErrorBody = {message?: string; error?: string} + +async function errorBody(response: Response): Promise { + return (await response.json().catch(() => ({}))) as XrpcErrorBody +} + +function failure(response: Response, body: XrpcErrorBody): never { + // A PDS that has never heard of the space methods answers 404 rather than an + // XRPC error, which is how a foreign-PDS account is recognised. + if (response.status === 404) { + throw new SpaceUnsupportedError() + } + throw new Error(body.message || body.error || `HTTP ${response.status}`) +} + +async function existingRecord( + agent: BskyAgent, + space: string, + repo: string, + collection: string, + rkey: string, +): Promise { + const response = await spaceQuery(agent, SPACE_GET_RECORD, { + space, + repo, + collection, + rkey, + }) + if (!response.ok) return failure(response, await errorBody(response)) + const data = (await response.json()) as Partial + if (!data.uri || !data.cid) { + throw new Error('Space host returned no record reference') + } + return {uri: data.uri, cid: data.cid} +} + +/** Create a record in the caller's permissioned repo within `space`. */ +export async function spaceCreateRecord( + agent: BskyAgent, + space: string, + collection: string, + record: Record, + rkey?: string, +): Promise { + const repo = authenticatedRepo(agent) + const recordKey = rkey ?? TID.nextStr() + const response = await spaceXrpc(agent, SPACE_CREATE_RECORD, { + space, + repo, + collection, + record, + rkey: recordKey, + }) + if (!response.ok) { + const body = await errorBody(response) + if (body.error === 'RecordExists') { + return existingRecord(agent, space, repo, collection, recordKey) + } + return failure(response, body) + } + const data = (await response.json()) as Partial + if (!data.uri || !data.cid) { + throw new Error('Space host returned no record reference') + } + return {uri: data.uri, cid: data.cid} +} + +/** Delete one of the caller's own records from `space`. */ +export async function spaceDeleteRecord( + agent: BskyAgent, + space: string, + collection: string, + rkey: string, +): Promise { + const repo = authenticatedRepo(agent) + const response = await spaceXrpc(agent, SPACE_DELETE_RECORD, { + space, + repo, + collection, + rkey, + }) + if (!response.ok) return failure(response, await errorBody(response)) +} + +/** + * Like a post inside a space. + * + * The like is written into the **permissioned repo**, never the public one: a + * public like whose subject is a space URI would announce that the private + * post exists, and to whom. + */ +export async function spaceLike( + agent: BskyAgent, + space: string, + subject: {uri: string; cid: string}, +): Promise { + return spaceCreateRecord(agent, space, LIKE_COLLECTION, { + $type: LIKE_COLLECTION, + subject: {uri: subject.uri, cid: subject.cid}, + createdAt: new Date().toISOString(), + }) +} + +/** Remove a like previously written into `space`. */ +export async function spaceUnlike( + agent: BskyAgent, + space: string, + likeUri: string, +): Promise { + const rkey = likeUri.split('/').pop() + if (!rkey) throw new Error(`Unusable like uri: ${likeUri}`) + return spaceDeleteRecord(agent, space, LIKE_COLLECTION, rkey) +} + +/* + * The three interactions below answer `null` for anything that is not a space + * record, so a caller reads as `spaceX(...) ?? publicX(...)`. The routing lives + * here rather than in the mutation hooks so it can be tested without them. + */ + +/** Like `uri` in its own space, or null if it is not a space record. */ +export function spaceLikeIfSpace( + agent: BskyAgent, + uri: string, + cid: string, +): Promise | null { + const ref = parseSpaceRecordUri(uri) + return ref ? spaceLike(agent, spaceUriOf(ref), {uri, cid}) : null +} + +/** Undo a like held in a space, or null if `likeUri` is not a space record. */ +export function spaceUnlikeIfSpace( + agent: BskyAgent, + likeUri: string, +): Promise | null { + const ref = parseSpaceRecordUri(likeUri) + return ref ? spaceUnlike(agent, spaceUriOf(ref), likeUri) : null +} + +/** Delete one's own space record, or null if `uri` is not one. */ +export function spaceDeleteIfSpace( + agent: BskyAgent, + uri: string, +): Promise | null { + const ref = parseSpaceRecordUri(uri) + return ref + ? spaceDeleteRecord(agent, spaceUriOf(ref), ref.collection, ref.rkey) + : null +} diff --git a/src/lib/constants.ts b/src/lib/constants.ts index cfdeae2f2..f9d7e16de 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -9,7 +9,9 @@ export const LOCAL_DEV_SERVICE = export const STAGING_SERVICE = 'https://staging.bsky.dev' export const BSKY_SERVICE = 'https://blacksky.app' export const BSKY_SERVICE_DID = 'did:web:bsky.social' -export const PUBLIC_BSKY_SERVICE = 'https://api.blacksky.community' +export const PUBLIC_BSKY_SERVICE = + (__DEV__ && process.env.EXPO_PUBLIC_APPVIEW_URL) || + 'https://api.blacksky.community' export const DEFAULT_SERVICE = BSKY_SERVICE // Handle suffixes that identify a Latinsky-community account living on the shared @@ -24,6 +26,7 @@ export const CHAT_SERVICE = 'https://api.bsky.chat' export const EMBED_SERVICE = 'https://embed.bsky.app' export const EMBED_SCRIPT = `${EMBED_SERVICE}/static/embed.js` export const BSKY_DOWNLOAD_URL = 'https://blacksky.community/download' +export const ACCOUNT_MIGRATION_URL = 'https://move.blacksky.community' export const STARTER_PACK_MAX_SIZE = 150 export const CARD_ASPECT_RATIO = 1200 / 630 diff --git a/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx b/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx new file mode 100644 index 000000000..b7cdb3006 --- /dev/null +++ b/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx @@ -0,0 +1,144 @@ +import {Pressable} from 'react-native' +import {fireEvent, render, waitFor} from '@testing-library/react-native' + +import {type FeedDescriptor} from '#/state/queries/post-feed' + +const mockRootOpenComposer = jest.fn() +const mockUseCommunityPostTargets = jest.fn() + +jest.mock('#/lib/hooks/useRequireEmailVerification', () => ({ + useRequireEmailVerification: + () => + (callback: (...args: unknown[]) => unknown) => + (...args: unknown[]) => + callback(...args), +})) +jest.mock('#/state/shell/composer', () => ({ + useOpenComposer: () => ({openComposer: mockRootOpenComposer}), +})) +jest.mock('#/state/queries/community-post-targets', () => ({ + useCommunityPostTargets: (feed?: unknown) => + mockUseCommunityPostTargets(feed), +})) +jest.mock('@lingui/react', () => ({Trans: () => null})) + +import {useOpenComposer} from '../useOpenComposer' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as FeedDescriptor +const PRIVATE_TARGET = { + feed: FEED_URI, + name: 'Private Test', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/space/community.blacksky.feed/private', + group: 'members', + createdAt: '2026-08-29T00:00:00.000Z', + }, +} +function OpenComposerHarness({ + opts = {}, + contextualFeed, +}: { + opts?: Record + contextualFeed?: FeedDescriptor +}) { + const {openComposer} = useOpenComposer(contextualFeed) + return ( + { + void openComposer(opts) + }} + /> + ) +} + +describe('useOpenComposer selected feed context', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseCommunityPostTargets.mockReturnValue({data: [PRIVATE_TARGET]}) + }) + + it('captures the active private Home feed for shared FAB/sidebar entry points', async () => { + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockUseCommunityPostTargets).toHaveBeenCalledWith(FEED_DESCRIPTOR) + expect(mockRootOpenComposer).toHaveBeenCalledWith({ + contextualCommunityFeedTarget: PRIVATE_TARGET, + }) + }) + }) + + it('opens from the global keyboard shortcut path outside a navigator', async () => { + const {getByLabelText} = render() + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockUseCommunityPostTargets).toHaveBeenCalledWith(undefined) + expect(mockRootOpenComposer).toHaveBeenCalledWith({}) + }) + }) + + it('waits for the authoritative target lookup before opening', async () => { + const refetch = jest.fn().mockResolvedValue({data: [PRIVATE_TARGET]}) + mockUseCommunityPostTargets.mockReturnValue({data: undefined, refetch}) + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(refetch).toHaveBeenCalled() + expect(mockRootOpenComposer).toHaveBeenCalledWith({ + contextualCommunityFeedTarget: PRIVATE_TARGET, + }) + }) + }) + + it('does not capture a selected feed without a permissioned space', async () => { + mockUseCommunityPostTargets.mockReturnValue({ + data: [ + { + ...PRIVATE_TARGET, + config: {...PRIVATE_TARGET.config, space: undefined}, + }, + ], + }) + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockRootOpenComposer).toHaveBeenCalledWith({}) + }) + }) + + it.each([ + ['a reply', {replyTo: {uri: 'at://did:plc:test/post/1'}}], + ['a quote', {quote: {uri: 'at://did:plc:test/post/1'}}], + ])('does not leak selected-feed context into %s', async (_, opts) => { + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockRootOpenComposer).toHaveBeenCalledWith(opts) + }) + }) +}) diff --git a/src/lib/hooks/useIntentHandler.ts b/src/lib/hooks/useIntentHandler.ts index 8fefe3a24..1a62362c1 100644 --- a/src/lib/hooks/useIntentHandler.ts +++ b/src/lib/hooks/useIntentHandler.ts @@ -5,7 +5,12 @@ import * as WebBrowser from 'expo-web-browser' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {parseLinkingUrl} from '#/lib/parseLinkingUrl' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + GROUP_INVITE_CODE_REGEX, + shouldHandleIncomingIntentUrl, +} from '#/lib/strings/url-helpers' +import {usePrefetchGroupInvitePreview} from '#/state/queries/group-invites' import {usePrefetchJoinLinkPreviews} from '#/state/queries/join-links' import {useSession} from '#/state/session' import {useSetActiveLanding} from '#/state/shell/landing' @@ -30,6 +35,7 @@ export function useIntentHandler() { const composeIntent = useComposeIntent() const verifyEmailIntent = useVerifyEmailIntent() const groupChatJoinIntent = useGroupChatJoinIntent() + const groupInviteIntent = useGroupInviteIntent() const {currentAccount} = useSession() const {tryApplyUpdate} = useApplyPullRequestOTAUpdate() @@ -40,20 +46,25 @@ export function useIntentHandler() { await WebBrowser.dismissBrowser().catch(() => {}) } - const referrerInfo = Referrer.getReferrerInfo() - if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { - ax.metric('deepLink:referrerReceived', { - to: url, - referrer: referrerInfo?.referrer, - hostname: referrerInfo?.hostname, - }) - } const urlp = parseLinkingUrl(url) const chatInviteMatch = urlp.pathname.match(CHAT_INVITE_CODE_REGEX) if (chatInviteMatch) { groupChatJoinIntent(chatInviteMatch[1], url) return } + const groupInviteMatch = urlp.pathname.match(GROUP_INVITE_CODE_REGEX) + if (groupInviteMatch) { + groupInviteIntent(groupInviteMatch[1]) + return + } + const referrerInfo = Referrer.getReferrerInfo() + if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { + ax.metric('deepLink:referrerReceived', { + to: url, + referrer: referrerInfo.referrer, + hostname: referrerInfo.hostname, + }) + } const [, intent, intentType] = urlp.pathname.split('/') // On native, our links look like blacksky://intent/SomeIntent, so we have to check the hostname for the @@ -97,24 +108,73 @@ export function useIntentHandler() { } } - if (incomingUrl) { - if (previousIntentUrl === incomingUrl) { + const processIncomingURL = (url: string, fromLinkEvent: boolean) => { + if ( + !shouldHandleIncomingIntentUrl(url, previousIntentUrl, fromLinkEvent) + ) { return } - handleIncomingURL(incomingUrl) - previousIntentUrl = incomingUrl + previousIntentUrl = url + void handleIncomingURL(url) } + + const subscription = Linking.addEventListener('url', event => { + processIncomingURL(event.url, true) + }) + if (incomingUrl) processIncomingURL(incomingUrl, false) + + return () => subscription.remove() }, [ incomingUrl, ax, composeIntent, verifyEmailIntent, groupChatJoinIntent, + groupInviteIntent, currentAccount, tryApplyUpdate, ]) } +export function useGroupInviteIntent() { + const closeAllActiveElements = useCloseAllActiveElements() + const {hasSession} = useSession() + const {groupInviteDialogControl: control, setGroupInviteState: setState} = + useIntentDialogs() + const {requestSwitchToAccount} = useLoggedOutViewControls() + const setActiveLanding = useSetActiveLanding() + const prefetchGroupInvitePreview = usePrefetchGroupInvitePreview() + + return useCallback( + (code: string) => { + closeAllActiveElements() + if (hasSession) { + setActiveLanding(undefined) + setState({code}) + const prefetch = prefetchGroupInvitePreview(code) + void Promise.race([ + prefetch, + new Promise(res => setTimeout(res, 200)), + ]).finally(() => control.open()) + } else { + // The original URL contains the bearer code. It is not needed to + // resume the landing flow and must not be retained in redirect state. + setActiveLanding({type: 'groupinvite', uri: '', code}) + requestSwitchToAccount({requestedAccount: 'groupinvite'}) + } + }, + [ + closeAllActiveElements, + hasSession, + setState, + prefetchGroupInvitePreview, + control, + setActiveLanding, + requestSwitchToAccount, + ], + ) +} + export function useComposeIntent() { const closeAllActiveElements = useCloseAllActiveElements() const {openComposer} = useOpenComposer() diff --git a/src/lib/hooks/useOpenComposer.tsx b/src/lib/hooks/useOpenComposer.tsx index f35b8722d..8088067b1 100644 --- a/src/lib/hooks/useOpenComposer.tsx +++ b/src/lib/hooks/useOpenComposer.tsx @@ -1,12 +1,54 @@ -import {useMemo} from 'react' +import {useCallback, useMemo} from 'react' import {Trans} from '@lingui/react/macro' +import {isSpaceBackedFeed} from '#/lib/api/community-feed' import {useRequireEmailVerification} from '#/lib/hooks/useRequireEmailVerification' -import {useOpenComposer as useRootOpenComposer} from '#/state/shell/composer' +import {useCommunityPostTargets} from '#/state/queries/community-post-targets' +import {type FeedDescriptor} from '#/state/queries/post-feed' +import { + type ComposerOpts, + useOpenComposer as useRootOpenComposer, +} from '#/state/shell/composer' -export function useOpenComposer() { - const {openComposer} = useRootOpenComposer() +export function useOpenComposer(contextualFeed?: FeedDescriptor) { + const {openComposer: rootOpenComposer} = useRootOpenComposer() const requireEmailVerification = useRequireEmailVerification() + const {data: postTargets, refetch: refetchPostTargets} = + useCommunityPostTargets(contextualFeed) + const openComposer = useCallback( + (opts: ComposerOpts) => { + if (!contextualFeed || opts.replyTo || opts.quote) { + rootOpenComposer(opts) + return + } + + const openWithTargets = ( + availableTargets: NonNullable, + ) => { + const contextualCommunityFeedTarget = availableTargets.find( + target => + `feedgen|${target.feed}` === contextualFeed && + isSpaceBackedFeed(target.config), + ) + + rootOpenComposer( + contextualCommunityFeedTarget + ? {...opts, contextualCommunityFeedTarget} + : opts, + ) + } + + if (postTargets) { + openWithTargets(postTargets) + } else { + void refetchPostTargets().then(result => { + openWithTargets(result.data ?? []) + }) + } + }, + [contextualFeed, postTargets, refetchPostTargets, rootOpenComposer], + ) + return useMemo(() => { return { openComposer: requireEmailVerification(openComposer, { diff --git a/src/lib/media/video/upload.shared.ts b/src/lib/media/video/upload.shared.ts index f8aaa1249..eb4c917b1 100644 --- a/src/lib/media/video/upload.shared.ts +++ b/src/lib/media/video/upload.shared.ts @@ -2,34 +2,11 @@ import {type AtpAgent} from '@atproto/api' import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {VIDEO_SERVICE_DID} from '#/lib/constants' import {UploadLimitError} from '#/lib/media/video/errors' -import {getServiceAuthAudFromUrl} from '#/lib/strings/url-helpers' import {createVideoAgent} from './util' -export async function getServiceAuthToken({ - agent, - aud, - lxm, - exp, -}: { - agent: AtpAgent - aud?: string - lxm: string - exp?: number -}) { - const pdsAud = getServiceAuthAudFromUrl(agent.dispatchUrl) - if (!pdsAud) { - throw new Error('Agent does not have a PDS URL') - } - const {data: serviceAuth} = await agent.com.atproto.server.getServiceAuth({ - aud: aud ?? pdsAud, - lxm, - exp, - }) - return serviceAuth.token -} - export async function getVideoUploadLimits(agent: AtpAgent, i18n: I18n) { const token = await getServiceAuthToken({ agent, diff --git a/src/lib/media/video/upload.ts b/src/lib/media/video/upload.ts index 721ee7f94..c3504d379 100644 --- a/src/lib/media/video/upload.ts +++ b/src/lib/media/video/upload.ts @@ -4,10 +4,11 @@ import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' import {nanoid} from 'nanoid/non-secure' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {AbortError} from '#/lib/async/cancelable' import {ServerError} from '#/lib/media/video/errors' import {type CompressedVideo} from '#/lib/media/video/types' -import {getServiceAuthToken, getVideoUploadLimits} from './upload.shared' +import {getVideoUploadLimits} from './upload.shared' import {createVideoEndpointUrl, mimeToExt} from './util' export async function uploadVideo({ diff --git a/src/lib/media/video/upload.web.ts b/src/lib/media/video/upload.web.ts index 59c6f6597..271827c5e 100644 --- a/src/lib/media/video/upload.web.ts +++ b/src/lib/media/video/upload.web.ts @@ -3,10 +3,11 @@ import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' import {nanoid} from 'nanoid/non-secure' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {AbortError} from '#/lib/async/cancelable' import {ServerError} from '#/lib/media/video/errors' import {type CompressedVideo} from '#/lib/media/video/types' -import {getServiceAuthToken, getVideoUploadLimits} from './upload.shared' +import {getVideoUploadLimits} from './upload.shared' import {createVideoEndpointUrl, mimeToExt} from './util' export async function uploadVideo({ diff --git a/src/lib/routes/links.ts b/src/lib/routes/links.ts index 549e179d4..b1a7e4d94 100644 --- a/src/lib/routes/links.ts +++ b/src/lib/routes/links.ts @@ -1,5 +1,7 @@ import {type AppBskyGraphDefs, AtUri} from '@atproto/api' +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' + export function makeProfileLink( info: { did: string @@ -10,6 +12,32 @@ export function makeProfileLink( return [`/profile`, info.did, ...segments].join('/') } +/** + * The in-app path for a post, whatever kind it is. + * + * Three shapes share one route: a public post, the community stub (which + * carries its collection as a query param), and a permissioned-space record, + * whose URI has seven segments and cannot be rebuilt from the path alone — + * so the space it belongs to rides along as `?space=`. The author DID and + * rkey come from the path exactly as they always have. + */ +export function postPermalink( + author: {did: string; handle: string}, + postUri: string, + ...segments: string[] +): string { + const spaceRef = parseSpaceRecordUri(postUri) + if (spaceRef) { + const base = makeProfileLink(author, 'post', spaceRef.rkey, ...segments) + return `${base}?space=${encodeURIComponent(spaceUriOf(spaceRef))}` + } + const urip = new AtUri(postUri) + const base = makeProfileLink(author, 'post', urip.rkey, ...segments) + return urip.collection && urip.collection !== 'app.bsky.feed.post' + ? `${base}?collection=${urip.collection}` + : base +} + export function makeCustomFeedLink( did: string, rkey: string, diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index 70c801d2d..a22e33c70 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -22,14 +22,20 @@ export type CommonNavigatorParams = { ProfileKnownFollowers: {name: string} ProfileSearch: {name: string; q?: string} ProfileList: {name: string; rkey: string} - PostThread: {name: string; rkey: string; collection?: string} - PostLikedBy: {name: string; rkey: string; collection?: string} - PostRepostedBy: {name: string; rkey: string; collection?: string} - PostQuotes: {name: string; rkey: string; collection?: string} + PostThread: {name: string; rkey: string; collection?: string; space?: string} + PostLikedBy: {name: string; rkey: string; collection?: string; space?: string} + PostRepostedBy: { + name: string + rkey: string + collection?: string + space?: string + } + PostQuotes: {name: string; rkey: string; collection?: string; space?: string} ProfileFeed: { name: string rkey: string feedCacheKey?: 'discover' | 'explore' | undefined + resolvedFeed?: string } ProfileFeedLikedBy: {name: string; rkey: string} ProfileLabelerLikedBy: {name: string} diff --git a/src/lib/strings/__tests__/group-invite-url.test.ts b/src/lib/strings/__tests__/group-invite-url.test.ts new file mode 100644 index 000000000..d5109c539 --- /dev/null +++ b/src/lib/strings/__tests__/group-invite-url.test.ts @@ -0,0 +1,29 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getGroupInviteCodeFromUrl, + GROUP_INVITE_CODE_REGEX, + isBskyGroupInviteUrl, +} from '../url-helpers' + +const CODE = 'a'.repeat(43) + +describe('group invite URLs', () => { + it('accepts the exact client deep-link shape', () => { + expect(GROUP_INVITE_CODE_REGEX.test(`/join/${CODE}`)).toBe(true) + expect( + getGroupInviteCodeFromUrl(`https://blacksky.community/join/${CODE}`), + ).toBe(CODE) + expect(isBskyGroupInviteUrl(`/join/${CODE}?from=message`)).toBe(true) + }) + + it.each([ + `/join/${'a'.repeat(42)}`, + `/join/${'a'.repeat(44)}`, + `/join/${'a'.repeat(42)}!`, + `/join/${'a'.repeat(42)}%2F`, + `/join/${'a'.repeat(43)}/extra`, + ])('rejects malformed group invite URL %s', url => { + expect(getGroupInviteCodeFromUrl(url)).toBeUndefined() + }) +}) diff --git a/src/lib/strings/__tests__/url-helpers.test.ts b/src/lib/strings/__tests__/url-helpers.test.ts new file mode 100644 index 000000000..ffc39a96a --- /dev/null +++ b/src/lib/strings/__tests__/url-helpers.test.ts @@ -0,0 +1,27 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getDeepLinkAnalyticsTarget, + shouldHandleIncomingIntentUrl, +} from '../url-helpers' + +const URL = 'https://bsky.app/join/' + 'a'.repeat(43) + +describe('incoming intent URL handling', () => { + it('reopens the same group invite for a new warm-app link event', () => { + expect(shouldHandleIncomingIntentUrl(URL, URL, true)).toBe(true) + expect(shouldHandleIncomingIntentUrl(URL, URL, false)).toBe(false) + }) + + it('continues deduplicating repeated non-invite URLs', () => { + const url = 'https://bsky.app/profile/alice' + expect(shouldHandleIncomingIntentUrl(url, url, true)).toBe(false) + }) + + it('removes group invite bearer codes from analytics targets', () => { + expect(getDeepLinkAnalyticsTarget(URL)).toBe('group-invite') + expect(getDeepLinkAnalyticsTarget('https://bsky.app/profile/alice')).toBe( + 'https://bsky.app/profile/alice', + ) + }) +}) diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts index 9b07881b9..48568f703 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -2,6 +2,7 @@ import {AtUri} from '@atproto/api' import {parse} from 'psl' import TLDs from 'tlds' +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext' import {BSKY_SERVICE} from '#/lib/constants' import {isInvalidHandle} from '#/lib/strings/handles' @@ -215,6 +216,53 @@ export function isBskyStarterPackUrl(url: string): boolean { // Invite codes are 7 alphanumeric characters long, supporting up to 10 here to future-proof. export const CHAT_INVITE_CODE_REGEX = /^\/chat\/([a-zA-Z0-9]{7,10})$/ +export const GROUP_INVITE_CODE_REGEX = /^\/join\/([A-Za-z0-9_-]{43})$/ + +/** + * Linking can emit an already-seen URL again after a warm-app tap. The hook + * listener is the authoritative event source for that case; the URL-state + * effect must not process the same event a second time. + */ +export function shouldHandleIncomingIntentUrl( + url: string, + previousUrl: string, + fromLinkEvent: boolean, +): boolean { + if (url !== previousUrl) return true + try { + const isGroupInvite = GROUP_INVITE_CODE_REGEX.test( + new URL(url, BSKY_APP_HOST).pathname, + ) + return isGroupInvite && fromLinkEvent + } catch { + return false + } +} + +export function getGroupInviteCodeFromUrl(url: string): string | undefined { + let pathname: string + if (isBskyAppUrl(url)) { + try { + pathname = new URL(url).pathname + } catch { + return undefined + } + } else if (url.startsWith('/')) { + pathname = url.split('?')[0].split('#')[0] + } else { + return undefined + } + return pathname.match(GROUP_INVITE_CODE_REGEX)?.[1] +} + +export function isBskyGroupInviteUrl(url: string): boolean { + return getGroupInviteCodeFromUrl(url) !== undefined +} + +export function getDeepLinkAnalyticsTarget(url: string): string { + return isBskyGroupInviteUrl(url) ? 'group-invite' : url +} + export function getChatInviteCodeFromUrl(url: string): string | undefined { let pathname: string if (isBskyAppUrl(url)) { @@ -284,6 +332,13 @@ export function postUriToRelativePath( uri: string, options?: {handle?: string}, ): string | undefined { + // A space record URI has seven segments and misparses in AtUri. Its author + // and rkey come out of the URI itself; the space rides in the query, which + // is what rebuilds it on the way back. + const spaceRef = parseSpaceRecordUri(uri) + if (spaceRef) { + return `/profile/${spaceRef.authorDid}/post/${spaceRef.rkey}?space=${encodeURIComponent(spaceUriOf(spaceRef))}` + } try { const {hostname, rkey, collection} = new AtUri(uri) const handleOrDid = diff --git a/src/screens/GroupInviteLanding.tsx b/src/screens/GroupInviteLanding.tsx new file mode 100644 index 000000000..202e7ebd4 --- /dev/null +++ b/src/screens/GroupInviteLanding.tsx @@ -0,0 +1,108 @@ +import {useEffect} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' + +import { + groupInviteErrorCopy, + shouldTrackGroupInviteOpened, +} from '#/lib/api/group-invite-ui' +import {useGroupInvitePreviewQuery} from '#/state/queries/group-invites' +import {useActiveGroupInvite} from '#/state/shell/landing' +import {LoggedOutScreenState} from '#/view/com/auth/LoggedOut' +import {Logo} from '#/view/icons/Logo' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' + +export function GroupInviteLanding({ + setScreenState, +}: { + setScreenState: (state: LoggedOutScreenState) => void +}) { + const {t: l} = useLingui() + const ax = useAnalytics() + const t = useTheme() + const landing = useActiveGroupInvite() + const {data, error, isPending, refetch} = useGroupInvitePreviewQuery( + landing?.code, + ) + + useEffect(() => { + if (landing?.code && shouldTrackGroupInviteOpened(landing.code)) { + ax.metric('groupInvite:opened', {hasSession: false}) + } + }, [ax, landing?.code]) + + return ( + + + + {isPending ? ( + + ) : error ? ( + + {groupInviteErrorCopy(error)} + + + ) : data ? ( + <> + + Group invite + + + {data.group.displayName} + + + {data.community.name} + + + ) : null} + + + + + + + ) +} diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index 18a26767e..7e1e51a54 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -26,22 +26,26 @@ import * as TextField from '#/components/forms/TextField' import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At' import {Loader} from '#/components/Loader' import {Text} from '#/components/Typography' +import {IS_E2E} from '#/env' import {FormContainer} from './FormContainer' export const LoginForm = ({ error, + serviceUrl, serviceDescription, initialHandle, setError, onPressBack, }: { error: string + serviceUrl: string serviceDescription: ComAtprotoServerDescribeServer.OutputSchema | undefined initialHandle: string setError: (v: string) => void onPressBack: () => void }) => { const [isProcessing, setIsProcessing] = useState(false) + const [password, setPassword] = useState('') const [awaitingRedirect, setAwaitingRedirect] = useState(false) const abortRef = useRef(null) const processingRef = useRef(false) @@ -144,6 +148,31 @@ export const LoginForm = ({ } const signInWithIdentifier = async (identifier: string) => { + if (IS_E2E) { + if (!password) { + setError(_(msg`Please enter your password`)) + return + } + setIsProcessing(true) + try { + await login({service: serviceUrl, identifier, password}, 'LoginForm') + } catch (e) { + const errMsg = String(e) + if (isNetworkError(e)) { + setError( + _( + msg`Unable to contact your service. Please check your Internet connection.`, + ), + ) + } else { + setError(cleanError(errMsg)) + } + } finally { + setIsProcessing(false) + } + return + } + const client = getOAuthClient() const controller = Platform.OS === 'android' ? new AbortController() : null if (controller) { @@ -249,6 +278,27 @@ export const LoginForm = ({ + {IS_E2E && ( + + + Password + + + void onPressNext()} + editable={!isProcessing} + /> + + + )} {handleOptions && ( diff --git a/src/screens/Login/index.tsx b/src/screens/Login/index.tsx index 6456a8704..d1b20ca4e 100644 --- a/src/screens/Login/index.tsx +++ b/src/screens/Login/index.tsx @@ -129,6 +129,7 @@ export const Login = ({ content = ( export const PostLikedByScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostLikedByRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostLikedBy']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let likeCount if (post) { diff --git a/src/screens/Post/PostQuotes.tsx b/src/screens/Post/PostQuotes.tsx index 7328c6ad9..f4d09ca33 100644 --- a/src/screens/Post/PostQuotes.tsx +++ b/src/screens/Post/PostQuotes.tsx @@ -1,19 +1,44 @@ import {Plural, Trans} from '@lingui/react/macro' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' import {usePostQuery} from '#/state/queries/post' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostQuotes as PostQuotesComponent} from '#/view/com/post-thread/PostQuotes' import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostQuotesScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostQuotesRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostQuotes']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let quoteCount if (post) { diff --git a/src/screens/Post/PostRepostedBy.tsx b/src/screens/Post/PostRepostedBy.tsx index 40a7beb7e..8d1c2c4bd 100644 --- a/src/screens/Post/PostRepostedBy.tsx +++ b/src/screens/Post/PostRepostedBy.tsx @@ -1,19 +1,44 @@ import {Plural, Trans} from '@lingui/react/macro' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' import {usePostQuery} from '#/state/queries/post' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostRepostedBy as PostRepostedByComponent} from '#/view/com/post-thread/PostRepostedBy' import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostRepostedByScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostRepostedByRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostRepostedBy']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let quoteCount if (post) { diff --git a/src/screens/PostThread/components/ThreadItemAnchor.tsx b/src/screens/PostThread/components/ThreadItemAnchor.tsx index 8e772da18..55898d6cb 100644 --- a/src/screens/PostThread/components/ThreadItemAnchor.tsx +++ b/src/screens/PostThread/components/ThreadItemAnchor.tsx @@ -4,14 +4,16 @@ import { AppBskyFeedDefs, AppBskyFeedPost, type AppBskyFeedThreadgate, - AtUri, RichText as RichTextAPI, } from '@atproto/api' import {Plural, Trans, useLingui} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' +import {postUriAuthor} from '#/lib/api/space-permalink' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {makeProfileLink, postPermalink} from '#/lib/routes/links' import {sanitizeDisplayName} from '#/lib/strings/display-names' import {sanitizeHandle} from '#/lib/strings/handles' import {niceDate} from '#/lib/strings/time' @@ -196,17 +198,17 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ [record], ) - const threadRootUri = record.reply?.root?.uri || post.uri const authorHref = makeProfileLink(post.author) const isThreadAuthor = getThreadAuthor(post, record) === currentAccount?.did const statHref = useCallback( (suffix: string) => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey, suffix) - return urip.collection === 'community.blacksky.feed.post' - ? `${link}?collection=${urip.collection}` - : link + // Space likes and quotes have permission-aware endpoints. Reposts remain + // unsupported, so their count deliberately has no destination. + if (isSpaceRecordUri(post.uri) && suffix === 'reposted-by') { + return undefined + } + return postPermalink(post.author, post.uri, suffix) }, [post.uri, post.author], ) @@ -219,8 +221,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ }) const additionalPostAlerts: AppModerationCause[] = useMemo(() => { const isPostHiddenByThreadgate = threadgateHiddenReplies.has(post.uri) - const isControlledByViewer = - new AtUri(threadRootUri).host === currentAccount?.did + const isControlledByViewer = isThreadAuthor return isControlledByViewer && isPostHiddenByThreadgate ? [ { @@ -230,7 +231,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ }, ] : [] - }, [post, currentAccount?.did, threadgateHiddenReplies, threadRootUri]) + }, [post, currentAccount?.did, isThreadAuthor, threadgateHiddenReplies]) const onlyFollowersCanReply = !!threadgateRecord?.allow?.find( rule => rule.$type === 'app.bsky.feed.threadgate#followerRule', ) @@ -258,6 +259,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', @@ -446,7 +448,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ t.atoms.border_contrast_low, ]}> {post.repostCount != null && post.repostCount !== 0 ? ( - + @@ -462,12 +464,12 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.quoteCount != null && post.quoteCount !== 0 && !post.viewer?.embeddingDisabled ? ( - + @@ -483,10 +485,10 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.likeCount != null && post.likeCount !== 0 ? ( - + @@ -502,7 +504,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.bookmarkCount != null && post.bookmarkCount !== 0 ? ( ) } + +/** + * A stat that links to its own screen when there is one to link to. + * + * Space posts have no liked-by / reposted-by / quotes screens, so the count + * renders as plain text rather than a link that would 400. + */ +function StatLink({ + to, + label, + children, +}: { + to?: string + label: string + children: React.ReactElement +}) { + if (!to) return children + return ( + + {children} + + ) +} diff --git a/src/screens/PostThread/components/ThreadItemPost.tsx b/src/screens/PostThread/components/ThreadItemPost.tsx index 5ee7d85b2..b15d7c719 100644 --- a/src/screens/PostThread/components/ThreadItemPost.tsx +++ b/src/screens/PostThread/components/ThreadItemPost.tsx @@ -8,9 +8,10 @@ import { } from '@atproto/api' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -211,10 +212,7 @@ const ThreadItemPostInner = memo(function ThreadItemPostInner({ ) const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(post.author, post.uri) }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, @@ -244,6 +242,7 @@ const ThreadItemPostInner = memo(function ThreadItemPostInner({ embed: post.embed, moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', diff --git a/src/screens/PostThread/components/ThreadItemTreePost.tsx b/src/screens/PostThread/components/ThreadItemTreePost.tsx index c1125110b..adeda3ec5 100644 --- a/src/screens/PostThread/components/ThreadItemTreePost.tsx +++ b/src/screens/PostThread/components/ThreadItemTreePost.tsx @@ -8,9 +8,10 @@ import { } from '@atproto/api' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -273,10 +274,7 @@ const ThreadItemTreePostInner = memo(function ThreadItemTreePostInner({ ) const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(post.author, post.uri) }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, @@ -306,6 +304,7 @@ const ThreadItemTreePostInner = memo(function ThreadItemTreePostInner({ embed: post.embed, moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', diff --git a/src/screens/PostThread/index.tsx b/src/screens/PostThread/index.tsx index 64d652972..02c885525 100644 --- a/src/screens/PostThread/index.tsx +++ b/src/screens/PostThread/index.tsx @@ -10,6 +10,7 @@ import {useWindowDimensions, View} from 'react-native' import Animated, {useAnimatedStyle} from 'react-native-reanimated' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -131,6 +132,7 @@ export function PostThread({uri}: {uri: string}) { embed: post.embed, moderation: anchor.moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: optimisticOnPostReply, logContext: 'PostReply', diff --git a/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx b/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx new file mode 100644 index 000000000..0070bcff4 --- /dev/null +++ b/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx @@ -0,0 +1,149 @@ +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {fireEvent, render, waitFor} from '@testing-library/react-native' + +import {type FeedSourceFeedInfo} from '#/state/queries/feed' +import {type UsePreferencesQueryResponse} from '#/state/queries/preferences' + +const mockOpenComposer = jest.fn() +const mockUseOpenComposer = jest.fn((_feed?: string) => ({ + openComposer: mockOpenComposer, +})) +const mockSetParams = jest.fn() +const mockUseResolveUriQuery = jest.fn() + +jest.mock('react-native-reanimated', () => ({ + useAnimatedRef: () => ({current: null}), +})) +jest.mock('@react-navigation/native', () => ({ + useIsFocused: () => true, +})) +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: (message: {message?: string} | string) => + typeof message === 'string' ? message : (message.message ?? ''), + }), +})) +jest.mock('#/lib/hooks/useOpenComposer', () => ({ + useOpenComposer: (feed?: string) => mockUseOpenComposer(feed), +})) +jest.mock('#/lib/hooks/useSetTitle', () => ({useSetTitle: jest.fn()})) +jest.mock('#/state/events', () => ({listenSoftReset: jest.fn()})) +jest.mock('#/state/feed-feedback', () => ({ + FeedFeedbackProvider: ({children}: React.PropsWithChildren) => children, + useFeedFeedback: () => ({}), +})) +jest.mock('#/state/queries/feed', () => ({ + useFeedSourceInfoQuery: () => ({data: undefined}), +})) +jest.mock('#/state/queries/preferences', () => ({ + usePreferencesQuery: () => ({data: undefined}), +})) +jest.mock('#/state/queries/post-feed', () => ({ + RQKEY: jest.fn(() => ['post-feed']), +})) +jest.mock('#/state/queries/resolve-uri', () => ({ + useResolveUriQuery: (...args: unknown[]) => mockUseResolveUriQuery(...args), +})) +jest.mock('#/state/session', () => ({ + useSession: () => ({hasSession: true}), +})) +jest.mock('#/view/com/posts/PostFeed', () => ({PostFeed: () => null})) +jest.mock('#/view/com/util/EmptyState', () => ({EmptyState: () => null})) +jest.mock('#/view/com/util/error/ErrorScreen', () => ({ + ErrorScreen: () => null, +})) +jest.mock('#/view/com/util/LoadingPlaceholder', () => ({ + PostFeedLoadingPlaceholder: () => null, +})) +jest.mock('#/view/com/util/load-latest/LoadLatestBtn', () => ({ + LoadLatestBtn: () => null, +})) +jest.mock('#/view/com/util/fab/FAB', () => { + const {Pressable} = require('react-native') + return { + FAB: ({onPress, testID}: {onPress: () => void; testID: string}) => ( + + ), + } +}) +jest.mock('#/screens/Profile/components/ProfileFeedHeader', () => ({ + ProfileFeedHeader: () => null, + ProfileFeedHeaderSkeleton: () => null, +})) +jest.mock('#/components/Layout', () => { + const {View} = require('react-native') + return { + Screen: ({children}: React.PropsWithChildren) => {children}, + Content: ({children}: React.PropsWithChildren) => {children}, + } +}) +jest.mock('#/alf', () => ({ + useTheme: () => ({palette: {white: '#fff'}}), +})) + +import {ProfileFeedScreen, ProfileFeedScreenInner} from '../index' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as const +const FEED_INFO = { + type: 'feed', + uri: FEED_URI, + feedDescriptor: FEED_DESCRIPTOR, + displayName: 'Private Test', + contentMode: undefined, +} as unknown as FeedSourceFeedInfo + +function wrapper({children}: React.PropsWithChildren) { + const client = new QueryClient() + return {children} +} + +describe('ProfileFeed composer context', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseResolveUriQuery.mockReturnValue({ + data: {uri: FEED_URI}, + error: undefined, + refetch: jest.fn(), + isRefetching: false, + }) + }) + + it('passes the resolved active feed to the ProfileFeed FAB composer', () => { + const {getByTestId} = render( + , + {wrapper}, + ) + + expect(mockUseOpenComposer).toHaveBeenCalledWith(FEED_DESCRIPTOR) + fireEvent.press(getByTestId('composeFAB')) + expect(mockOpenComposer).toHaveBeenCalledWith({logContext: 'Fab'}) + }) + + it('publishes the resolved descriptor for the desktop sidebar composer', async () => { + const props = { + route: { + params: {name: 'did:plc:test', rkey: 'private'}, + }, + navigation: {setParams: mockSetParams}, + } as unknown as React.ComponentProps + + render(, {wrapper}) + + await waitFor(() => { + expect(mockSetParams).toHaveBeenCalledWith({ + resolvedFeed: FEED_DESCRIPTOR, + }) + }) + }) +}) diff --git a/src/screens/Profile/ProfileFeed/index.tsx b/src/screens/Profile/ProfileFeed/index.tsx index 6ed5f4b5b..a2f93d622 100644 --- a/src/screens/Profile/ProfileFeed/index.tsx +++ b/src/screens/Profile/ProfileFeed/index.tsx @@ -64,6 +64,13 @@ export function ProfileFeedScreen(props: Props) { refetch, isRefetching, } = useResolveUriQuery(uri) + const resolvedFeed = resolvedUri + ? (`feedgen|${resolvedUri.uri}` as FeedDescriptor) + : undefined + + useEffect(() => { + props.navigation.setParams({resolvedFeed}) + }, [props.navigation, resolvedFeed]) if (error && !isRefetching) { return ( @@ -133,13 +140,13 @@ export function ProfileFeedScreenInner({ }) { const {_} = useLingui() const {hasSession} = useSession() - const {openComposer} = useOpenComposer() const isScreenFocused = useIsFocused() const t = useTheme() useSetTitle(feedInfo?.displayName) const feed = `feedgen|${feedInfo.uri}` as FeedDescriptor + const {openComposer} = useOpenComposer(feed) const [hasNew, setHasNew] = useState(false) const [isScrolledDown, setIsScrolledDown] = useState(false) diff --git a/src/screens/VideoFeed/index.tsx b/src/screens/VideoFeed/index.tsx index 7e760b88d..ba8e02e19 100644 --- a/src/screens/VideoFeed/index.tsx +++ b/src/screens/VideoFeed/index.tsx @@ -43,6 +43,7 @@ import { } from '@react-navigation/native' import {type NativeStackScreenProps} from '@react-navigation/native-stack' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {HITSLOP_20} from '#/lib/constants' import {useHaptics} from '#/lib/haptics' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' @@ -772,6 +773,7 @@ function Overlay({ author: post.author, embed: post.embed, langs: record?.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) diff --git a/src/state/cache/__tests__/post-shadow-space.test.ts b/src/state/cache/__tests__/post-shadow-space.test.ts new file mode 100644 index 000000000..17f9f06de --- /dev/null +++ b/src/state/cache/__tests__/post-shadow-space.test.ts @@ -0,0 +1,75 @@ +import {type AppBskyFeedDefs} from '@atproto/api' +import {QueryClient} from '@tanstack/react-query' + +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) +jest.mock('#/state/queries/notifications/feed', () => ({ + findAllPostsInQueryData: function* () {}, +})) +jest.mock('#/view/com/posts/PostFeedErrorMessage', () => ({ + KnownError: {FeedSignedInOnly: 'FeedSignedInOnly'}, +})) +jest.mock('#/state/queries/usePostThread', () => ({ + usePostThreadContext: jest.fn(), +})) + +import { + dangerousGetPostShadow, + updatePostShadow, +} from '#/state/cache/post-shadow' +import {RQKEY_ROOT as POST_FEED_QUERY_KEY_ROOT} from '#/state/queries/post-feed' + +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' +const LEGACY_POST = 'at://did:plc:alice/community.blacksky.feed.post/3klegacy' +const SPACE_POST = + 'at://did:plc:space/space/community.blacksky.feed/test/did:plc:alice/app.bsky.feed.post/3kspace' + +function post(uri: string): AppBskyFeedDefs.PostView { + return { + uri, + cid: 'bafyrei post', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'hello'}, + indexedAt: '2026-08-27T00:00:00.000Z', + } +} + +function cachePost( + queryClient: QueryClient, + cachedPost: AppBskyFeedDefs.PostView, +) { + queryClient.setQueryData([POST_FEED_QUERY_KEY_ROOT, 'following'], { + pages: [{feed: [{post: cachedPost}]}], + pageParams: [undefined], + }) +} + +describe('post shadow URI matching', () => { + it.each([PUBLIC_POST, LEGACY_POST])( + 'preserves ordinary matching for %s', + uri => { + const queryClient = new QueryClient() + const cachedPost = post(uri) + cachePost(queryClient, cachedPost) + + expect(() => + updatePostShadow(queryClient, uri, {likeUri: `${uri}/like`}), + ).not.toThrow() + expect(dangerousGetPostShadow(cachedPost)?.likeUri).toBe(`${uri}/like`) + }, + ) + + it('updates a cached permissioned-space post without parsing its URI', () => { + const queryClient = new QueryClient() + const cachedPost = post(SPACE_POST) + cachePost(queryClient, cachedPost) + + expect(() => + updatePostShadow(queryClient, SPACE_POST, { + likeUri: 'at://did:plc:alice/app.bsky.feed.like/3klike', + }), + ).not.toThrow() + expect(dangerousGetPostShadow(cachedPost)?.likeUri).toBe( + 'at://did:plc:alice/app.bsky.feed.like/3klike', + ) + }) +}) diff --git a/src/state/queries/__tests__/community-post-targets.test.tsx b/src/state/queries/__tests__/community-post-targets.test.tsx new file mode 100644 index 000000000..3c3d10ee1 --- /dev/null +++ b/src/state/queries/__tests__/community-post-targets.test.tsx @@ -0,0 +1,92 @@ +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {renderHook, waitFor} from '@testing-library/react-native' + +const mockFetchCommunityFeedTarget = jest.fn() +const mockUseSavedFeeds = jest.fn() +const mockAgent = {} + +jest.mock('#/lib/api/community-feed', () => ({ + fetchCommunityFeedTarget: (...args: unknown[]) => + mockFetchCommunityFeedTarget(...args), +})) +jest.mock('#/state/queries/feed', () => ({ + useSavedFeeds: () => mockUseSavedFeeds(), +})) +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, + useSession: () => ({currentAccount: {did: 'did:plc:test'}}), +})) + +import {useCommunityPostTargets} from '../community-post-targets' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as const +const TARGET = { + feed: FEED_URI, + name: 'Generator fallback', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/community.blacksky.space/private', + group: 'members', + createdAt: '2026-08-30T00:00:00.000Z', + }, +} + +function wrapper({children}: React.PropsWithChildren) { + const client = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + return {children} +} + +describe('useCommunityPostTargets', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseSavedFeeds.mockReturnValue({data: {feeds: []}, isLoading: false}) + mockFetchCommunityFeedTarget.mockResolvedValue(TARGET) + }) + + it('authoritatively resolves an unsaved writable contextual feed', async () => { + const {result} = renderHook( + () => useCommunityPostTargets(FEED_DESCRIPTOR), + {wrapper}, + ) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledTimes(1) + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledWith( + mockAgent, + FEED_URI, + ) + expect(result.current.data).toEqual([TARGET]) + }) + + it('deduplicates the current feed against saved targets and keeps its saved display name', async () => { + mockUseSavedFeeds.mockReturnValue({ + data: { + feeds: [ + { + type: 'feed', + view: {uri: FEED_URI, displayName: 'Saved display name'}, + }, + ], + }, + isLoading: false, + }) + const {result} = renderHook( + () => useCommunityPostTargets(FEED_DESCRIPTOR), + {wrapper}, + ) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledTimes(1) + expect(result.current.data).toEqual([ + {...TARGET, name: 'Saved display name'}, + ]) + }) +}) diff --git a/src/state/queries/__tests__/space-engagement-routing.test.ts b/src/state/queries/__tests__/space-engagement-routing.test.ts new file mode 100644 index 000000000..4055f47d9 --- /dev/null +++ b/src/state/queries/__tests__/space-engagement-routing.test.ts @@ -0,0 +1,106 @@ +import {type BskyAgent} from '@atproto/api' + +const mockGetSpacePostLikes = jest.fn() +const mockGetSpacePostQuotes = jest.fn() + +jest.mock('#/lib/api/community', () => ({ + getSpacePostLikes: (...args: unknown[]) => mockGetSpacePostLikes(...args), + getSpacePostQuotes: (...args: unknown[]) => mockGetSpacePostQuotes(...args), +})) +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) + +import {fetchLikedByPage} from '../post-liked-by' +import {fetchPostQuotesPage} from '../post-quotes' +import {fetchRepostedByPage} from '../post-reposted-by' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kpost` +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kpost' +const LEGACY_POST = 'at://did:plc:alice/community.blacksky.feed.post/3kpost' + +function mockAgent() { + const getLikes = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, likes: []}, + }) + const getQuotes = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, posts: []}, + }) + const getRepostedBy = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, repostedBy: []}, + }) + mockGetSpacePostLikes.mockResolvedValue({uri: SPACE_POST, likes: []}) + mockGetSpacePostQuotes.mockResolvedValue({uri: SPACE_POST, posts: []}) + const agent = { + getLikes, + getRepostedBy, + api: {app: {bsky: {feed: {getQuotes}}}}, + } as unknown as BskyAgent + return {agent, getLikes, getQuotes, getRepostedBy} +} + +describe('post engagement routing', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it.each([PUBLIC_POST, LEGACY_POST])( + 'keeps likes for %s on the standard endpoint', + async uri => { + const {agent, getLikes} = mockAgent() + + await fetchLikedByPage(agent, uri, 'next') + + expect(getLikes).toHaveBeenCalledWith({ + uri, + limit: 30, + cursor: 'next', + }) + expect(mockGetSpacePostLikes).not.toHaveBeenCalled() + }, + ) + + it.each([PUBLIC_POST, LEGACY_POST])( + 'keeps quotes for %s on the standard endpoint', + async uri => { + const {agent, getQuotes} = mockAgent() + + await fetchPostQuotesPage(agent, uri, 'next') + + expect(getQuotes).toHaveBeenCalledWith({ + uri, + limit: 30, + cursor: 'next', + }) + expect(mockGetSpacePostQuotes).not.toHaveBeenCalled() + }, + ) + + it('uses only the permission-aware endpoints for space engagement', async () => { + const {agent, getLikes, getQuotes} = mockAgent() + + await fetchLikedByPage(agent, SPACE_POST) + await fetchPostQuotesPage(agent, SPACE_POST) + + expect(getLikes).not.toHaveBeenCalled() + expect(getQuotes).not.toHaveBeenCalled() + expect(mockGetSpacePostLikes).toHaveBeenCalledWith(agent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + expect(mockGetSpacePostQuotes).toHaveBeenCalledWith(agent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + + it('never calls the standard repost endpoint for a space URI', async () => { + const {agent, getRepostedBy} = mockAgent() + + await expect(fetchRepostedByPage(agent, SPACE_POST)).rejects.toThrow( + 'Reposts are not supported for private space posts', + ) + expect(getRepostedBy).not.toHaveBeenCalled() + }) +}) diff --git a/src/state/queries/bookmarks/useBookmarksQuery.ts b/src/state/queries/bookmarks/useBookmarksQuery.ts index 3e8e87a13..706d50e94 100644 --- a/src/state/queries/bookmarks/useBookmarksQuery.ts +++ b/src/state/queries/bookmarks/useBookmarksQuery.ts @@ -2,7 +2,6 @@ import { type $Typed, type AppBskyBookmarkGetBookmarks, AppBskyFeedDefs, - AtUri, } from '@atproto/api' import { type InfiniteData, @@ -12,9 +11,9 @@ import { } from '@tanstack/react-query' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' import * as bsky from '#/types/bsky' @@ -129,7 +128,7 @@ export function* findAllPostsInQueryData( >({ queryKey: [bookmarksQueryKeyRoot], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { @@ -145,12 +144,12 @@ export function* findAllPostsInQueryData( ) continue - if (didOrHandleUriMatches(atUri, bookmark.item)) { + if (matches(bookmark.item)) { yield bookmark.item } const quotedPost = getEmbeddedPost(bookmark.item.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/community-feed-permissions.ts b/src/state/queries/community-feed-permissions.ts new file mode 100644 index 000000000..7479767b8 --- /dev/null +++ b/src/state/queries/community-feed-permissions.ts @@ -0,0 +1,23 @@ +import {useQuery} from '@tanstack/react-query' + +import { + type CommunityFeedPermission, + fetchFeedPermissions, +} from '#/lib/api/community-feed' +import {useAgent, useSession} from '#/state/session' + +export const feedPermissionsQueryKey = ( + did: string | undefined, + feed: string, +) => ['community-feed-permissions', did ?? '', feed] + +export function useFeedPermissionsQuery(feed: string) { + const agent = useAgent() + const {currentAccount} = useSession() + return useQuery({ + queryKey: feedPermissionsQueryKey(currentAccount?.did, feed), + enabled: !!currentAccount?.did && !!feed, + staleTime: 60 * 1000, + queryFn: () => fetchFeedPermissions(agent, feed), + }) +} diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 1753c6180..e518019e0 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -18,13 +18,15 @@ import { import {communityXrpc} from '#/lib/api/community' import {FeedTuner} from '#/lib/api/feed-manip' +import {spaceRecordAuthor} from '#/lib/api/space-uri' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {STALE} from '#/state/queries' import {usePreferencesQuery} from '#/state/queries/preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' @@ -79,7 +81,7 @@ export function useCommunityFeedQuery(actor: string | undefined) { if (!res.ok) { throw new Error(`getCommunityFeed failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -116,7 +118,7 @@ export function useCommunityTimelineQuery(enabled: boolean) { if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -144,8 +146,8 @@ export async function fetchCommunityTimelineHead( if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - const page = jsonToLex(await res.json()) as CommunityFeedPage - return page.feed?.find(surfacesInCommunityFeed) + const page = toSpaceFeedPage(jsonToLex(await res.json())) + return page.feed.find(surfacesInCommunityFeed) } // A reply only resurfaces its thread when the root author is @@ -171,7 +173,11 @@ export function surfacesInCommunityFeed( if (!item.reason && !AppBskyFeedDefs.isPostView(item.reply?.parent)) { return false } - return new AtUri(reply.root.uri).host === item.post.author.did + // A space record URI names its author in its own segment; `AtUri` would + // report the space authority as the host and never match. + const rootAuthor = + spaceRecordAuthor(reply.root.uri) ?? new AtUri(reply.root.uri).host + return rootAuthor === item.post.author.did } const COMMUNITY_POST_RQKEY_ROOT = 'community-post' @@ -193,10 +199,10 @@ export function useCommunityPostQuery(uri: string | undefined) { if (!res.ok) { throw new Error(`getCommunityPost failed: ${res.status}`) } - const data = jsonToLex(await res.json()) as { - post: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post }, enabled: !!uri, }) @@ -321,7 +327,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) // Search both actor feeds and timeline const queryDatas = [ @@ -345,25 +351,25 @@ export function* findAllPostsInQueryData( if (!item?.post) { continue } - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } // Check for quoted posts in embeds const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } // Reply-context rows render in slices too; without these, likes on // a parent/root row never reach the shadow cache. if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } } diff --git a/src/state/queries/community-post-targets.ts b/src/state/queries/community-post-targets.ts new file mode 100644 index 000000000..cc17df19c --- /dev/null +++ b/src/state/queries/community-post-targets.ts @@ -0,0 +1,48 @@ +import {useQuery} from '@tanstack/react-query' + +import { + type CommunityFeedTarget, + fetchCommunityFeedTarget, +} from '#/lib/api/community-feed' +import {STALE} from '#/state/queries' +import {useSavedFeeds} from '#/state/queries/feed' +import {type FeedDescriptor} from '#/state/queries/post-feed' +import {useAgent, useSession} from '#/state/session' + +export function useCommunityPostTargets(contextualFeed?: FeedDescriptor) { + const agent = useAgent() + const {currentAccount} = useSession() + const {data, isLoading} = useSavedFeeds() + const feeds = (data?.feeds ?? []).filter(item => item.type === 'feed') + const candidates = new Map( + feeds.map(item => [item.view.uri, item.view.displayName] as const), + ) + if (contextualFeed?.startsWith('feedgen|')) { + const currentFeedUri = contextualFeed.slice('feedgen|'.length) + if (!candidates.has(currentFeedUri)) { + candidates.set(currentFeedUri, undefined) + } + } + const candidateFeeds = [...candidates] + + return useQuery({ + queryKey: [ + 'community-post-targets', + currentAccount?.did ?? '', + candidateFeeds, + ], + enabled: !!currentAccount?.did && !isLoading, + staleTime: STALE.MINUTES.FIVE, + queryFn: async () => { + const targets = await Promise.all( + candidateFeeds.map(async ([feed, displayName]) => { + const target = await fetchCommunityFeedTarget(agent, feed) + return target ? {...target, name: displayName ?? target.name} : null + }), + ) + return targets.filter( + (target): target is CommunityFeedTarget => target !== null, + ) + }, + }) +} diff --git a/src/state/queries/explore-feed-previews.tsx b/src/state/queries/explore-feed-previews.tsx index acbc4ee7e..7ba6a6c4d 100644 --- a/src/state/queries/explore-feed-previews.tsx +++ b/src/state/queries/explore-feed-previews.tsx @@ -2,7 +2,6 @@ import {useMemo, useRef} from 'react' import { type AppBskyActorDefs, AppBskyFeedDefs, - AtUri, moderatePost, } from '@atproto/api' import {msg} from '@lingui/core/macro' @@ -24,9 +23,9 @@ import { } from '#/state/queries/post-feed' import {usePreferencesQuery} from '#/state/queries/preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' @@ -350,7 +349,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData< InfiniteData<{ @@ -366,36 +365,33 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const item of page.posts) { - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } const parentQuotedPost = getEmbeddedPost(item.reply.parent.embed) - if ( - parentQuotedPost && - didOrHandleUriMatches(atUri, parentQuotedPost) - ) { + if (parentQuotedPost && matches(parentQuotedPost)) { yield embedViewRecordToPostView(parentQuotedPost) } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } const rootQuotedPost = getEmbeddedPost(item.reply.root.embed) - if (rootQuotedPost && didOrHandleUriMatches(atUri, rootQuotedPost)) { + if (rootQuotedPost && matches(rootQuotedPost)) { yield embedViewRecordToPostView(rootQuotedPost) } } diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index f016461b3..0f5a38ed1 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -21,6 +21,10 @@ import { useQueryClient, } from '@tanstack/react-query' +import { + type CommunityFeedConfig, + fetchCommunityFeedConfig, +} from '#/lib/api/community-feed' import {getProxyHeadersForFeed} from '#/lib/api/feed/utils' import {searchAppviewOpts} from '#/lib/api/search-routing' import {useBrand} from '#/lib/community/BrandContext' @@ -223,6 +227,20 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) { }) } +export const communityFeedConfigQueryKey = (uri: string) => [ + 'community-feed-config', + uri, +] + +export function useCommunityFeedConfigQuery({uri}: {uri: string}) { + const agent = useAgent() + return useQuery({ + queryKey: communityFeedConfigQueryKey(uri), + staleTime: STALE.INFINITY, + queryFn: () => fetchCommunityFeedConfig(agent, uri), + }) +} + // HACK // the protocol doesn't yet tell us which feeds are personalized // this list is used to filter out feed recommendations from logged out users diff --git a/src/state/queries/group-invites.ts b/src/state/queries/group-invites.ts new file mode 100644 index 000000000..47e5fc3bb --- /dev/null +++ b/src/state/queries/group-invites.ts @@ -0,0 +1,42 @@ +import {useCallback} from 'react' +import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' + +import {acceptGroupInvite, previewGroupInvite} from '#/lib/api/group-invites' +import {useAgent} from '#/state/session' +import {createQueryKey} from './util' + +export const groupInvitePreviewQueryKey = (code: string) => + createQueryKey('group-invite-preview', {code}, {persistedVersion: 1}) + +export function useGroupInvitePreviewQuery(code?: string) { + return useQuery({ + queryKey: groupInvitePreviewQueryKey(code ?? ''), + queryFn: () => { + if (!code) throw new Error('Missing invite code') + return previewGroupInvite(code) + }, + enabled: Boolean(code), + retry: false, + }) +} + +export function usePrefetchGroupInvitePreview() { + const queryClient = useQueryClient() + return useCallback( + (code: string) => + queryClient.prefetchQuery({ + queryKey: groupInvitePreviewQueryKey(code), + queryFn: () => previewGroupInvite(code), + staleTime: 15_000, + }), + [queryClient], + ) +} + +export function useAcceptGroupInviteMutation() { + const agent = useAgent() + return useMutation({ + mutationFn: ({code, communityDid}: {code: string; communityDid: string}) => + acceptGroupInvite({code, communityDid, agent}), + }) +} diff --git a/src/state/queries/notifications/__tests__/space-subjects.test.ts b/src/state/queries/notifications/__tests__/space-subjects.test.ts new file mode 100644 index 000000000..27dccdc4a --- /dev/null +++ b/src/state/queries/notifications/__tests__/space-subjects.test.ts @@ -0,0 +1,70 @@ +import {type AtpAgent} from '@atproto/api' + +const mockCommunityXrpc = jest.fn() + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) +jest.mock('#/lib/api/community', () => ({ + communityXrpc: (...args: unknown[]) => mockCommunityXrpc(...args), +})) +jest.mock('#/state/queries/profile', () => ({precacheProfile: jest.fn()})) + +import {type FeedNotification} from '../types' +import {fetchSubjects} from '../util' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' + +const subject = (rkey: string): FeedNotification => { + const uri = `${SPACE}/did:plc:alice/app.bsky.feed.post/${rkey}` + return { + subjectUri: uri, + notification: {}, + } as FeedNotification +} + +describe('space notification subject hydration', () => { + it('routes like, reply, and quote subjects through getCommunityPost', async () => { + const notifications = [subject('like'), subject('reply'), subject('quote')] + mockCommunityXrpc.mockImplementation( + (_agent: AtpAgent, _method: string, opts: {params: {uri: string}}) => + Promise.resolve( + new Response( + JSON.stringify({ + post: { + uri: opts.params.uri, + cid: 'bafypost', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'private'}, + indexedAt: '2026-08-27T12:00:00.000Z', + }, + }), + ), + ), + ) + const getPosts = jest.fn() + const getStarterPacks = jest.fn().mockResolvedValue({ + data: {starterPacks: []}, + }) + const agent = { + app: { + bsky: { + feed: {getPosts}, + graph: {getStarterPacks}, + }, + }, + } as unknown as AtpAgent + + const result = await fetchSubjects(agent, notifications) + + expect(mockCommunityXrpc).toHaveBeenCalledTimes(3) + expect(mockCommunityXrpc.mock.calls.map(([, method]) => method)).toEqual([ + 'community.blacksky.feed.getCommunityPost', + 'community.blacksky.feed.getCommunityPost', + 'community.blacksky.feed.getCommunityPost', + ]) + expect(getPosts).not.toHaveBeenCalled() + expect(result.posts.size).toBe(3) + }) +}) diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index a81802e56..97091e31e 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -17,12 +17,7 @@ */ import {useCallback, useEffect, useMemo, useRef} from 'react' -import { - AppBskyFeedDefs, - AppBskyFeedPost, - AtUri, - moderatePost, -} from '@atproto/api' +import {AppBskyFeedDefs, AppBskyFeedPost, moderatePost} from '@atproto/api' import { type InfiniteData, type QueryClient, @@ -38,9 +33,9 @@ import {useAgent} from '#/state/session' import {useThreadgateHiddenReplyUris} from '#/state/threadgate-hidden-replies' import type * as bsky from '#/types/bsky' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '../util' import {type FeedPage} from './types' import {useUnreadNotificationsApi} from './unread' @@ -280,7 +275,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData>({ queryKey: [RQKEY_ROOT], @@ -293,14 +288,14 @@ export function* findAllPostsInQueryData( for (const page of queryData?.pages) { for (const item of page.items) { if (item.type !== 'starterpack-joined') { - if (item.subject && didOrHandleUriMatches(atUri, item.subject)) { + if (item.subject && matches(item.subject)) { yield item.subject } } if (AppBskyFeedDefs.isPostView(item.subject)) { const quotedPost = getEmbeddedPost(item.subject?.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index e9264d9ff..59e8f5d5f 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -16,6 +16,8 @@ import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' import {communityXrpc} from '#/lib/api/community' +import {isCommunityPostUri} from '#/lib/api/community-post' +import {toPostView} from '#/lib/api/space-views' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' @@ -215,7 +217,7 @@ export function groupNotifications( return groupedNotifs } -async function fetchSubjects( +export async function fetchSubjects( agent: AtpAgent, groupedNotifs: FeedNotification[], ): Promise<{ @@ -226,10 +228,11 @@ async function fetchSubjects( const communityPostUris = new Set() const packUris = new Set() for (const notif of groupedNotifs) { - if (notif.subjectUri?.includes('community.blacksky.feed.post')) { - communityPostUris.add(notif.subjectUri) - } else if (notif.subjectUri?.includes('app.bsky.feed.post')) { - postUris.add(notif.subjectUri) + const subjectUri = notif.subjectUri + if (subjectUri && isCommunityPostUri(subjectUri)) { + communityPostUris.add(subjectUri) + } else if (subjectUri?.includes('app.bsky.feed.post')) { + postUris.add(subjectUri) } else if ( notif.notification.reasonSubject?.includes('app.bsky.graph.starterpack') ) { @@ -253,10 +256,8 @@ async function fetchSubjects( }) .then(async res => { if (!res.ok) return undefined - const data = jsonToLex(await res.json()) as { - post?: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + return toPostView(data.post) }) .catch(() => undefined), ), diff --git a/src/state/queries/pinned-post.ts b/src/state/queries/pinned-post.ts index 09a0b4c9b..8b7a69736 100644 --- a/src/state/queries/pinned-post.ts +++ b/src/state/queries/pinned-post.ts @@ -2,6 +2,7 @@ import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {useMutation, useQueryClient} from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {logger} from '#/logger' import {RQKEY as FEED_RQKEY} from '#/state/queries/post-feed' import * as Toast from '#/components/Toast' @@ -27,6 +28,12 @@ export function usePinnedPostMutation() { action: 'pin' | 'unpin' }) => { const pinCurrentPost = action === 'pin' + // The pin lands in the public profile record, so a space URI here would + // publish a private post's existence and author. The menu already hides + // the control; this is the invariant at the write. + if (isSpaceRecordUri(postUri)) { + throw new Error('A post in a private space cannot be pinned') + } let prevPinnedPost: string | undefined try { updatePostShadow(queryClient, postUri, {pinned: pinCurrentPost}) diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index b0c226b23..f7163ea76 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -5,7 +5,6 @@ import { AppBskyFeedDefs, type AppBskyFeedPost, type AtpAgent, - AtUri, moderatePost, type ModerationDecision, type ModerationPrefs, @@ -40,9 +39,9 @@ import {useFeedTuners} from '../preferences/feed-tuners' import {useModerationOpts} from '../preferences/moderation-opts' import {usePreferencesQuery} from './preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' type ActorDid = string @@ -500,7 +499,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData< InfiniteData @@ -513,36 +512,33 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const item of page.feed) { - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } const parentQuotedPost = getEmbeddedPost(item.reply.parent.embed) - if ( - parentQuotedPost && - didOrHandleUriMatches(atUri, parentQuotedPost) - ) { + if (parentQuotedPost && matches(parentQuotedPost)) { yield embedViewRecordToPostView(parentQuotedPost) } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } const rootQuotedPost = getEmbeddedPost(item.reply.root.embed) - if (rootQuotedPost && didOrHandleUriMatches(atUri, rootQuotedPost)) { + if (rootQuotedPost && matches(rootQuotedPost)) { yield embedViewRecordToPostView(rootQuotedPost) } } diff --git a/src/state/queries/post-liked-by.ts b/src/state/queries/post-liked-by.ts index e02de6153..63c31d28b 100644 --- a/src/state/queries/post-liked-by.ts +++ b/src/state/queries/post-liked-by.ts @@ -1,4 +1,8 @@ -import {type AppBskyActorDefs, type AppBskyFeedGetLikes} from '@atproto/api' +import { + type AppBskyActorDefs, + type AppBskyFeedGetLikes, + type BskyAgent, +} from '@atproto/api' import { type InfiniteData, type QueryClient, @@ -6,6 +10,8 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {getSpacePostLikes} from '#/lib/api/community' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -15,6 +21,26 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'liked-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchLikedByPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + return getSpacePostLikes(agent, { + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + } + const res = await agent.getLikes({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function useLikedByQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -26,12 +52,7 @@ export function useLikedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.getLikes({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchLikedByPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, diff --git a/src/state/queries/post-quotes.ts b/src/state/queries/post-quotes.ts index 1d0fa07e8..633b79f50 100644 --- a/src/state/queries/post-quotes.ts +++ b/src/state/queries/post-quotes.ts @@ -3,7 +3,7 @@ import { AppBskyEmbedRecord, type AppBskyFeedDefs, type AppBskyFeedGetQuotes, - AtUri, + type BskyAgent, } from '@atproto/api' import { type InfiniteData, @@ -12,11 +12,13 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {getSpacePostQuotes} from '#/lib/api/community' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' const PAGE_SIZE = 30 @@ -25,6 +27,26 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'post-quotes' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchPostQuotesPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + return getSpacePostQuotes(agent, { + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + } + const res = await agent.api.app.bsky.feed.getQuotes({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function usePostQuotesQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -36,12 +58,7 @@ export function usePostQuotesQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.api.app.bsky.feed.getQuotes({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchPostQuotesPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -103,19 +120,19 @@ export function* findAllPostsInQueryData( >({ queryKey: [RQKEY_ROOT], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { continue } for (const page of queryData?.pages) { for (const post of page.posts) { - if (didOrHandleUriMatches(atUri, post)) { + if (matches(post)) { yield post } const quotedPost = getEmbeddedPost(post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/post-reposted-by.ts b/src/state/queries/post-reposted-by.ts index 814a815aa..1c3a37e34 100644 --- a/src/state/queries/post-reposted-by.ts +++ b/src/state/queries/post-reposted-by.ts @@ -1,6 +1,7 @@ import { type AppBskyActorDefs, type AppBskyFeedGetRepostedBy, + type BskyAgent, } from '@atproto/api' import { type InfiniteData, @@ -9,6 +10,7 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -18,6 +20,22 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'post-reposted-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchRepostedByPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + throw new Error('Reposts are not supported for private space posts') + } + const res = await agent.getRepostedBy({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function usePostRepostedByQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -29,16 +47,11 @@ export function usePostRepostedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.getRepostedBy({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchRepostedByPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, - enabled: !!resolvedUri, + enabled: !!resolvedUri && !isSpaceRecordUri(resolvedUri), }) } diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index 7b936299a..e7eeaed67 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -8,6 +8,14 @@ import { } from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {setSpaceThreadMute} from '#/lib/api/community-thread' +import {isSpaceRecordUri} from '#/lib/api/space-uri' +import { + spaceDeleteIfSpace, + spaceLikeIfSpace, + spaceUnlikeIfSpace, +} from '#/lib/api/space-write' import {useToggleMutationQueue} from '#/lib/hooks/useToggleMutationQueue' import {updatePostShadow} from '#/state/cache/post-shadow' import {type Shadow} from '#/state/cache/types' @@ -28,6 +36,12 @@ export function usePostQuery(uri: string | undefined) { queryFn: async () => { if (!uri) throw new Error('[unreachable] No URI provided') + // Checked before AtUri, which misparses a space URI, and before + // getPosts, whose uris are at-uris. + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } + const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { @@ -65,6 +79,9 @@ export function useGetPost() { return queryClient.fetchQuery({ queryKey: RQKEY(uri || ''), async queryFn() { + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { @@ -216,7 +233,10 @@ function usePostLikeMutation( : undefined, feedDescriptor: feedDescriptor, }) - return agent.like(uri, cid, via) + // A like on a permissioned post is written into the space, never the + // public repo: a public like naming a space URI would announce that the + // private post exists, and who can see it. + return spaceLikeIfSpace(agent, uri, cid) ?? agent.like(uri, cid, via) }, }) } @@ -236,7 +256,7 @@ function usePostUnlikeMutation( logContext, feedDescriptor, }) - return agent.deleteLike(likeUri) + return spaceUnlikeIfSpace(agent, likeUri) ?? agent.deleteLike(likeUri) }, }) } @@ -356,6 +376,12 @@ export function usePostDeleteMutation() { const agent = useAgent() return useMutation({ mutationFn: async ({uri}) => { + // Checked before AtUri sees the URI: a space URI misparses there. + const spaceDelete = spaceDeleteIfSpace(agent, uri) + if (spaceDelete) { + await spaceDelete + return + } const parsedUri = new AtUri(uri) if (parsedUri.collection === COMMUNITY_POST_COLLECTION) { // Both deletes are idempotent, so ordering is safe and a retry after @@ -440,7 +466,10 @@ function useThreadMuteMutation() { Error, {uri: string} // the root post's uri >({ - mutationFn: ({uri}) => { + mutationFn: async ({uri}) => { + if (isSpaceRecordUri(uri)) { + return setSpaceThreadMute(agent, uri, true) + } return agent.api.app.bsky.graph.muteThread({root: uri}) }, }) @@ -449,7 +478,10 @@ function useThreadMuteMutation() { function useThreadUnmuteMutation() { const agent = useAgent() return useMutation<{}, Error, {uri: string}>({ - mutationFn: ({uri}) => { + mutationFn: async ({uri}) => { + if (isSpaceRecordUri(uri)) { + return setSpaceThreadMute(agent, uri, false) + } return agent.api.app.bsky.graph.unmuteThread({root: uri}) }, }) diff --git a/src/state/queries/resolve-uri.ts b/src/state/queries/resolve-uri.ts index b27e6ef7d..8d8d37999 100644 --- a/src/state/queries/resolve-uri.ts +++ b/src/state/queries/resolve-uri.ts @@ -46,18 +46,21 @@ const resolvedDidQueryOptions = ( }) export function useResolveUriQuery(uri: string | undefined) { - const urip = new AtUri(uri || '') - const host = urip.host + const urip = uri ? new AtUri(uri) : undefined + const host = urip?.host const agent = useAgent() const {getUnstableProfile} = useUnstableProfileViewCache() return useQuery({ ...resolvedDidQueryOptions(agent, getUnstableProfile, host), - select: did => ({ - did, - uri: AtUri.make(did, urip.collection, urip.rkey).toString(), - }), + select: did => { + if (!urip) return undefined + return { + did, + uri: AtUri.make(did, urip.collection, urip.rkey).toString(), + } + }, }) } diff --git a/src/state/queries/search-posts.ts b/src/state/queries/search-posts.ts index 95cc5f24a..97a4d3bab 100644 --- a/src/state/queries/search-posts.ts +++ b/src/state/queries/search-posts.ts @@ -3,7 +3,6 @@ import { type AppBskyActorDefs, type AppBskyFeedDefs, type AppBskyFeedSearchPosts, - AtUri, moderatePost, } from '@atproto/api' import { @@ -17,9 +16,9 @@ import {searchAppviewOpts} from '#/lib/api/search-routing' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useAgent} from '#/state/session' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' const searchPostsQueryKeyRoot = 'search-posts' @@ -154,7 +153,7 @@ export function* findAllPostsInQueryData( >({ queryKey: [searchPostsQueryKeyRoot], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { @@ -162,12 +161,12 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const post of page.posts) { - if (didOrHandleUriMatches(atUri, post)) { + if (matches(post)) { yield post } const quotedPost = getEmbeddedPost(post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/usePostThread/index.ts b/src/state/queries/usePostThread/index.ts index f27b532f1..62a939869 100644 --- a/src/state/queries/usePostThread/index.ts +++ b/src/state/queries/usePostThread/index.ts @@ -1,6 +1,8 @@ import {useCallback, useMemo, useState} from 'react' import {useQuery, useQueryClient} from '@tanstack/react-query' +import {fetchCommunityThread} from '#/lib/api/community-thread' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useThreadPreferences} from '#/state/queries/preferences/useThreadPreferences' @@ -82,15 +84,27 @@ export function usePostThread({anchor}: {anchor?: string}) { enabled: isThreadPreferencesLoaded && !!anchor && !!moderationOpts, queryKey: postThreadQueryKey, async queryFn(ctx) { - const {data} = await agent.app.bsky.unspecced.getPostThreadV2( - { - anchor: anchor!, - branchingFactor: view === 'linear' ? LINEAR_VIEW_BF : TREE_VIEW_BF, - below, - sort: sort, - }, - pinnedOpts, - ) + const branchingFactor = view === 'linear' ? LINEAR_VIEW_BF : TREE_VIEW_BF + // A space record cannot be an anchor on the standard endpoint: that + // parameter is an at-uri and a space URI is not one. The community + // endpoint answers with the same item shape. + const data = isSpaceRecordUri(anchor) + ? await fetchCommunityThread(agent, { + anchor: anchor!, + branchingFactor, + below, + }) + : ( + await agent.app.bsky.unspecced.getPostThreadV2( + { + anchor: anchor!, + branchingFactor, + below, + sort: sort, + }, + pinnedOpts, + ) + ).data /* * Initialize `ctx.meta` to track if we know we have additional replies diff --git a/src/state/queries/usePostThread/queryCache.ts b/src/state/queries/usePostThread/queryCache.ts index 5f5481d65..93401cbcf 100644 --- a/src/state/queries/usePostThread/queryCache.ts +++ b/src/state/queries/usePostThread/queryCache.ts @@ -6,7 +6,6 @@ import { AppBskyUnspeccedDefs, type AppBskyUnspeccedGetPostThreadOtherV2, type AppBskyUnspeccedGetPostThreadV2, - AtUri, } from '@atproto/api' import {type QueryClient, useQueryClient} from '@tanstack/react-query' @@ -32,9 +31,9 @@ import { import {getRootPostAtUri} from '#/state/queries/usePostThread/utils' import {postViewToThreadPlaceholder} from '#/state/queries/usePostThread/views' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' export function createCacheMutator({ @@ -277,7 +276,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData({ queryKey: [postThreadQueryKeyRoot], @@ -290,12 +289,12 @@ export function* findAllPostsInQueryData( for (const item of thread) { if (AppBskyUnspeccedDefs.isThreadItemPost(item.value)) { - if (didOrHandleUriMatches(atUri, item.value.post)) { + if (matches(item.value.post)) { yield item.value.post } const qp = getEmbeddedPost(item.value.post.embed) - if (qp && didOrHandleUriMatches(atUri, qp)) { + if (qp && matches(qp)) { yield embedViewRecordToPostView(qp) } } diff --git a/src/state/queries/util.ts b/src/state/queries/util.ts index 7ea54745c..90c0520d1 100644 --- a/src/state/queries/util.ts +++ b/src/state/queries/util.ts @@ -4,7 +4,7 @@ import { AppBskyEmbedRecordWithMedia, type AppBskyFeedDefs, AppBskyFeedPost, - type AtUri, + AtUri, } from '@atproto/api' import { type InfiniteData, @@ -12,6 +12,7 @@ import { type QueryKey, } from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import * as bsky from '#/types/bsky' export type StructuredQueryKey> = readonly [ @@ -102,6 +103,27 @@ export function didOrHandleUriMatches( return atUri.host === record.author.handle && record.uri.endsWith(atUri.rkey) } +/** + * A predicate matching cached posts against a target URI, for shadow-cache + * updates (like, delete, ...). + * + * A permissioned-space record URI is not an at-uri: `AtUri` misparses it, so + * its `host` becomes the space authority and its `rkey` the space type. The + * handle branch of `didOrHandleUriMatches` would then compare the wrong + * segments and could match a different post entirely, which is why the space + * form is matched by exact equality — it is always fully qualified — and never + * constructed as an `AtUri` at all. + */ +export function makeUriMatcher(uri: string) { + if (isSpaceRecordUri(uri)) { + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + record.uri === uri + } + const atUri = new AtUri(uri) + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + didOrHandleUriMatches(atUri, record) +} + export function getEmbeddedPost( v: unknown, ): AppBskyEmbedRecord.ViewRecord | undefined { diff --git a/src/state/session/__tests__/strip-appview-proxy-test.ts b/src/state/session/__tests__/strip-appview-proxy-test.ts index 710757332..4a8fb2f3c 100644 --- a/src/state/session/__tests__/strip-appview-proxy-test.ts +++ b/src/state/session/__tests__/strip-appview-proxy-test.ts @@ -19,6 +19,12 @@ function headerValue( const GET_PREFS = 'https://pds.example.com/xrpc/app.bsky.actor.getPreferences' const PUT_PREFS = 'https://pds.example.com/xrpc/app.bsky.actor.putPreferences' const TIMELINE = 'https://pds.example.com/xrpc/app.bsky.feed.getTimeline' +const SPACE_CREATE = + 'https://pds.example.com/xrpc/com.atproto.space.createRecord' +const SPACE_DELETE = + 'https://pds.example.com/xrpc/com.atproto.space.deleteRecord' +const SPACE_GET = 'https://pds.example.com/xrpc/com.atproto.space.getRecord' +const SPACE_OTHER = 'https://pds.example.com/xrpc/com.atproto.space.listRecords' describe('stripAppviewProxyForPdsLocalMethods', () => { it('strips the appview proxy header on getPreferences', () => { @@ -61,4 +67,23 @@ describe('stripAppviewProxyForPdsLocalMethods', () => { ) expect(headerValue(out, PROXY)).toBeNull() }) + + it.each([SPACE_CREATE, SPACE_DELETE, SPACE_GET])( + 'strips the appview proxy header on %s', + url => { + const out = stripAppviewProxyForPdsLocalMethods( + url, + getInit({[PROXY]: PROXY_VALUE, authorization: 'DPoP tok'}), + ) + expect(headerValue(out, PROXY)).toBeNull() + expect(headerValue(out, 'authorization')).toBe('DPoP tok') + }, + ) + + it('does not strip unlisted space methods', () => { + const init = getInit({[PROXY]: PROXY_VALUE}) + const out = stripAppviewProxyForPdsLocalMethods(SPACE_OTHER, init) + expect(out).toBe(init) + expect(headerValue(out, PROXY)).toBe(PROXY_VALUE) + }) }) diff --git a/src/state/session/agent.ts b/src/state/session/agent.ts index f21750f8b..0f483282a 100644 --- a/src/state/session/agent.ts +++ b/src/state/session/agent.ts @@ -457,6 +457,9 @@ export class Agent extends BaseAgent { const PDS_LOCAL_PROXY_EXEMPT_METHODS = [ 'app.bsky.actor.getPreferences', 'app.bsky.actor.putPreferences', + 'com.atproto.space.createRecord', + 'com.atproto.space.deleteRecord', + 'com.atproto.space.getRecord', ] export function stripAppviewProxyForPdsLocalMethods( diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index e4ee5ed9d..2317be2c1 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -9,6 +9,22 @@ import { } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + export const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' // The redirect deep-link can arrive with either a single (`:/oauth`) or double @@ -79,7 +95,7 @@ const BSKY_OAUTH_CLIENT = new ExpoOAuthClient({ application_type: 'native', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: debugFetch, ...sessionHooks, }) diff --git a/src/state/session/oauth-client.web.ts b/src/state/session/oauth-client.web.ts index a38b0ebb3..b512bcf2f 100644 --- a/src/state/session/oauth-client.web.ts +++ b/src/state/session/oauth-client.web.ts @@ -9,6 +9,22 @@ import { import {type Metrics} from '#/analytics/metrics' import {OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + function getOAuthBaseUrl(): string { if (typeof window !== 'undefined') { return window.location.origin @@ -162,7 +178,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) @@ -184,7 +200,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) diff --git a/src/state/shell/composer/index.tsx b/src/state/shell/composer/index.tsx index 9a1e212f4..265e93d5a 100644 --- a/src/state/shell/composer/index.tsx +++ b/src/state/shell/composer/index.tsx @@ -9,6 +9,7 @@ import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {useQueryClient} from '@tanstack/react-query' +import {type CommunityFeedTarget} from '#/lib/api/community-feed' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {postUriToRelativePath, toBskyAppUrl} from '#/lib/strings/url-helpers' import {purgeTemporaryImageFiles} from '#/state/gallery' @@ -27,6 +28,7 @@ export interface ComposerOptsPostRef { author: AppBskyActorDefs.ProfileViewBasic embed?: AppBskyFeedDefs.PostView['embed'] moderation?: ModerationDecision + communitySpace?: string } export type OnPostSuccessData = @@ -55,6 +57,7 @@ export interface ComposerOpts { videoUri?: {uri: string; width: number; height: number} openGallery?: boolean logContext?: ComposerLogContext + contextualCommunityFeedTarget?: CommunityFeedTarget } type StateContext = ComposerOpts | undefined diff --git a/src/state/shell/landing.tsx b/src/state/shell/landing.tsx index f071c79e3..f69dc5ab0 100644 --- a/src/state/shell/landing.tsx +++ b/src/state/shell/landing.tsx @@ -1,4 +1,4 @@ -import {createContext, useContext, useState} from 'react' +import {createContext, useContext, useEffect, useState} from 'react' import {logger} from '#/logger' @@ -14,17 +14,70 @@ type GroupChatJoinRequestLanding = { code: string } -type LandingType = StarterPackLanding | GroupChatJoinRequestLanding | undefined +type GroupInviteLanding = { + type: 'groupinvite' + uri: string + code: string +} + +type LandingType = + | StarterPackLanding + | GroupChatJoinRequestLanding + | GroupInviteLanding + | undefined type SetContext = (v: LandingType) => void +const PENDING_GROUP_INVITE_KEY = 'blacksky.pendingGroupInvite' + +function readPendingGroupInvite(): GroupInviteLanding | undefined { + if (typeof window === 'undefined') return undefined + try { + const value: unknown = JSON.parse( + window.sessionStorage.getItem(PENDING_GROUP_INVITE_KEY) ?? 'null', + ) + const code = + value && typeof value === 'object' + ? (value as {code?: unknown}).code + : undefined + if ( + value && + typeof value === 'object' && + (value as {type?: unknown}).type === 'groupinvite' && + typeof code === 'string' && + /^[A-Za-z0-9_-]{43}$/.test(code) + ) { + return {type: 'groupinvite', uri: '', code} + } + } catch { + // Session storage is a best-effort OAuth resume aid. + } + return undefined +} + const stateContext = createContext(undefined) stateContext.displayName = 'ActiveLandingStateContext' const setContext = createContext((_: LandingType) => {}) setContext.displayName = 'ActiveLandingSetContext' export function Provider({children}: {children: React.ReactNode}) { - const [state, setState] = useState() + const [state, setState] = useState(readPendingGroupInvite) + + useEffect(() => { + if (typeof window === 'undefined') return + try { + if (state?.type === 'groupinvite') { + window.sessionStorage.setItem( + PENDING_GROUP_INVITE_KEY, + JSON.stringify({type: state.type, code: state.code}), + ) + } else { + window.sessionStorage.removeItem(PENDING_GROUP_INVITE_KEY) + } + } catch { + // Session storage is never required for normal invite handling. + } + }, [state]) return ( @@ -64,3 +117,8 @@ export const useActiveGroupChatJoinRequest = () => { const landing = useActiveLanding() return landing?.type === 'groupchat' ? landing : undefined } + +export const useActiveGroupInvite = () => { + const landing = useActiveLanding() + return landing?.type === 'groupinvite' ? landing : undefined +} diff --git a/src/state/shell/logged-out.tsx b/src/state/shell/logged-out.tsx index fcb76818c..7d5d65ca7 100644 --- a/src/state/shell/logged-out.tsx +++ b/src/state/shell/logged-out.tsx @@ -32,6 +32,7 @@ type Controls = { | 'new' | 'starterpack' | 'groupchat' + | 'groupinvite' }) => void /** * Clears the requested account so that next time the logged out view is @@ -64,6 +65,8 @@ function getRequestedAccountFromLanding( return IS_WEB ? 'starterpack' : 'new' case 'groupchat': return 'groupchat' + case 'groupinvite': + return 'groupinvite' default: return undefined } diff --git a/src/view/com/auth/LoggedOut.tsx b/src/view/com/auth/LoggedOut.tsx index 05340d0d2..063eded10 100644 --- a/src/view/com/auth/LoggedOut.tsx +++ b/src/view/com/auth/LoggedOut.tsx @@ -16,6 +16,7 @@ import { } from '#/state/shell/logged-out' import {useEnableMinimalShellMode} from '#/state/shell/minimal-mode' import {ErrorBoundary} from '#/view/com/util/ErrorBoundary' +import {GroupInviteLanding} from '#/screens/GroupInviteLanding' import {Login} from '#/screens/Login' import {JoinRequest} from '#/screens/Messages/JoinRequest' import {Signup} from '#/screens/Signup' @@ -32,6 +33,7 @@ enum ScreenState { S_CreateAccount, S_StarterPack, S_GroupChatJoinRequest, + S_GroupInvite, } export {ScreenState as LoggedOutScreenState} @@ -43,6 +45,8 @@ function getInitialScreenState(requestedAccountSwitchTo?: string): ScreenState { return ScreenState.S_StarterPack case 'groupchat': return ScreenState.S_GroupChatJoinRequest + case 'groupinvite': + return ScreenState.S_GroupInvite case undefined: return ScreenState.S_LoginOrCreateAccount default: @@ -124,6 +128,8 @@ export function LoggedOut({onDismiss}: {onDismiss?: () => void}) { ) : screenState === ScreenState.S_GroupChatJoinRequest ? ( + ) : screenState === ScreenState.S_GroupInvite ? ( + ) : screenState === ScreenState.S_LoginOrCreateAccount ? ( { diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index e83db8211..f2d61e698 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -60,13 +60,28 @@ import {Trans, useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' import {useQueries, useQueryClient} from '@tanstack/react-query' +import { + type CommunityFeedTarget, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import { + getCommunitySpaceUri, + isCommunityPostUri, +} from '#/lib/api/community-post' import * as apilib from '#/lib/api/index' import {EmbeddingDisabledError} from '#/lib/api/resolve' +import { + isSpaceRecordUri, + parseSpaceRecordUri, + spaceUriOf, +} from '#/lib/api/space-uri' +import {SpaceUnsupportedError} from '#/lib/api/space-write' import {useAppState} from '#/lib/appState' import {retry} from '#/lib/async/retry' import {until} from '#/lib/async/until' import {useBrand} from '#/lib/community/BrandContext' import { + ACCOUNT_MIGRATION_URL, MAX_DRAFT_GRAPHEME_LENGTH, MAX_GRAPHEME_LENGTH, SUPPORTED_MIME_TYPES, @@ -119,6 +134,7 @@ import {LabelsBtn} from '#/view/com/composer/labels/LabelsBtn' import {Gallery} from '#/view/com/composer/photos/Gallery' import {OpenCameraBtn} from '#/view/com/composer/photos/OpenCameraBtn' import {SelectGifBtn} from '#/view/com/composer/photos/SelectGifBtn' +import {PostTargetControls} from '#/view/com/composer/PostTargetControls' import {SuggestedLanguage} from '#/view/com/composer/select-language/SuggestedLanguage' // TODO: Prevent naming components that coincide with RN primitives // due to linting false positives @@ -133,11 +149,11 @@ import {Admonition} from '#/components/Admonition' import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {CommunityOnlyBadge} from '#/components/CommunityOnlyBadge' import * as EmojiPicker from '#/components/EmojiPicker' -import * as Toggle from '#/components/forms/Toggle' import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfoIcon} from '#/components/icons/CircleInfo' import {EmojiArc_Stroke2_Corner0_Rounded as EmojiSmileIcon} from '#/components/icons/Emoji' import {PlusLarge_Stroke2_Corner0_Rounded as PlusIcon} from '#/components/icons/Plus' import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times' +import {SimpleInlineLinkText} from '#/components/Link' import {LazyQuoteEmbed} from '#/components/Post/Embed/LazyQuoteEmbed' import * as Prompt from '#/components/Prompt' import * as Toast from '#/components/Toast' @@ -268,6 +284,7 @@ export const ComposePost = ({ videoUri: initVideoUri, openGallery, logContext, + contextualCommunityFeedTarget, cancelRef, }: Props & { cancelRef?: React.RefObject @@ -298,6 +315,10 @@ export const ComposePost = ({ const [isPublishing, setIsPublishing] = useState(false) const [publishingStage, setPublishingStage] = useState('') const [error, setError] = useState('') + // A write refused because the account's server has no space support: the + // only fix is moving the account, so the banner offers that rather than a + // failure the user cannot act on. + const [needsMigration, setNeedsMigration] = useState(false) /** * Track when a draft was created so we can measure draft age in metrics. @@ -363,11 +384,18 @@ export const ComposePost = ({ const setBlackskyOnlyDefault = useSetBlackskyOnlyDefault() const {data: isCommunityMember = false} = useCommunityMembership() - // Force Blacksky-Only when the thread targets a community post — replies - // and quotes of a community post can only land in the community. + // Both the appview-stored stub and any record inside a space: a reply or + // quote of either must stay inside the community it came from. + const isCommunityReply = isCommunityPostUri(replyTo?.uri) + const isCommunityQuote = isCommunityPostUri(initQuote?.uri) + const replyCommunitySpace = replyTo?.communitySpace + const quoteCommunitySpace = getCommunitySpaceUri(initQuote) const isForcedBlackskyOnly = - (!!replyTo?.uri && replyTo.uri.includes('community.blacksky.feed.post')) || - (!!initQuote?.uri && initQuote.uri.includes('community.blacksky.feed.post')) + (isCommunityReply && !replyCommunitySpace) || + (isCommunityQuote && !quoteCommunitySpace) + const isForcedCommunityTarget = isCommunityReply || isCommunityQuote + const hasEligibleContextualTarget = + !!contextualCommunityFeedTarget && !replyTo && !isForcedCommunityTarget const [composerState, composerDispatch] = useReducer( composerReducer, @@ -377,17 +405,56 @@ export const ComposePost = ({ initText, initMention, initInteractionSettings: preferences?.postInteractionSettings, + initCommunitySpaceUri: replyCommunitySpace ?? quoteCommunitySpace, // Replies inherit their parent's audience: forced on for community // parents, forced off for public parents. The sticky default only - // applies to top-level posts, and only for community members. + // applies to top-level posts for community members. A selected writable + // private feed starts public and supersedes that default for this + // composer instance without changing the persisted preference. initBlackskyOnly: isForcedBlackskyOnly || - (!replyTo && isCommunityMember && blackskyOnlyDefault), + (!hasEligibleContextualTarget && + !replyTo && + isCommunityMember && + blackskyOnlyDefault), }, createComposerState, ) const thread = composerState.thread + const spaceTarget = + thread.communitySpaceUri ?? + (isSpaceBackedFeed(thread.communityFeed?.config) + ? thread.communityFeed.config.space + : undefined) + + useEffect(() => { + if (!spaceTarget) return + for (const post of thread.posts) { + const media = post.embed.media + if (media?.type === 'images' || media?.type === 'gallery') { + for (const image of media.images) { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_image', image}, + }) + } + } else if (media?.type === 'video') { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_video'}, + }) + } else if (media?.type === 'gif') { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_gif'}, + }) + } + } + }, [spaceTarget, thread.posts]) // Clear error when composer content changes, but only if all posts are // back within the character limit. @@ -998,6 +1065,7 @@ export const ComposePost = ({ postUri = ( await apilib.post(agent, queryClient, { thread: filteredThread, + draftId: composerState.draftId, replyTo: replyTo?.uri, onStateChange: setPublishingStage, langs: currentLanguages, @@ -1064,6 +1132,9 @@ export const ComposePost = ({ err = l`We're sorry! The post you are replying to has been deleted.` } else if (e instanceof EmbeddingDisabledError) { err = l`This post's author has disabled quote posts.` + } else if (e instanceof SpaceUnsupportedError) { + err = l`Your account is hosted elsewhere, so it cannot post to a private community feed. You can read it, but posting needs an account hosted here.` + setNeedsMigration(true) } setError(err) setIsPublishing(false) @@ -1133,7 +1204,7 @@ export const ComposePost = ({ }) } setLangPrefs.savePostLanguageToHistory() - if (initQuote) { + if (initQuote && !isSpaceRecordUri(initQuote.uri)) { // We want to wait for the quote count to update before we call `onPost`, which will refetch data void whenAppViewReady(agent, initQuote.uri, res => { const anchor = res.data.thread.at(0) @@ -1167,17 +1238,33 @@ export const ComposePost = ({ { - const urip = new AtUri(postUri) const params: { name: string rkey: string collection?: string - } = { - name: urip.host, - rkey: urip.rkey, - } - if (urip.collection !== 'app.bsky.feed.post') { - params.collection = urip.collection + space?: string + } = (() => { + // A space record uri is not an at-uri, so its parts come + // from the space parser and the space itself travels as a + // route param rather than in the path. + const inSpace = parseSpaceRecordUri(postUri) + if (inSpace) { + return { + name: inSpace.authorDid, + rkey: inSpace.rkey, + collection: inSpace.collection, + space: spaceUriOf(inSpace), + } + } + const urip = new AtUri(postUri) + return { + name: urip.host, + rkey: urip.rkey, + collection: urip.collection, + } + })() + if (params.collection === 'app.bsky.feed.post') { + delete params.collection } navigation.navigate('PostThread', params) }}> @@ -1326,7 +1413,9 @@ export const ComposePost = ({ dispatch={composerDispatch} bottomBarAnimatedStyle={bottomBarAnimatedStyle} isForcedBlackskyOnly={isForcedBlackskyOnly} + isForcedCommunityTarget={isForcedCommunityTarget} setBlackskyOnlyDefault={setBlackskyOnlyDefault} + contextualCommunityFeedTarget={contextualCommunityFeedTarget} /> ) @@ -1383,8 +1473,12 @@ export const ComposePost = ({ {missingAltError && } setError('')} + clearError={() => { + setError('') + setNeedsMigration(false) + }} clearVideo={ erroredVideoPostId ? () => clearVideo(erroredVideoPostId) @@ -1984,7 +2078,9 @@ function ComposerPills({ dispatch, bottomBarAnimatedStyle, isForcedBlackskyOnly, + isForcedCommunityTarget, setBlackskyOnlyDefault, + contextualCommunityFeedTarget, }: { isReply: boolean thread: ThreadDraft @@ -1992,10 +2088,11 @@ function ComposerPills({ dispatch: (action: ComposerAction) => void bottomBarAnimatedStyle: StyleProp isForcedBlackskyOnly: boolean + isForcedCommunityTarget: boolean setBlackskyOnlyDefault: (v: boolean) => void + contextualCommunityFeedTarget?: CommunityFeedTarget }) { const t = useTheme() - const {t: l} = useLingui() const {data: isCommunityMember = false} = useCommunityMembership() const homeAppviewOutage = useHomeAppviewOutage() const media = post.embed.media @@ -2006,7 +2103,14 @@ function ComposerPills({ media?.type === 'video' const hasLink = !!post.embed.link - if (isReply && !hasMedia && !hasLink && !isForcedBlackskyOnly) { + if ( + isReply && + !hasMedia && + !hasLink && + !isForcedBlackskyOnly && + !thread.communityFeedUri && + !thread.communitySpaceUri + ) { return null } @@ -2020,7 +2124,7 @@ function ComposerPills({ bounces={false} keyboardShouldPersistTaps="always" showsHorizontalScrollIndicator={false}> - {isReply ? null : ( + {isReply || isSpaceBackedFeed(thread.communityFeed?.config) ? null : ( { @@ -2036,28 +2140,17 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} - {!isCommunityMember || (isReply && !isForcedBlackskyOnly) ? null : ( - { - const next = !thread.blackskyOnly - dispatch({type: 'toggle_blacksky_only'}) - setBlackskyOnlyDefault(next) - }} - style={[a.flex_row, a.align_center, a.gap_xs]}> - - {homeAppviewOutage ? ( - Blacksky Only (temporarily unavailable) - ) : ( - Blacksky Only - )} - - - - )} + {hasMedia || hasLink ? ( ) : null} - {thread.blackskyOnly && ( + {(thread.blackskyOnly || + thread.communityFeedUri || + thread.communitySpaceUri) && ( - + )} @@ -2094,6 +2191,7 @@ function ComposerFooter({ languageNudgeAt, openGallery, textInputRef, + spaceMediaDisabled, }: { post: PostDraft dispatch: (action: PostAction) => void @@ -2106,6 +2204,7 @@ function ComposerFooter({ languageNudgeAt: number openGallery?: boolean textInputRef: React.RefObject + spaceMediaDisabled: boolean }) { const t = useTheme() const {t: l} = useLingui() @@ -2142,9 +2241,10 @@ function ComposerFooter({ const onSelectGif = useCallback( (gif: Gif) => { + if (spaceMediaDisabled) return dispatch({type: 'embed_add_gif', gif}) }, - [dispatch], + [dispatch, spaceMediaDisabled], ) /* @@ -2156,6 +2256,7 @@ function ComposerFooter({ const onSelectAssets = useCallback( async ({type, assets, errors}) => { + if (spaceMediaDisabled) return setSelectedAssetsType(type) if (assets.length) { @@ -2192,7 +2293,7 @@ function ComposerFooter({ }) }) }, - [post.id, onSelectVideo, onImageAdd], + [post.id, onSelectVideo, onImageAdd, spaceMediaDisabled], ) return ( @@ -2214,7 +2315,7 @@ function ComposerFooter({ ) : ( - + {IS_WEB && gtPhone ? ( @@ -2250,6 +2356,11 @@ function ComposerFooter({ )} + {spaceMediaDisabled ? ( + + Media isn’t available in private spaces yet. + + ) : null} {showAddButton && ( @@ -2527,11 +2638,13 @@ const styles = StyleSheet.create({ function ErrorBanner({ error: standardError, + needsMigration, videoState, clearError, clearVideo, }: { error: string + needsMigration?: boolean videoState: VideoState | NoVideoState clearError: () => void clearVideo: () => void @@ -2582,6 +2695,15 @@ function ErrorBanner({ + {needsMigration && ( + + + Move your account to Blacksky + + + )} {videoError && videoState.jobId && ( void + isCommunityMember: boolean + homeAppviewOutage: boolean + setBlackskyOnlyDefault: (value: boolean) => void + isReply: boolean + isForcedBlackskyOnly: boolean + isForcedCommunityTarget: boolean + contextualCommunityFeedTarget?: CommunityFeedTarget +}) { + const {t} = useLingui() + const showContextualTarget = + !isReply && !isForcedCommunityTarget && !!contextualCommunityFeedTarget + const showBlackskyOnly = + !showContextualTarget && + isCommunityMember && + !(isReply && !isForcedBlackskyOnly) && + (!isForcedCommunityTarget || isForcedBlackskyOnly) + + return ( + <> + {showBlackskyOnly ? ( + { + const next = !thread.blackskyOnly + dispatch({type: 'toggle_blacksky_only'}) + setBlackskyOnlyDefault(next) + }} + style={[a.flex_row, a.align_center, a.gap_xs]}> + + {homeAppviewOutage ? ( + Blacksky Only (temporarily unavailable) + ) : ( + Blacksky Only + )} + + + + ) : null} + {showContextualTarget ? ( + { + dispatch({ + type: 'set_post_target', + target: + thread.communityFeed?.feed === + contextualCommunityFeedTarget.feed + ? 'public' + : contextualCommunityFeedTarget, + }) + }} + style={[a.flex_row, a.align_center, a.gap_xs]}> + + {contextualCommunityFeedTarget.name} + + + + ) : null} + + ) +} diff --git a/src/view/com/composer/__tests__/PostTargetControls.test.tsx b/src/view/com/composer/__tests__/PostTargetControls.test.tsx new file mode 100644 index 000000000..8ca7c1a1d --- /dev/null +++ b/src/view/com/composer/__tests__/PostTargetControls.test.tsx @@ -0,0 +1,196 @@ +import {fireEvent, render} from '@testing-library/react-native' + +import {type CommunityFeedTarget} from '#/lib/api/community-feed' +import {type ThreadDraft} from '#/view/com/composer/state/composer' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: ( + message: {message?: string; values?: Record} | string, + ) => { + if (typeof message === 'string') return message + return message.message?.replace( + /{(\w+)}/g, + (_, key: string) => message.values?.[key] ?? '', + ) + }, + }), + Trans: ({ + id, + message, + values, + }: { + id: string + message?: string + values?: Record + }) => + (message ?? id).replace( + /{(\w+)}/g, + (_, key: string) => values?.[key] ?? '', + ), +})) +jest.mock('#/alf', () => ({ + atoms: {flex_row: {}, align_center: {}, gap_xs: {}}, +})) +jest.mock('#/components/forms/Toggle', () => { + const React = require('react') + const {Pressable, Text} = require('react-native') + return { + Item: ({ + children, + disabled, + label, + name, + onChange, + value, + }: { + children: React.ReactNode + disabled?: boolean + label: string + name: string + onChange: () => void + value: boolean + }) => ( + + {children} + + ), + LabelText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + Switch: () => null, + } +}) + +import {PostTargetControls} from '../PostTargetControls' + +const PRIVATE_TARGET: CommunityFeedTarget = { + feed: 'at://did:plc:test/app.bsky.feed.generator/private', + name: 'Private Test', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/space/community.blacksky.feed/private', + group: 'members', + createdAt: '2026-08-30T00:00:00.000Z', + }, +} + +function thread(overrides: Partial = {}): ThreadDraft { + return { + posts: [], + postgate: {} as ThreadDraft['postgate'], + threadgate: [], + blackskyOnly: false, + ...overrides, + } +} + +function renderControls({ + draft = thread(), + target, + isForcedCommunityTarget = false, +}: { + draft?: ThreadDraft + target?: CommunityFeedTarget + isForcedCommunityTarget?: boolean +} = {}) { + const dispatch = jest.fn() + const setBlackskyOnlyDefault = jest.fn() + return { + ...render( + , + ), + dispatch, + setBlackskyOnlyDefault, + } +} + +describe('PostTargetControls', () => { + it('keeps ordinary public composition on the legacy Blacksky-only toggle', () => { + const {getByTestId, queryByTestId} = renderControls() + + expect(getByTestId('blacksky_only')).toBeTruthy() + expect(queryByTestId('permissioned_space')).toBeNull() + }) + + it('preserves legacy Blacksky-only state and behavior', () => { + const {dispatch, getByTestId, setBlackskyOnlyDefault} = renderControls({ + draft: thread({blackskyOnly: true}), + }) + + fireEvent.press(getByTestId('blacksky_only')) + expect(dispatch).toHaveBeenCalledWith({type: 'toggle_blacksky_only'}) + expect(setBlackskyOnlyDefault).toHaveBeenCalledWith(false) + }) + + it('offers public versus the selected private feed when Blacksky-only is off', () => { + const {dispatch, getByTestId, getByText, queryByTestId} = renderControls({ + target: PRIVATE_TARGET, + }) + + expect(getByText('Private Test')).toBeTruthy() + expect(queryByTestId('blacksky_only')).toBeNull() + fireEvent.press(getByTestId('permissioned_space')) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('gives the selected private feed precedence over sticky Blacksky-only state', () => { + const {dispatch, getByTestId, queryByTestId} = renderControls({ + draft: thread({blackskyOnly: true}), + target: PRIVATE_TARGET, + }) + + expect(queryByTestId('blacksky_only')).toBeNull() + const contextualToggle = getByTestId('permissioned_space') + expect(contextualToggle).toHaveProp( + 'accessibilityState', + expect.objectContaining({checked: false}), + ) + fireEvent.press(contextualToggle) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('does not expose private-space controls outside selected-feed context', () => { + const {queryByTestId} = renderControls({ + draft: thread({communityFeed: PRIVATE_TARGET}), + }) + + expect(queryByTestId('permissioned_space')).toBeNull() + }) + + it('does not expose destination controls for a forced private quote', () => { + const {queryByTestId} = renderControls({ + target: PRIVATE_TARGET, + isForcedCommunityTarget: true, + }) + + expect(queryByTestId('blacksky_only')).toBeNull() + expect(queryByTestId('permissioned_space')).toBeNull() + }) +}) diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index b1a64ae71..3f0684bb1 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -8,6 +8,7 @@ import { } from '@atproto/api' import {nanoid} from 'nanoid/non-secure' +import {type CommunityFeedTarget} from '#/lib/api/community-feed' import {type SelfLabel} from '#/lib/moderation' import {insertMentionAt} from '#/lib/strings/mention-manip' import {shortenLinks} from '#/lib/strings/rich-text-manip' @@ -103,6 +104,14 @@ export type ThreadDraft = { postgate: AppBskyFeedPostgate.Record threadgate: ThreadgateAllowUISetting[] blackskyOnly: boolean + communityFeed?: CommunityFeedTarget + communityFeedUri?: string + /** + * The space a parent post lives in, inherited when replying to or quoting + * one. Distinct from `communityFeedUri`, which names a feed the author + * chose to post into: a space is where content goes, a feed is a view. + */ + communitySpaceUri?: string } export type ComposerState = { @@ -123,6 +132,10 @@ export type ComposerAction = | {type: 'update_postgate'; postgate: AppBskyFeedPostgate.Record} | {type: 'update_threadgate'; threadgate: ThreadgateAllowUISetting[]} | {type: 'toggle_blacksky_only'} + | { + type: 'set_post_target' + target: 'public' | 'blacksky' | CommunityFeedTarget + } | { type: 'update_post' postId: string @@ -220,6 +233,23 @@ export function composerReducer( thread: { ...state.thread, blackskyOnly: !state.thread.blackskyOnly, + communityFeed: undefined, + communityFeedUri: undefined, + communitySpaceUri: undefined, + }, + } + } + case 'set_post_target': { + return { + ...state, + isDirty: true, + thread: { + ...state.thread, + blackskyOnly: action.target === 'blacksky', + communityFeed: + typeof action.target === 'string' ? undefined : action.target, + communityFeedUri: + typeof action.target === 'string' ? undefined : action.target.feed, }, } } @@ -631,6 +661,7 @@ export function createComposerState({ initQuoteUri, initInteractionSettings, initBlackskyOnly, + initCommunitySpaceUri, }: { initText: string | undefined initMention: string | undefined @@ -640,6 +671,7 @@ export function createComposerState({ | AppBskyActorDefs.PostInteractionSettingsPref | undefined initBlackskyOnly?: boolean + initCommunitySpaceUri?: string }): ComposerState { let media: ImagesMedia | GalleryMedia | undefined if (initImageUris?.length) { @@ -761,6 +793,7 @@ export function createComposerState({ allow: initInteractionSettings?.threadgateAllowRules, }), blackskyOnly: !!initBlackskyOnly, + communitySpaceUri: initCommunitySpaceUri, }, } } diff --git a/src/view/com/feeds/FeedPage.tsx b/src/view/com/feeds/FeedPage.tsx index 331c62e0d..7c40b8ce5 100644 --- a/src/view/com/feeds/FeedPage.tsx +++ b/src/view/com/feeds/FeedPage.tsx @@ -67,7 +67,7 @@ export function FeedPage({ const {_} = useLingui() const navigation = useNavigation>() const queryClient = useQueryClient() - const {openComposer} = useOpenComposer() + const {openComposer} = useOpenComposer(isPageFocused ? feed : undefined) const [isScrolledDown, setIsScrolledDown] = useState(false) const headerOffset = useHeaderOffset() const feedFeedback = useFeedFeedback(feedInfo, hasSession) diff --git a/src/view/com/post-thread/PostLikedBy.tsx b/src/view/com/post-thread/PostLikedBy.tsx index 48669d99c..a82b5644d 100644 --- a/src/view/com/post-thread/PostLikedBy.tsx +++ b/src/view/com/post-thread/PostLikedBy.tsx @@ -3,6 +3,7 @@ import {type AppBskyFeedGetLikes as GetLikes} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' @@ -32,11 +33,11 @@ export function PostLikedBy({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingLikes, diff --git a/src/view/com/post-thread/PostQuotes.tsx b/src/view/com/post-thread/PostQuotes.tsx index 671334ad3..d03e491a8 100644 --- a/src/view/com/post-thread/PostQuotes.tsx +++ b/src/view/com/post-thread/PostQuotes.tsx @@ -8,6 +8,7 @@ import { import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {usePostViewTracking} from '#/lib/hooks/usePostViewTracking' import {cleanError} from '#/lib/strings/errors' @@ -47,11 +48,11 @@ export function PostQuotes({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) const trackPostView = usePostViewTracking('PostQuotes') - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingQuotes, diff --git a/src/view/com/post-thread/PostRepostedBy.tsx b/src/view/com/post-thread/PostRepostedBy.tsx index 611eb7c43..60d392264 100644 --- a/src/view/com/post-thread/PostRepostedBy.tsx +++ b/src/view/com/post-thread/PostRepostedBy.tsx @@ -3,6 +3,7 @@ import {type AppBskyActorDefs as ActorDefs} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' @@ -38,11 +39,11 @@ export function PostRepostedBy({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingRepostedBy, diff --git a/src/view/com/post-thread/__tests__/space-engagement.test.tsx b/src/view/com/post-thread/__tests__/space-engagement.test.tsx new file mode 100644 index 000000000..b654fe45f --- /dev/null +++ b/src/view/com/post-thread/__tests__/space-engagement.test.tsx @@ -0,0 +1,95 @@ +import {type ReactNode} from 'react' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {render, waitFor} from '@testing-library/react-native' + +const mockGetSpacePostLikes = jest.fn() +const mockGetSpacePostQuotes = jest.fn() +const mockAgent = { + getLikes: jest.fn(), + api: {app: {bsky: {feed: {getQuotes: jest.fn()}}}}, +} + +jest.mock('#/lib/api/community', () => ({ + getSpacePostLikes: (...args: unknown[]) => mockGetSpacePostLikes(...args), + getSpacePostQuotes: (...args: unknown[]) => mockGetSpacePostQuotes(...args), +})) +jest.mock('#/state/session', () => ({useAgent: () => mockAgent})) +jest.mock('#/state/queries/profile', () => ({ + useUnstableProfileViewCache: () => ({getUnstableProfile: jest.fn()}), +})) +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: unknown) => value}), +})) +jest.mock('#/lib/hooks/useInitialNumToRender', () => ({ + useInitialNumToRender: () => 1, +})) +jest.mock('#/lib/hooks/usePostViewTracking', () => ({ + usePostViewTracking: () => jest.fn(), +})) +jest.mock('#/lib/strings/errors', () => ({ + cleanError: (error: unknown) => error, +})) +jest.mock('#/logger', () => ({logger: {error: jest.fn()}})) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => ({}), +})) +jest.mock('#/view/com/profile/ProfileCard', () => ({ + ProfileCardWithFollowBtn: () => null, +})) +jest.mock('#/view/com/post/Post', () => ({Post: () => null})) +jest.mock('#/view/com/util/List', () => ({List: () => null})) +jest.mock('#/components/Lists', () => ({ + ListFooter: () => null, + ListMaybePlaceholder: () => null, +})) + +import {PostLikedBy} from '../PostLikedBy' +import {PostQuotes} from '../PostQuotes' + +const SPACE_POST = + 'at://did:plc:space/space/community.blacksky.feed/test/did:plc:alice/app.bsky.feed.post/3kspace' + +function wrapper({children}: {children: ReactNode}) { + const queryClient = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + return ( + {children} + ) +} + +describe('permissioned-space post engagement components', () => { + beforeEach(() => { + jest.clearAllMocks() + mockGetSpacePostLikes.mockImplementation(() => new Promise(() => {})) + mockGetSpacePostQuotes.mockImplementation(() => new Promise(() => {})) + }) + + it('mounts liked-by and requests the space likes endpoint', async () => { + expect(() => + render(, {wrapper}), + ).not.toThrow() + + await waitFor(() => { + expect(mockGetSpacePostLikes).toHaveBeenCalledWith(mockAgent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + }) + + it('mounts quotes and requests the space quotes endpoint', async () => { + expect(() => + render(, {wrapper}), + ).not.toThrow() + + await waitFor(() => { + expect(mockGetSpacePostQuotes).toHaveBeenCalledWith(mockAgent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + }) +}) diff --git a/src/view/com/post/Post.tsx b/src/view/com/post/Post.tsx index 0e701312e..3ced56d22 100644 --- a/src/view/com/post/Post.tsx +++ b/src/view/com/post/Post.tsx @@ -10,9 +10,13 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -39,7 +43,6 @@ import {TranslatedPost} from '#/components/Post/Translated' import {PostControls} from '#/components/PostControls' import {RichText} from '#/components/RichText' import {SubtleHover} from '#/components/SubtleHover' -import * as bsky from '#/types/bsky' export function Post({ post, @@ -56,10 +59,7 @@ export function Post({ }) { const moderationOpts = useModerationOpts() const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], ) const postShadowed = usePostShadow(post) @@ -122,11 +122,7 @@ function PostInner({ const [limitLines, setLimitLines] = useState( () => countLines(richText?.text) >= MAX_POST_LINES, ) - const itemUrip = new AtUri(post.uri) - const isCommunityPost = itemUrip.collection === 'community.blacksky.feed.post' - const itemHref = isCommunityPost - ? `${makeProfileLink(post.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` - : makeProfileLink(post.author, 'post', itemUrip.rkey) + const itemHref = postPermalink(post.author, post.uri) let replyAuthorDid = '' if (record.reply) { const urip = new AtUri(record.reply.parent?.uri || record.reply.root.uri) @@ -143,6 +139,7 @@ function PostInner({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) diff --git a/src/view/com/posts/PostFeedItem.tsx b/src/view/com/posts/PostFeedItem.tsx index 6fa693578..7a1a2c90e 100644 --- a/src/view/com/posts/PostFeedItem.tsx +++ b/src/view/com/posts/PostFeedItem.tsx @@ -11,11 +11,15 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {type ReasonFeedSource} from '#/lib/api/feed/types' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {usePalette} from '#/lib/hooks/usePalette' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -174,12 +178,8 @@ let FeedItemInner = ({ const [href] = useMemo(() => { const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return [ - isCommunity ? `${link}?collection=${urip.collection}` : link, - urip.rkey, - ] + const link = postPermalink(post.author, post.uri) + return [link, urip.rkey] }, [post.uri, post.author]) const {sendInteraction, feedSourceInfo, feedDescriptor} = useFeedFeedbackContext() @@ -200,6 +200,7 @@ let FeedItemInner = ({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) @@ -482,10 +483,7 @@ let PostContent = ({ ) const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], ) diff --git a/src/view/com/testing/TestCtrls.e2e.tsx b/src/view/com/testing/TestCtrls.e2e.tsx index f7e7bc1a1..0e395b559 100644 --- a/src/view/com/testing/TestCtrls.e2e.tsx +++ b/src/view/com/testing/TestCtrls.e2e.tsx @@ -2,6 +2,7 @@ import {useState} from 'react' import {LogBox, Pressable, TextInput, View} from 'react-native' import {useQueryClient} from '@tanstack/react-query' +import {setGroupInviteE2EFailure} from '#/lib/api/group-invite-e2e' import {BLUESKY_PROXY_HEADER} from '#/lib/constants' import {useAgent, useSessionApi} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' @@ -148,6 +149,24 @@ export function TestCtrls() { accessibilityRole="button" style={BTN} /> + setGroupInviteE2EFailure('saved-feed-update')} + accessibilityRole="button" + style={BTN} + /> + setGroupInviteE2EFailure('saved-feed-add')} + accessibilityRole="button" + style={BTN} + /> + setGroupInviteE2EFailure('navigation')} + accessibilityRole="button" + style={BTN} + /> ) } diff --git a/src/view/screens/PostThread.tsx b/src/view/screens/PostThread.tsx index c4ba6b7d3..8cd0e4816 100644 --- a/src/view/screens/PostThread.tsx +++ b/src/view/screens/PostThread.tsx @@ -1,8 +1,10 @@ +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostThread} from '#/screens/PostThread' import * as Layout from '#/components/Layout' @@ -18,11 +20,48 @@ export function PostThreadScreen({route}: Props) { collection = collection || qs.get('collection') || undefined rkey = rkey.slice(0, qIndex) } - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + const space = route.params.space return ( - + ) } + +function PostThreadRoute({ + name, + rkey, + collection, + space, +}: { + name: string + rkey: string + collection?: string + space?: string +}) { + // A space URI admits only DIDs in its author segment, so a handle in the + // path has to be resolved before the URI can be assembled. Links the app + // builds already carry DIDs; this covers hand-typed and shared URLs. + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + if (needsDid && isPending) return null + + const author = needsDid ? resolvedDid : name + // Falling back to the ordinary URI when the space parts do not add up gives + // the thread's own not-found state rather than a blank screen. + const uri = + (space && + author && + spacePostUriFromRoute(space, author, rkey, collection)) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + + return +} diff --git a/src/view/shell/Composer.ios.tsx b/src/view/shell/Composer.ios.tsx index 7a1f59937..bc8e2c649 100644 --- a/src/view/shell/Composer.ios.tsx +++ b/src/view/shell/Composer.ios.tsx @@ -47,6 +47,7 @@ export function Composer() { text={state?.text} imageUris={state?.imageUris} videoUri={state?.videoUri} + contextualCommunityFeedTarget={state?.contextualCommunityFeedTarget} /> diff --git a/src/view/shell/Composer.tsx b/src/view/shell/Composer.tsx index e5705f422..853c2e54c 100644 --- a/src/view/shell/Composer.tsx +++ b/src/view/shell/Composer.tsx @@ -48,6 +48,7 @@ export function Composer() { imageUris={state.imageUris} videoUri={state.videoUri} openGallery={state.openGallery} + contextualCommunityFeedTarget={state.contextualCommunityFeedTarget} /> ) diff --git a/src/view/shell/Composer.web.tsx b/src/view/shell/Composer.web.tsx index d7d0e4ed8..0ab8d6958 100644 --- a/src/view/shell/Composer.web.tsx +++ b/src/view/shell/Composer.web.tsx @@ -72,6 +72,7 @@ function Inner({state}: {state: ComposerOpts}) { text={state.text} imageUris={state.imageUris} openGallery={state.openGallery} + contextualCommunityFeedTarget={state.contextualCommunityFeedTarget} /> diff --git a/src/view/shell/__tests__/Composer-context.test.tsx b/src/view/shell/__tests__/Composer-context.test.tsx new file mode 100644 index 000000000..3d3a2f80f --- /dev/null +++ b/src/view/shell/__tests__/Composer-context.test.tsx @@ -0,0 +1,57 @@ +import {render} from '@testing-library/react-native' + +const mockComposePost = jest.fn((_props: Record) => null) +const mockUseComposerState = jest.fn() + +jest.mock('#/state/shell/composer', () => ({ + useComposerState: () => mockUseComposerState(), +})) +jest.mock('#/view/com/composer/Composer', () => ({ + ComposePost: (props: Record) => mockComposePost(props), + useComposerCancelRef: () => ({current: null}), +})) +jest.mock('#/components/Tooltip', () => ({ + SheetCompatProvider: ({children}: {children: React.ReactNode}) => children, +})) +jest.mock('#/alf', () => ({ + atoms: {absolute: {}, inset_0: {}}, + useTheme: () => ({name: 'light', atoms: {bg: {}}}), +})) +jest.mock('react-native-edge-to-edge', () => ({ + SystemBars: { + pushStackEntry: jest.fn(() => ({})), + popStackEntry: jest.fn(), + }, +})) +jest.mock('react-native-reanimated', () => { + const {View} = require('react-native') + const animation = {duration: () => animation, easing: () => animation} + return { + __esModule: true, + default: {View}, + Easing: {out: jest.fn(), in: jest.fn(), exp: {}, quad: {}}, + SlideInDown: animation, + SlideOutDown: animation, + } +}) + +import {Composer} from '../Composer' + +describe('Composer selected feed context', () => { + it('forwards the contextual private feed into ComposePost', () => { + const target = { + feed: 'at://did:plc:test/app.bsky.feed.generator/private', + name: 'Private Test', + } + mockUseComposerState.mockReturnValue({ + text: 'hello', + contextualCommunityFeedTarget: target, + }) + + render() + + expect(mockComposePost).toHaveBeenCalledWith( + expect.objectContaining({contextualCommunityFeedTarget: target}), + ) + }) +}) diff --git a/src/view/shell/desktop/LeftNav.tsx b/src/view/shell/desktop/LeftNav.tsx index 53181655c..a62ec5edb 100644 --- a/src/view/shell/desktop/LeftNav.tsx +++ b/src/view/shell/desktop/LeftNav.tsx @@ -17,12 +17,15 @@ import { import {sanitizeDisplayName} from '#/lib/strings/display-names' import {isInvalidHandle, sanitizeHandle} from '#/lib/strings/handles' import {emitSoftReset} from '#/state/events' +import {usePinnedFeedsInfos} from '#/state/queries/feed' import {useFetchHandle} from '#/state/queries/handle' import {useUnreadMessageCount} from '#/state/queries/messages/list-conversations' import {useUnreadNotifications} from '#/state/queries/notifications/unread' +import {type FeedDescriptor} from '#/state/queries/post-feed' import {useProfilesQuery} from '#/state/queries/profile' import {type SessionAccount, useSession, useSessionApi} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useSelectedFeed} from '#/state/shell/selected-feed' import {useCloseAllActiveElements} from '#/state/util' import {LoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' import {PressableWithHover} from '#/view/com/util/PressableWithHover' @@ -543,7 +546,22 @@ function NavItem({ function ComposeBtn({minimal}: {minimal: boolean}) { const {currentAccount} = useSession() const {getState} = useNavigation() - const {openComposer} = useOpenComposer() + const currentRoute = useNavigationState(state => + state ? getCurrentRoute(state) : {name: 'Home'}, + ) + const selectedFeed = useSelectedFeed() + const {data: pinnedFeedInfos} = usePinnedFeedsInfos() + const contextualFeed = + currentRoute.name === 'Home' + ? (selectedFeed ?? pinnedFeedInfos?.[0]?.feedDescriptor) + : currentRoute.name === 'ProfileFeed' + ? (( + currentRoute.params as + | CommonNavigatorParams['ProfileFeed'] + | undefined + )?.resolvedFeed as FeedDescriptor | undefined) + : undefined + const {openComposer} = useOpenComposer(contextualFeed) const {t: l} = useLingui() const brand = useBrand() const {leftNavMinimal} = useLayoutBreakpoints() -- knotmirror 0.0.1 From 9f9ed6418903172a96c249a94c95b7f6e734d09a Mon Sep 17 00:00:00 2001 From: rudyfraser <26655424+rudyfraser@users.noreply.github.com> Date: Mon, 31 Aug 2026 02:24:55 +0000 Subject: [PATCH 3/4] Nightly source-language update --- src/locale/locales/en/messages.po | 913 +++++++++++++++++------------- 1 file changed, 515 insertions(+), 398 deletions(-) diff --git a/src/locale/locales/en/messages.po b/src/locale/locales/en/messages.po index 0077d78c6..13d1a3995 100644 --- a/src/locale/locales/en/messages.po +++ b/src/locale/locales/en/messages.po @@ -70,7 +70,7 @@ msgid "{0, plural, one {# label has} other {# labels have}} been placed on this msgstr "" #. placeholder {0}: likeCount ?? 0 -#: src/screens/Post/PostLikedBy.tsx:34 +#: src/screens/Post/PostLikedBy.tsx:59 msgid "{0, plural, one {# like} other {# likes}}" msgstr "" @@ -101,12 +101,12 @@ msgid "{0, plural, one {# person} other {# people}} reacted – {1}" msgstr "{0, plural, one {# person} other {# people}} reacted – {1}" #. placeholder {0}: quoteCount ?? 0 -#: src/screens/Post/PostQuotes.tsx:34 +#: src/screens/Post/PostQuotes.tsx:59 msgid "{0, plural, one {# quote} other {# quotes}}" msgstr "" #. placeholder {0}: quoteCount ?? 0 -#: src/screens/Post/PostRepostedBy.tsx:34 +#: src/screens/Post/PostRepostedBy.tsx:59 msgid "{0, plural, one {# repost} other {# reposts}}" msgstr "" @@ -195,7 +195,7 @@ msgid "{0} added to chat" msgstr "{0} added to chat" #. placeholder {0}: brand.messages.postButtonLabel -#: src/view/com/composer/Composer.tsx:1844 +#: src/view/com/composer/Composer.tsx:1938 msgctxt "action" msgid "{0} All" msgstr "{0} All" @@ -416,7 +416,7 @@ msgstr "{count, plural, one {# new join request} other {# new join requests}}" msgid "{count, plural, one {# request} other {# requests}}" msgstr "{count, plural, one {# request} other {# requests}}" -#: src/view/shell/desktop/LeftNav.tsx:488 +#: src/view/shell/desktop/LeftNav.tsx:491 msgid "{count, plural, one {# unread item} other {# unread items}}" msgstr "" @@ -658,7 +658,7 @@ msgstr "" msgid "{MAX_ALT_TEXT, plural, other {Alt text must be less than # characters.}}" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:392 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:396 msgid "{MAX_HIDDEN_REPLIES, plural, other {You can hide a maximum of # replies.}}" msgstr "" @@ -793,28 +793,28 @@ msgstr "" #. Like count display, the <0> tags enclose the number of likes in bold (will never be 0) #. placeholder {0}: formatPostStatCount(post.likeCount) #. placeholder {1}: post.likeCount -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:493 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:495 msgid "<0>{0} {1, plural, one {like} other {likes}}" msgstr "" #. Quote count display, the <0> tags enclose the number of quotes in bold (will never be 0) #. placeholder {0}: formatPostStatCount(post.quoteCount) #. placeholder {1}: post.quoteCount -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:474 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:476 msgid "<0>{0} {1, plural, one {quote} other {quotes}}" msgstr "" #. Repost count display, the <0> tags enclose the number of reposts in bold (will never be 0) #. placeholder {0}: formatPostStatCount(post.repostCount) #. placeholder {1}: post.repostCount -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:453 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:455 msgid "<0>{0} {1, plural, one {repost} other {reposts}}" msgstr "" #. Save count display, the <0> tags enclose the number of saves in bold (will never be 0) #. placeholder {0}: formatPostStatCount(post.bookmarkCount) #. placeholder {1}: post.bookmarkCount -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:511 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:513 msgid "<0>{0} {1, plural, one {save} other {saves}}" msgstr "" @@ -923,7 +923,7 @@ msgstr "" msgid "A selected recipient is not followed by the sender." msgstr "A selected recipient is not followed by the sender." -#: src/Navigation.tsx:492 +#: src/Navigation.tsx:496 #: src/screens/Settings/AboutSettings.tsx:76 #: src/screens/Settings/Settings.tsx:257 #: src/screens/Settings/Settings.tsx:260 @@ -950,6 +950,10 @@ msgstr "Accept" msgid "Accept chat request" msgstr "" +#: src/components/intents/GroupInviteDialog.tsx:317 +msgid "Accept group invite" +msgstr "Accept group invite" + #: src/screens/Messages/JoinRequests.tsx:448 msgid "Accept join request" msgstr "Accept join request" @@ -978,19 +982,19 @@ msgstr "Access requested! The group owner will review your request." msgid "Accessibility" msgstr "" -#: src/Navigation.tsx:407 +#: src/Navigation.tsx:411 msgid "Accessibility Settings" msgstr "" -#: src/Navigation.tsx:431 -#: src/screens/Login/LoginForm.tsx:218 +#: src/Navigation.tsx:435 +#: src/screens/Login/LoginForm.tsx:247 #: src/screens/Settings/AccountSettings.tsx:69 #: src/screens/Settings/Settings.tsx:167 #: src/screens/Settings/Settings.tsx:170 msgid "Account" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:424 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:428 #: src/screens/Messages/components/RequestButtons.tsx:104 #: src/screens/Messages/ConversationSettings/MemberMenu.tsx:122 #: src/view/com/profile/ProfileMenu.tsx:182 @@ -1044,7 +1048,7 @@ msgstr "Account is suspended by <0>@{0}. Click <1>here to submit an appe msgid "Account is suspended." msgstr "Account is suspended." -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:467 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:471 #: src/view/com/profile/ProfileMenu.tsx:152 msgctxt "toast" msgid "Account muted" @@ -1088,7 +1092,7 @@ msgctxt "toast" msgid "Account unfollowed" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:447 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:451 #: src/view/com/profile/ProfileMenu.tsx:139 msgctxt "toast" msgid "Account unmuted" @@ -1162,16 +1166,16 @@ msgstr "" #: src/screens/Settings/Settings.tsx:537 #: src/screens/Settings/Settings.tsx:540 -#: src/view/shell/desktop/LeftNav.tsx:280 #: src/view/shell/desktop/LeftNav.tsx:283 +#: src/view/shell/desktop/LeftNav.tsx:286 msgid "Add another account" msgstr "" -#: src/view/com/composer/Composer.tsx:1557 +#: src/view/com/composer/Composer.tsx:1651 msgid "Add another post" msgstr "" -#: src/view/com/composer/Composer.tsx:2257 +#: src/view/com/composer/Composer.tsx:2368 msgid "Add another post to thread" msgstr "" @@ -1359,7 +1363,7 @@ msgstr "" msgid "AI preferences" msgstr "AI preferences" -#: src/Navigation.tsx:415 +#: src/Navigation.tsx:419 msgid "AI Preferences" msgstr "AI Preferences" @@ -1534,7 +1538,7 @@ msgstr "" msgid "An error occurred while fetching suggested accounts." msgstr "" -#: src/state/queries/explore-feed-previews.tsx:183 +#: src/state/queries/explore-feed-previews.tsx:182 msgid "An error occurred while fetching the feed." msgstr "" @@ -1688,7 +1692,7 @@ msgstr "" msgid "Anyone who has it will no longer be able to join or request to join. You can always create a new one." msgstr "Anyone who has it will no longer be able to join or request to join. You can always create a new one." -#: src/Navigation.tsx:500 +#: src/Navigation.tsx:504 #: src/screens/Settings/AppIconSettings/index.tsx:62 #: src/screens/Settings/AppIconSettings/SettingsListItem.tsx:19 #: src/screens/Settings/AppIconSettings/SettingsListItem.tsx:24 @@ -1728,7 +1732,7 @@ msgstr "" msgid "App passwords" msgstr "" -#: src/Navigation.tsx:375 +#: src/Navigation.tsx:379 #: src/screens/Settings/AppPasswords.tsx:89 #: src/screens/Settings/AppPasswords.tsx:143 msgid "App Passwords" @@ -1771,7 +1775,7 @@ msgstr "" msgid "Appeal this decision" msgstr "" -#: src/Navigation.tsx:423 +#: src/Navigation.tsx:427 #: src/screens/Settings/AppearanceSettings.tsx:73 #: src/screens/Settings/Settings.tsx:227 #: src/screens/Settings/Settings.tsx:230 @@ -1802,12 +1806,12 @@ msgid "Apply Pull Request" msgstr "" #. placeholder {0}: niceDate(i18n, createdAt, 'medium') -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:633 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:635 msgid "Archived from {0}" msgstr "" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:604 -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:642 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:606 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:644 msgid "Archived post" msgstr "" @@ -1855,7 +1859,7 @@ msgstr "" msgid "Are you sure you want to rescind your request to join {0}?" msgstr "Are you sure you want to rescind your request to join {0}?" -#: src/view/com/composer/Composer.tsx:1693 +#: src/view/com/composer/Composer.tsx:1787 msgid "Are you sure you'd like to discard this post?" msgstr "" @@ -1897,7 +1901,7 @@ msgstr "Automated account" msgid "Automation label" msgstr "Automation label" -#: src/Navigation.tsx:439 +#: src/Navigation.tsx:443 #: src/screens/Settings/AutomationLabelSettings.tsx:103 msgid "Automation Label" msgstr "Automation Label" @@ -1924,8 +1928,8 @@ msgstr "" #: src/screens/Login/ChooseAccountForm.tsx:113 #: src/screens/Login/ForgotPasswordForm.tsx:124 #: src/screens/Login/ForgotPasswordForm.tsx:130 -#: src/screens/Login/LoginForm.tsx:290 -#: src/screens/Login/LoginForm.tsx:296 +#: src/screens/Login/LoginForm.tsx:340 +#: src/screens/Login/LoginForm.tsx:346 #: src/screens/Login/SetNewPasswordForm.tsx:170 #: src/screens/Login/SetNewPasswordForm.tsx:176 #: src/screens/Messages/components/ChatDisabled.tsx:166 @@ -1965,7 +1969,7 @@ msgstr "" msgid "Before creating a list, you must first verify your email." msgstr "" -#: src/lib/hooks/useOpenComposer.tsx:14 +#: src/lib/hooks/useOpenComposer.tsx:56 msgid "Before creating a post or replying, you must first verify your email." msgstr "" @@ -2008,7 +2012,7 @@ msgstr "Birthdate" msgid "Birthday" msgstr "Birthday" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:658 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:660 msgid "Blacksky cannot confirm the authenticity of the claimed date." msgstr "Blacksky cannot confirm the authenticity of the claimed date." @@ -2024,13 +2028,13 @@ msgstr "Blacksky is more fun with friends" msgid "Blacksky needs camera access to scan QR codes from other profiles." msgstr "Blacksky needs camera access to scan QR codes from other profiles." -#: src/components/CommunityOnlyBadge.tsx:57 -#: src/view/com/composer/Composer.tsx:2042 -#: src/view/com/composer/Composer.tsx:2055 +#: src/components/CommunityOnlyBadge.tsx:68 +#: src/view/com/composer/PostTargetControls.tsx:46 +#: src/view/com/composer/PostTargetControls.tsx:59 msgid "Blacksky Only" msgstr "Blacksky Only" -#: src/view/com/composer/Composer.tsx:2053 +#: src/view/com/composer/PostTargetControls.tsx:57 msgid "Blacksky Only (temporarily unavailable)" msgstr "Blacksky Only (temporarily unavailable)" @@ -2046,8 +2050,7 @@ msgstr "Blacksky will follow the preferences you set here. We will share your pr msgid "Blacksky will not show your profile and posts to logged-out users. Other apps may not honor this request. This does not make your account private." msgstr "Blacksky will not show your profile and posts to logged-out users. Other apps may not honor this request. This does not make your account private." -#: src/components/CommunityOnlyBadge.tsx:36 -#: src/components/CommunityOnlyBadge.tsx:54 +#: src/components/CommunityOnlyBadge.tsx:25 msgid "Blacksky-only post" msgstr "Blacksky-only post" @@ -2069,8 +2072,8 @@ msgstr "Block {displayName}" #: src/components/dms/ConvoMenu.tsx:284 #: src/components/dms/ConvoMenu.tsx:288 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:708 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:710 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:712 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:714 #: src/screens/Messages/components/RequestButtons.tsx:154 #: src/screens/Messages/components/RequestButtons.tsx:156 #: src/view/com/profile/ProfileMenu.tsx:464 @@ -2131,7 +2134,7 @@ msgstr "" msgid "Block user and/or leave this conversation" msgstr "Block user and/or leave this conversation" -#: src/components/Post/Embed/index.tsx:209 +#: src/components/Post/Embed/index.tsx:208 msgid "Blocked" msgstr "" @@ -2139,7 +2142,7 @@ msgstr "" msgid "Blocked accounts" msgstr "" -#: src/Navigation.tsx:201 +#: src/Navigation.tsx:205 #: src/view/screens/ModerationBlockedAccounts.tsx:95 msgid "Blocked Accounts" msgstr "" @@ -2330,8 +2333,8 @@ msgstr "Camera access needed" #: src/features/liveNow/components/GoLiveDialog.tsx:254 #: src/lib/media/picker.tsx:38 #: src/screens/Deactivated.tsx:288 -#: src/screens/Login/LoginForm.tsx:303 -#: src/screens/Login/LoginForm.tsx:310 +#: src/screens/Login/LoginForm.tsx:353 +#: src/screens/Login/LoginForm.tsx:360 #: src/screens/Messages/components/InviteLinkDialog.tsx:502 #: src/screens/Messages/components/InviteLinkDialog.tsx:506 #: src/screens/Messages/ConversationSettings/prompts.tsx:108 @@ -2350,11 +2353,11 @@ msgstr "Camera access needed" #: src/screens/Settings/Settings.tsx:302 #: src/screens/Takendown.tsx:104 #: src/screens/Takendown.tsx:107 -#: src/view/com/composer/Composer.tsx:1772 -#: src/view/com/composer/Composer.tsx:1782 +#: src/view/com/composer/Composer.tsx:1866 +#: src/view/com/composer/Composer.tsx:1876 #: src/view/com/composer/photos/EditImageDialog.web.tsx:44 #: src/view/com/composer/photos/EditImageDialog.web.tsx:53 -#: src/view/shell/desktop/LeftNav.tsx:232 +#: src/view/shell/desktop/LeftNav.tsx:235 msgid "Cancel" msgstr "" @@ -2374,14 +2377,14 @@ msgstr "Cancel reply" msgid "Cancel search" msgstr "" -#: src/screens/Login/LoginForm.tsx:304 +#: src/screens/Login/LoginForm.tsx:354 msgid "Cancels the sign-in process" msgstr "Cancels the sign-in process" -#: src/components/PostControls/index.tsx:113 -#: src/components/PostControls/index.tsx:143 -#: src/components/PostControls/index.tsx:171 -#: src/state/shell/composer/index.tsx:105 +#: src/components/PostControls/index.tsx:114 +#: src/components/PostControls/index.tsx:144 +#: src/components/PostControls/index.tsx:172 +#: src/state/shell/composer/index.tsx:108 msgid "Cannot interact with a blocked user" msgstr "" @@ -2478,9 +2481,9 @@ msgid "Changes to the starter pack will not be reflected in the list after creat msgstr "" #: src/lib/hooks/useNotificationHandler.ts:133 -#: src/Navigation.tsx:518 +#: src/Navigation.tsx:522 #: src/view/shell/bottom-bar/BottomBar.tsx:237 -#: src/view/shell/desktop/LeftNav.tsx:706 +#: src/view/shell/desktop/LeftNav.tsx:724 #: src/view/shell/Drawer.tsx:590 msgid "Chat" msgstr "" @@ -2531,7 +2534,7 @@ msgstr "Chat owners cannot leave a group chat." msgid "Chat recipient is not followed by the sender." msgstr "Chat recipient is not followed by the sender." -#: src/Navigation.tsx:538 +#: src/Navigation.tsx:542 msgid "Chat request inbox" msgstr "" @@ -2540,7 +2543,7 @@ msgid "Chat requests" msgstr "" #: src/components/dms/ConvoMenu.tsx:88 -#: src/Navigation.tsx:533 +#: src/Navigation.tsx:537 #: src/screens/Messages/ChatList.tsx:525 #: src/screens/Messages/ChatList.tsx:556 msgid "Chat settings" @@ -2824,7 +2827,7 @@ msgstr "" msgid "Closes password update alert" msgstr "" -#: src/view/com/composer/Composer.tsx:1780 +#: src/view/com/composer/Composer.tsx:1874 msgid "Closes post composer and discards post draft" msgstr "" @@ -2871,11 +2874,19 @@ msgstr "Community Builder" msgid "Community features are temporarily unavailable. We're working on it — the rest of the app still works." msgstr "Community features are temporarily unavailable. We're working on it — the rest of the app still works." -#: src/Navigation.tsx:365 +#: src/Navigation.tsx:369 #: src/view/screens/CommunityGuidelines.tsx:28 msgid "Community Guidelines" msgstr "" +#: src/components/CommunityOnlyBadge.tsx:66 +msgid "Community Only" +msgstr "Community Only" + +#: src/components/CommunityOnlyBadge.tsx:24 +msgid "Community-only post" +msgstr "Community-only post" + #: src/screens/Onboarding/StepFinished/index.tsx:333 msgid "Complete onboarding and start using your account" msgstr "" @@ -2886,12 +2897,12 @@ msgstr "" #: src/lib/hotkeys/index.tsx:66 #: src/view/com/feeds/ComposerPrompt.tsx:148 -#: src/view/shell/desktop/LeftNav.tsx:593 +#: src/view/shell/desktop/LeftNav.tsx:611 msgid "Compose new post" msgstr "" #. placeholder {0}: MAX_GRAPHEME_LENGTH || 0 -#: src/view/com/composer/Composer.tsx:1655 +#: src/view/com/composer/Composer.tsx:1749 msgid "Compose posts up to {0, plural, other {# characters}} in length" msgstr "" @@ -2899,11 +2910,11 @@ msgstr "" msgid "Compose reply" msgstr "" -#: src/view/com/composer/Composer.tsx:2654 +#: src/view/com/composer/Composer.tsx:2776 msgid "Compressing GIF..." msgstr "" -#: src/view/com/composer/Composer.tsx:2656 +#: src/view/com/composer/Composer.tsx:2778 msgid "Compressing video..." msgstr "" @@ -2975,7 +2986,7 @@ msgstr "" msgid "Content and media" msgstr "" -#: src/Navigation.tsx:476 +#: src/Navigation.tsx:480 msgid "Content and Media" msgstr "" @@ -3083,8 +3094,8 @@ msgstr "" #: src/components/dms/ChatInvite/Root.tsx:102 #: src/components/dms/MessageContextMenu.tsx:83 #: src/components/PostControls/DiscoverDebug.tsx:36 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:276 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:77 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:280 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:73 #: src/lib/sharing.ts:24 #: src/lib/sharing.ts:42 msgid "Copied to clipboard" @@ -3118,8 +3129,8 @@ msgstr "" msgid "Copy at:// URI" msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:154 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:157 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:150 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:153 msgid "Copy author DID" msgstr "" @@ -3157,10 +3168,10 @@ msgstr "" msgid "Copy link to list" msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:142 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:145 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:88 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:91 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:138 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:141 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:84 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:87 msgid "Copy link to post" msgstr "" @@ -3178,13 +3189,13 @@ msgstr "" msgid "Copy message text" msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:145 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:148 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:141 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:144 msgid "Copy post at:// URI" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:548 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:550 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:552 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:554 msgid "Copy post text" msgstr "" @@ -3196,7 +3207,7 @@ msgstr "" msgid "Copy TXT record value" msgstr "" -#: src/Navigation.tsx:370 +#: src/Navigation.tsx:374 #: src/view/screens/CopyrightPolicy.tsx:25 msgid "Copyright Policy" msgstr "" @@ -3250,7 +3261,7 @@ msgstr "" msgid "Could not leave chat." msgstr "Could not leave chat." -#: src/screens/Profile/ProfileFeed/index.tsx:73 +#: src/screens/Profile/ProfileFeed/index.tsx:80 msgid "Could not load feed" msgstr "" @@ -3335,7 +3346,7 @@ msgstr "" #: src/components/StarterPack/ProfileStarterPacks.tsx:207 #: src/components/StarterPack/ProfileStarterPacks.tsx:316 -#: src/Navigation.tsx:569 +#: src/Navigation.tsx:573 msgid "Create a starter pack" msgstr "" @@ -3350,6 +3361,8 @@ msgstr "" #: src/components/WelcomeModal.tsx:158 #: src/components/WelcomeModal.tsx:166 +#: src/screens/GroupInviteLanding.tsx:94 +#: src/screens/GroupInviteLanding.tsx:101 #: src/screens/Messages/JoinRequest.tsx:310 #: src/view/com/auth/SplashScreen.tsx:107 #: src/view/com/auth/SplashScreen.web.tsx:118 @@ -3550,7 +3563,7 @@ msgid "Default icons" msgstr "" #: src/components/dms/MessageOverlays.tsx:184 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:783 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:787 #: src/screens/ProfileList/components/MoreOptionsMenu.tsx:275 #: src/screens/Settings/AppPasswords.tsx:312 #: src/screens/StarterPack/StarterPackScreen.tsx:615 @@ -3619,9 +3632,9 @@ msgstr "" msgid "Delete my account" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:767 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:769 -#: src/view/com/composer/Composer.tsx:1667 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:771 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:773 +#: src/view/com/composer/Composer.tsx:1761 msgid "Delete post" msgstr "" @@ -3638,11 +3651,11 @@ msgstr "" msgid "Delete this list?" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:780 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:784 msgid "Delete this post?" msgstr "" -#: src/components/Post/Embed/index.tsx:291 +#: src/components/Post/Embed/index.tsx:290 msgid "Deleted" msgstr "" @@ -3687,12 +3700,12 @@ msgstr "Description (1000 characters max)" msgid "Descriptive alt text" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:652 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:662 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:656 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:666 msgid "Detach quote" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:815 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:819 msgid "Detach quote post?" msgstr "" @@ -3780,9 +3793,9 @@ msgstr "" #: src/components/dialogs/lists/CreateOrEditListDialog.tsx:101 #: src/screens/Profile/Header/EditProfileDialog.tsx:82 -#: src/view/com/composer/Composer.tsx:1449 -#: src/view/com/composer/Composer.tsx:1493 -#: src/view/com/composer/Composer.tsx:1700 +#: src/view/com/composer/Composer.tsx:1543 +#: src/view/com/composer/Composer.tsx:1587 +#: src/view/com/composer/Composer.tsx:1794 #: src/view/com/composer/drafts/DraftItem.tsx:242 #: src/view/com/composer/drafts/DraftsButton.tsx:131 msgid "Discard" @@ -3793,14 +3806,14 @@ msgstr "" msgid "Discard changes?" msgstr "" -#: src/view/com/composer/Composer.tsx:1447 +#: src/view/com/composer/Composer.tsx:1541 #: src/view/com/composer/drafts/DraftItem.tsx:239 #: src/view/com/composer/drafts/DraftsButton.tsx:98 msgid "Discard draft?" msgstr "" -#: src/view/com/composer/Composer.tsx:1464 -#: src/view/com/composer/Composer.tsx:1692 +#: src/view/com/composer/Composer.tsx:1558 +#: src/view/com/composer/Composer.tsx:1786 msgid "Discard post?" msgstr "" @@ -3831,7 +3844,7 @@ msgstr "" msgid "Discussion" msgstr "Discussion" -#: src/components/Dialog/index.tsx:413 +#: src/components/Dialog/index.tsx:416 #: src/features/inviteFriends/components/FollowersPromoBanner.tsx:83 msgid "Dismiss" msgstr "" @@ -3840,7 +3853,7 @@ msgstr "" msgid "Dismiss banner" msgstr "" -#: src/view/com/composer/Composer.tsx:2575 +#: src/view/com/composer/Composer.tsx:2688 msgid "Dismiss error" msgstr "" @@ -3951,11 +3964,11 @@ msgstr "" msgid "Double tap or long press the message to add a reaction" msgstr "" -#: src/components/Dialog/index.tsx:414 +#: src/components/Dialog/index.tsx:417 msgid "Double tap to close the dialog" msgstr "" -#: src/screens/VideoFeed/index.tsx:1107 +#: src/screens/VideoFeed/index.tsx:1109 msgid "Double tap to like" msgstr "" @@ -4089,8 +4102,8 @@ msgstr "Edit group name" msgid "Edit image" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:748 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:761 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:752 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:765 msgid "Edit interaction settings" msgstr "" @@ -4126,7 +4139,7 @@ msgstr "" msgid "Edit moderation list" msgstr "" -#: src/Navigation.tsx:380 +#: src/Navigation.tsx:384 #: src/view/screens/Feeds.tsx:511 msgid "Edit My Feeds" msgstr "" @@ -4173,7 +4186,7 @@ msgstr "" msgid "Edit who can reply" msgstr "" -#: src/Navigation.tsx:574 +#: src/Navigation.tsx:578 msgid "Edit your starter pack" msgstr "" @@ -4229,8 +4242,8 @@ msgstr "" #: src/components/dialogs/Embed.tsx:105 #: src/components/dialogs/Embed.tsx:109 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:120 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:125 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:116 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:121 msgid "Embed post" msgstr "" @@ -4367,7 +4380,7 @@ msgstr "Enter your birthdate" msgid "Enter your email address" msgstr "" -#: src/screens/Login/LoginForm.tsx:245 +#: src/screens/Login/LoginForm.tsx:274 msgid "Enter your handle (e.g. alice.bsky.social)" msgstr "Enter your handle (e.g. alice.bsky.social)" @@ -4389,7 +4402,7 @@ msgstr "" msgid "Entertainment" msgstr "" -#: src/view/com/composer/Composer.tsx:2674 +#: src/view/com/composer/Composer.tsx:2796 #: src/view/com/util/error/ErrorScreen.tsx:40 msgid "Error" msgstr "" @@ -4423,8 +4436,8 @@ msgstr "" msgid "Error: {error}" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:726 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:728 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:730 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:732 msgid "Escalate post" msgstr "Escalate post" @@ -4493,11 +4506,11 @@ msgstr "" msgid "Expand post text" msgstr "" -#: src/screens/VideoFeed/index.tsx:983 +#: src/screens/VideoFeed/index.tsx:985 msgid "Expands or collapses post text" msgstr "" -#: src/lib/api/index.ts:782 +#: src/lib/api/index.ts:941 msgid "Expected uri to resolve to a record" msgstr "" @@ -4537,9 +4550,9 @@ msgstr "" msgid "Explicit sexual images." msgstr "" -#: src/Navigation.tsx:778 +#: src/Navigation.tsx:782 #: src/screens/Search/Shell.tsx:362 -#: src/view/shell/desktop/LeftNav.tsx:685 +#: src/view/shell/desktop/LeftNav.tsx:703 #: src/view/shell/Drawer.tsx:538 msgid "Explore" msgstr "" @@ -4579,7 +4592,7 @@ msgstr "" msgid "External media may allow websites to collect information about you and your device. No information is sent or requested until you press the \"play\" button." msgstr "" -#: src/Navigation.tsx:399 +#: src/Navigation.tsx:403 #: src/screens/Settings/ExternalMediaPreferences.tsx:35 msgid "External Media Preferences" msgstr "" @@ -4652,7 +4665,7 @@ msgstr "" msgid "Failed to delete message" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:223 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:227 msgid "Failed to delete post, please try again" msgstr "" @@ -4757,7 +4770,7 @@ msgstr "" msgid "Failed to mute group chat" msgstr "Failed to mute group chat" -#: src/state/queries/pinned-post.ts:75 +#: src/state/queries/pinned-post.ts:82 msgid "Failed to pin post" msgstr "" @@ -4803,7 +4816,7 @@ msgstr "" msgid "Failed to rescind your request. Please try again." msgstr "Failed to rescind your request. Please try again." -#: src/view/com/composer/Composer.tsx:671 +#: src/view/com/composer/Composer.tsx:738 msgid "Failed to save draft" msgstr "" @@ -4841,11 +4854,11 @@ msgstr "Failed to send report" msgid "Failed to submit appeal, please try again." msgstr "" -#: src/lib/api/index.ts:392 +#: src/lib/api/index.ts:500 msgid "Failed to submit community post. Please try again." msgstr "Failed to submit community post. Please try again." -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:255 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:259 msgid "Failed to toggle thread mute, please try again" msgstr "" @@ -4879,10 +4892,10 @@ msgstr "" msgid "Failed to update settings" msgstr "" -#: src/lib/media/video/upload.ts:73 -#: src/lib/media/video/upload.web.ts:88 -#: src/lib/media/video/upload.web.ts:93 -#: src/lib/media/video/upload.web.ts:103 +#: src/lib/media/video/upload.ts:74 +#: src/lib/media/video/upload.web.ts:89 +#: src/lib/media/video/upload.web.ts:94 +#: src/lib/media/video/upload.web.ts:104 msgid "Failed to upload video" msgstr "" @@ -4902,7 +4915,7 @@ msgstr "" msgid "False information about elections" msgstr "" -#: src/Navigation.tsx:300 +#: src/Navigation.tsx:304 msgid "Feed" msgstr "" @@ -4910,7 +4923,7 @@ msgstr "" #. placeholder {0}: sanitizeHandle(feed.creatorHandle, '@') #. placeholder {0}: sanitizeHandle(view.creator.handle, '@') #: src/components/FeedCard.tsx:170 -#: src/state/queries/feed.ts:134 +#: src/state/queries/feed.ts:138 #: src/view/com/feeds/FeedSourceCard.tsx:151 msgid "Feed by {0}" msgstr "" @@ -4939,20 +4952,20 @@ msgstr "" msgid "Feedback" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:306 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:329 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:310 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:333 msgctxt "toast" msgid "Feedback sent to feed operator" msgstr "" -#: src/Navigation.tsx:554 +#: src/Navigation.tsx:558 #: src/screens/SavedFeeds.tsx:114 #: src/screens/SavedFeeds.tsx:306 #: src/screens/Search/SearchResults.tsx:80 #: src/screens/StarterPack/StarterPackScreen.tsx:196 #: src/view/screens/Feeds.tsx:504 #: src/view/screens/Profile.tsx:270 -#: src/view/shell/desktop/LeftNav.tsx:718 +#: src/view/shell/desktop/LeftNav.tsx:736 #: src/view/shell/Drawer.tsx:654 msgid "Feeds" msgstr "" @@ -4962,6 +4975,10 @@ msgstr "" msgid "Feeds are custom algorithms that users build with a little coding expertise. <0>See this guide for more information." msgstr "" +#: src/components/intents/GroupInviteDialog.tsx:373 +msgid "Feeds to pin" +msgstr "Feeds to pin" + #: src/components/FeedCard.tsx:313 #: src/screens/SavedFeeds.tsx:94 #: src/screens/SavedFeeds.tsx:274 @@ -5032,8 +5049,8 @@ msgstr "" msgid "Find and invite friends" msgstr "Find and invite friends" -#: src/Navigation.tsx:463 -#: src/Navigation.tsx:596 +#: src/Navigation.tsx:467 +#: src/Navigation.tsx:600 msgid "Find Contacts" msgstr "" @@ -5078,7 +5095,7 @@ msgstr "" msgid "Finish" msgstr "" -#: src/screens/Login/LoginForm.tsx:283 +#: src/screens/Login/LoginForm.tsx:333 msgid "Finishing sign-in… complete it in your browser, or cancel." msgstr "Finishing sign-in… complete it in your browser, or cancel." @@ -5097,7 +5114,7 @@ msgstr "Focus the search field" #: src/screens/Messages/ConversationSettings/Member.tsx:170 #: src/screens/PostThread/components/ThreadItemAnchorFollowButton.tsx:157 #: src/screens/Profile/Header/ProfileHeaderStandard.tsx:439 -#: src/screens/VideoFeed/index.tsx:866 +#: src/screens/VideoFeed/index.tsx:868 #: src/view/com/notifications/NotificationFeedItem.tsx:873 #: src/view/com/notifications/NotificationFeedItem.tsx:880 msgid "Follow" @@ -5113,7 +5130,7 @@ msgstr "" msgid "Follow {displayName}" msgstr "Follow {displayName}" -#: src/screens/VideoFeed/index.tsx:845 +#: src/screens/VideoFeed/index.tsx:847 msgid "Follow {handle}" msgstr "" @@ -5196,7 +5213,7 @@ msgid "Followers can join" msgstr "Followers can join" #. placeholder {0}: route.params.name -#: src/Navigation.tsx:254 +#: src/Navigation.tsx:258 msgid "Followers of @{0} that you know" msgstr "" @@ -5212,7 +5229,7 @@ msgstr "" #: src/components/ProfileHoverCard/index.web.tsx:505 #: src/screens/PostThread/components/ThreadItemAnchorFollowButton.tsx:160 #: src/screens/Profile/Header/ProfileHeaderStandard.tsx:435 -#: src/screens/VideoFeed/index.tsx:864 +#: src/screens/VideoFeed/index.tsx:866 #: src/view/com/notifications/NotificationFeedItem.tsx:851 #: src/view/com/notifications/NotificationFeedItem.tsx:868 msgid "Following" @@ -5237,7 +5254,7 @@ msgstr "" msgid "Following {displayName}" msgstr "Following {displayName}" -#: src/screens/VideoFeed/index.tsx:844 +#: src/screens/VideoFeed/index.tsx:846 msgid "Following {handle}" msgstr "" @@ -5246,7 +5263,7 @@ msgstr "" msgid "Following feed preferences" msgstr "" -#: src/Navigation.tsx:386 +#: src/Navigation.tsx:390 #: src/screens/Settings/FollowingFeedPreferences.tsx:57 msgid "Following Feed Preferences" msgstr "" @@ -5296,8 +5313,8 @@ msgstr "" msgid "Forget the noise" msgstr "" -#: src/screens/Login/index.tsx:153 -#: src/screens/Login/index.tsx:169 +#: src/screens/Login/index.tsx:154 +#: src/screens/Login/index.tsx:170 msgid "Forgot Password" msgstr "" @@ -5430,7 +5447,7 @@ msgstr "" msgid "GIF" msgstr "" -#: src/view/com/composer/Composer.tsx:2679 +#: src/view/com/composer/Composer.tsx:2801 msgid "GIF uploaded" msgstr "" @@ -5455,9 +5472,9 @@ msgstr "" #: src/screens/ProfileList/components/ErrorScreen.tsx:35 #: src/screens/ProfileList/components/ErrorScreen.tsx:41 #: src/screens/VideoFeed/components/Header.tsx:163 -#: src/screens/VideoFeed/index.tsx:1168 -#: src/screens/VideoFeed/index.tsx:1172 -#: src/view/com/auth/LoggedOut.tsx:104 +#: src/screens/VideoFeed/index.tsx:1170 +#: src/screens/VideoFeed/index.tsx:1174 +#: src/view/com/auth/LoggedOut.tsx:108 #: src/view/com/profile/ProfileFollowers.tsx:211 #: src/view/com/profile/ProfileFollowers.tsx:212 #: src/view/screens/NotFound.tsx:51 @@ -5534,8 +5551,8 @@ msgstr "" #: src/components/dms/ConvoMenu.tsx:262 #: src/screens/Messages/components/MessagesListInfoPanel.tsx:98 #: src/screens/Messages/ConversationSettings/MemberMenu.tsx:194 -#: src/view/shell/desktop/LeftNav.tsx:340 -#: src/view/shell/desktop/LeftNav.tsx:346 +#: src/view/shell/desktop/LeftNav.tsx:343 +#: src/view/shell/desktop/LeftNav.tsx:349 msgid "Go to profile" msgstr "" @@ -5605,7 +5622,7 @@ msgctxt "toast" msgid "Group chat name updated" msgstr "Group chat name updated" -#: src/Navigation.tsx:523 +#: src/Navigation.tsx:527 #: src/screens/Messages/ConversationSettings/index.tsx:113 msgid "Group chat settings" msgstr "Group chat settings" @@ -5630,6 +5647,11 @@ msgstr "Group chats are only available to users 18 and over." msgid "Group chats can only have a maximum of {0, plural, other {# people}}." msgstr "Group chats can only have a maximum of {0, plural, other {# people}}." +#: src/components/intents/GroupInviteDialog.tsx:282 +#: src/screens/GroupInviteLanding.tsx:68 +msgid "Group invite" +msgstr "Group invite" + #: src/components/dialogs/SearchablePeopleList.tsx:565 msgid "Group is locked" msgstr "Group is locked" @@ -5698,7 +5720,7 @@ msgstr "" msgid "Harming or endangering minors" msgstr "" -#: src/Navigation.tsx:507 +#: src/Navigation.tsx:511 msgid "Hashtag" msgstr "" @@ -5744,7 +5766,7 @@ msgstr "" msgid "Hidden" msgstr "" -#: src/screens/VideoFeed/index.tsx:643 +#: src/screens/VideoFeed/index.tsx:644 msgid "Hidden by your moderation settings." msgstr "" @@ -5792,8 +5814,8 @@ msgstr "" msgid "Hide post" msgstr "Hide post" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:628 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:638 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:632 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:642 msgid "Hide reply for everyone" msgstr "" @@ -5810,14 +5832,14 @@ msgstr "" msgid "Hide this post?" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:822 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:826 msgid "Hide this reply?" msgstr "" #: src/components/Post/Translated/index.tsx:216 #: src/components/Post/Translated/index.tsx:350 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:531 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:533 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:535 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:537 msgid "Hide translation" msgstr "Hide translation" @@ -5888,10 +5910,10 @@ msgstr "" msgid "Hold up! We’re gradually giving access to video, and you’re still waiting in line. Check back soon!" msgstr "" -#: src/Navigation.tsx:773 -#: src/Navigation.tsx:794 +#: src/Navigation.tsx:777 +#: src/Navigation.tsx:798 #: src/view/shell/bottom-bar/BottomBar.tsx:193 -#: src/view/shell/desktop/LeftNav.tsx:675 +#: src/view/shell/desktop/LeftNav.tsx:693 #: src/view/shell/Drawer.tsx:564 msgid "Home" msgstr "" @@ -5976,7 +5998,7 @@ msgstr "If you have your own domain, you can use that as your handle. This lets msgid "If you need to update your email, <0>click here." msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:781 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:785 msgid "If you remove this post, you won't be able to recover it." msgstr "" @@ -6167,7 +6189,7 @@ msgstr "Invalid group chat code." msgid "Invalid handle. Please try a different one." msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:398 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:402 msgctxt "toast" msgid "Invalid interaction settings." msgstr "" @@ -6279,7 +6301,7 @@ msgstr "Invited" msgid "Invites, but personal" msgstr "" -#: src/Navigation.tsx:330 +#: src/Navigation.tsx:334 msgid "iOS 26 Crash Regression" msgstr "iOS 26 Crash Regression" @@ -6305,7 +6327,7 @@ msgid "It's just you right now! Add more people to your starter pack by searchin msgstr "" #. placeholder {0}: videoState.jobId -#: src/view/com/composer/Composer.tsx:2594 +#: src/view/com/composer/Composer.tsx:2716 msgid "Job ID: {0}" msgstr "" @@ -6321,6 +6343,11 @@ msgstr "Join" msgid "Join Blacksky" msgstr "Join Blacksky" +#: src/components/intents/GroupInviteDialog.tsx:260 +#: src/components/intents/GroupInviteDialog.tsx:323 +msgid "Join group" +msgstr "Join group" + #: src/components/intents/GroupChatJoinDialog.tsx:72 #: src/components/intents/GroupChatJoinDialog.tsx:464 msgid "Join group chat" @@ -6335,8 +6362,8 @@ msgstr "Join request rescinded." msgid "Journalism" msgstr "" -#: src/view/com/composer/Composer.tsx:1497 -#: src/view/com/composer/Composer.tsx:1507 +#: src/view/com/composer/Composer.tsx:1591 +#: src/view/com/composer/Composer.tsx:1601 #: src/view/com/composer/drafts/DraftsButton.tsx:135 msgid "Keep editing" msgstr "" @@ -6353,8 +6380,8 @@ msgstr "Kick member" #: src/components/moderation/LabelDialog/index.tsx:119 #: src/components/moderation/LabelDialog/index.tsx:237 #: src/components/moderation/LabelDialog/index.tsx:244 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:719 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:721 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:723 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:725 msgid "Label post" msgstr "Label post" @@ -6392,7 +6419,7 @@ msgstr "" msgid "Labels on your content" msgstr "" -#: src/Navigation.tsx:227 +#: src/Navigation.tsx:231 msgid "Language Settings" msgstr "" @@ -6520,8 +6547,8 @@ msgstr "" msgid "Let me choose" msgstr "" -#: src/screens/Login/index.tsx:154 -#: src/screens/Login/index.tsx:170 +#: src/screens/Login/index.tsx:155 +#: src/screens/Login/index.tsx:171 msgid "Let's get your password reset!" msgstr "" @@ -6546,7 +6573,7 @@ msgstr "" #. Accessibility label for the like button when the post has not been liked, verb form followed by number of likes and noun form #. placeholder {0}: post.likeCount || 0 -#: src/components/PostControls/index.tsx:290 +#: src/components/PostControls/index.tsx:291 msgid "Like ({0, plural, one {# like} other {# likes}})" msgstr "" @@ -6567,12 +6594,12 @@ msgstr "" msgid "Like this labeler" msgstr "" -#: src/Navigation.tsx:305 -#: src/Navigation.tsx:310 +#: src/Navigation.tsx:309 +#: src/Navigation.tsx:314 msgid "Liked by" msgstr "" -#: src/screens/Post/PostLikedBy.tsx:31 +#: src/screens/Post/PostLikedBy.tsx:56 #: src/screens/Profile/ProfileLabelerLikedBy.tsx:22 #: src/view/screens/ProfileFeedLikedBy.tsx:22 msgid "Liked By" @@ -6605,7 +6632,7 @@ msgstr "" msgid "Likes of your reposts" msgstr "" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:489 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:491 msgid "Likes on this post" msgstr "" @@ -6618,7 +6645,7 @@ msgstr "" msgid "Link copied to clipboard" msgstr "Link copied to clipboard" -#: src/Navigation.tsx:260 +#: src/Navigation.tsx:264 msgid "List" msgstr "" @@ -6704,11 +6731,11 @@ msgctxt "toast" msgid "List unmuted" msgstr "" -#: src/Navigation.tsx:181 +#: src/Navigation.tsx:185 #: src/view/screens/Lists.tsx:60 #: src/view/screens/Profile.tsx:263 #: src/view/screens/Profile.tsx:272 -#: src/view/shell/desktop/LeftNav.tsx:728 +#: src/view/shell/desktop/LeftNav.tsx:746 #: src/view/shell/Drawer.tsx:669 msgid "Lists" msgstr "" @@ -6769,7 +6796,7 @@ msgstr "Load more" msgid "Load new notifications" msgstr "" -#: src/screens/Profile/ProfileFeed/index.tsx:206 +#: src/screens/Profile/ProfileFeed/index.tsx:213 #: src/screens/Profile/Sections/Feed.tsx:117 #: src/screens/ProfileList/FeedSection.tsx:113 #: src/view/com/feeds/CommunityFeedPage.tsx:310 @@ -6792,7 +6819,11 @@ msgstr "" msgid "Loading post interaction settings..." msgstr "" -#: src/components/Post/Embed/index.tsx:263 +#: src/components/intents/GroupInviteDialog.tsx:406 +msgid "Loading your saved feeds…" +msgstr "Loading your saved feeds…" + +#: src/components/Post/Embed/index.tsx:262 #: src/view/com/composer/text-input/mobile/Autocomplete.tsx:60 #: src/view/screens/SupportReturn.tsx:73 msgid "Loading..." @@ -6818,7 +6849,7 @@ msgstr "Lock this group chat" msgid "Locked" msgstr "Locked" -#: src/Navigation.tsx:340 +#: src/Navigation.tsx:344 msgid "Log" msgstr "" @@ -6830,8 +6861,8 @@ msgstr "" msgid "Logged-out visibility" msgstr "" -#: src/screens/Login/LoginForm.tsx:316 -#: src/screens/Login/LoginForm.tsx:323 +#: src/screens/Login/LoginForm.tsx:366 +#: src/screens/Login/LoginForm.tsx:373 msgid "Login" msgstr "Login" @@ -6939,6 +6970,10 @@ msgstr "" msgid "Media" msgstr "" +#: src/view/com/composer/Composer.tsx:2361 +msgid "Media isn’t available in private spaces yet." +msgstr "Media isn’t available in private spaces yet." + #. Example: "Media stored on John's iPhone" #. placeholder {0}: draft.draft.deviceName #: src/view/com/composer/drafts/DraftItem.tsx:119 @@ -7044,7 +7079,7 @@ msgstr "Message is too long ({graphemeCount}/{MAX_DM_GRAPHEME_LENGTH})" msgid "Message options" msgstr "" -#: src/Navigation.tsx:788 +#: src/Navigation.tsx:792 msgid "Messages" msgstr "" @@ -7072,7 +7107,7 @@ msgstr "" msgid "Missing media" msgstr "" -#: src/Navigation.tsx:186 +#: src/Navigation.tsx:190 #: src/screens/Moderation/index.tsx:100 msgid "Moderation" msgstr "" @@ -7116,7 +7151,7 @@ msgstr "" msgid "Moderation lists" msgstr "" -#: src/Navigation.tsx:191 +#: src/Navigation.tsx:195 #: src/view/screens/ModerationModlists.tsx:60 msgid "Moderation Lists" msgstr "" @@ -7125,7 +7160,7 @@ msgstr "" msgid "moderation settings" msgstr "" -#: src/Navigation.tsx:320 +#: src/Navigation.tsx:324 msgid "Moderation states" msgstr "" @@ -7168,6 +7203,11 @@ msgstr "" msgid "Move feed up" msgstr "" +#: src/view/com/composer/Composer.tsx:2701 +#: src/view/com/composer/Composer.tsx:2703 +msgid "Move your account to Blacksky" +msgstr "Move your account to Blacksky" + #: src/lib/interests.ts:64 msgid "Movies" msgstr "" @@ -7193,8 +7233,8 @@ msgstr "" msgid "Mute {0}" msgstr "Mute {0}" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:691 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:697 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:695 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:701 #: src/view/com/profile/ProfileMenu.tsx:443 #: src/view/com/profile/ProfileMenu.tsx:450 msgid "Mute account" @@ -7250,13 +7290,13 @@ msgstr "" msgid "Mute this word until you unmute it" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:594 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:597 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:598 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:601 msgid "Mute thread" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:607 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:609 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:611 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:613 msgid "Mute words & tags" msgstr "" @@ -7268,7 +7308,7 @@ msgstr "Muted" msgid "Muted accounts" msgstr "" -#: src/Navigation.tsx:196 +#: src/Navigation.tsx:200 #: src/view/screens/ModerationMutedAccounts.tsx:107 msgid "Muted Accounts" msgstr "" @@ -7437,7 +7477,7 @@ msgstr "" msgid "New password" msgstr "" -#: src/screens/Profile/ProfileFeed/index.tsx:217 +#: src/screens/Profile/ProfileFeed/index.tsx:224 #: src/screens/ProfileList/index.tsx:237 #: src/screens/ProfileList/index.tsx:280 #: src/view/com/feeds/CommunityFeedPage.tsx:320 @@ -7448,7 +7488,7 @@ msgid "New post" msgstr "" #: src/view/com/feeds/FeedPage.tsx:179 -#: src/view/shell/desktop/LeftNav.tsx:605 +#: src/view/shell/desktop/LeftNav.tsx:623 msgctxt "action" msgid "New post" msgstr "" @@ -7571,7 +7611,7 @@ msgid "No image" msgstr "" #: src/components/LikedByList.tsx:84 -#: src/view/com/post-thread/PostLikedBy.tsx:84 +#: src/view/com/post-thread/PostLikedBy.tsx:85 #: src/view/screens/Profile.tsx:575 msgid "No likes yet" msgstr "" @@ -7647,7 +7687,7 @@ msgstr "" msgid "No preference" msgstr "No preference" -#: src/view/com/post-thread/PostQuotes.tsx:107 +#: src/view/com/post-thread/PostQuotes.tsx:108 msgid "No quotes yet" msgstr "" @@ -7660,7 +7700,7 @@ msgstr "No recent GIFs yet. Pick one to see it here." msgid "No replies yet" msgstr "" -#: src/view/com/post-thread/PostRepostedBy.tsx:90 +#: src/view/com/post-thread/PostRepostedBy.tsx:91 msgid "No reposts yet" msgstr "" @@ -7716,15 +7756,15 @@ msgid "Nobody" msgstr "" #: src/components/LikedByList.tsx:86 -#: src/view/com/post-thread/PostLikedBy.tsx:86 +#: src/view/com/post-thread/PostLikedBy.tsx:87 msgid "Nobody has liked this yet. Maybe you should be the first!" msgstr "" -#: src/view/com/post-thread/PostQuotes.tsx:109 +#: src/view/com/post-thread/PostQuotes.tsx:110 msgid "Nobody has quoted this yet. Maybe you should be the first!" msgstr "" -#: src/view/com/post-thread/PostRepostedBy.tsx:92 +#: src/view/com/post-thread/PostRepostedBy.tsx:93 msgid "Nobody has reposted this yet. Maybe you should be the first!" msgstr "" @@ -7757,7 +7797,7 @@ msgstr "Not followed by anyone you’re following" msgid "Not found" msgstr "Not found" -#: src/Navigation.tsx:176 +#: src/Navigation.tsx:180 #: src/view/screens/Profile.tsx:147 msgid "Not Found" msgstr "" @@ -7776,7 +7816,7 @@ msgstr "" msgid "Note: {0} is an open and public network. This setting only limits the visibility of your content on the {1} app and website, and other apps may not respect this setting. Your content may still be shown to logged-out users by other apps and websites." msgstr "Note: {0} is an open and public network. This setting only limits the visibility of your content on the {1} app and website, and other apps may not respect this setting. Your content may still be shown to logged-out users by other apps and websites." -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:135 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:131 msgid "Note: This post is only visible to logged-in users." msgstr "" @@ -7786,8 +7826,8 @@ msgid "Nothing saved yet" msgstr "" #: src/components/dialogs/NotificationSettingsDialog.tsx:64 -#: src/Navigation.tsx:470 -#: src/Navigation.tsx:549 +#: src/Navigation.tsx:474 +#: src/Navigation.tsx:553 #: src/view/screens/Notifications.tsx:134 msgid "Notification settings" msgstr "" @@ -7797,15 +7837,15 @@ msgstr "" msgid "Notification sounds" msgstr "" -#: src/Navigation.tsx:544 -#: src/Navigation.tsx:783 +#: src/Navigation.tsx:548 +#: src/Navigation.tsx:787 #: src/screens/Notifications/ActivityList.tsx:31 #: src/screens/Settings/NotificationSettings/index.tsx:105 #: src/screens/Settings/Settings.tsx:199 #: src/screens/Settings/Settings.tsx:202 #: src/view/screens/Notifications.tsx:128 #: src/view/shell/bottom-bar/BottomBar.tsx:268 -#: src/view/shell/desktop/LeftNav.tsx:695 +#: src/view/shell/desktop/LeftNav.tsx:713 #: src/view/shell/Drawer.tsx:617 msgid "Notifications" msgstr "" @@ -7850,7 +7890,7 @@ msgstr "" #: src/components/dms/InitiateChatFlow.tsx:726 #: src/components/dms/MessageItem.tsx:722 #: src/screens/Login/PasswordUpdatedForm.tsx:37 -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:664 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:666 msgid "Okay" msgstr "" @@ -7881,11 +7921,11 @@ msgstr "One of the selected recipients does not allow group chats." msgid "One of the selected recipients has blocked you and cannot be messaged." msgstr "One of the selected recipients has blocked you and cannot be messaged." -#: src/view/com/composer/Composer.tsx:887 +#: src/view/com/composer/Composer.tsx:954 msgid "One or more GIFs is missing alt text." msgstr "" -#: src/view/com/composer/Composer.tsx:884 +#: src/view/com/composer/Composer.tsx:951 msgid "One or more images is missing alt text." msgstr "" @@ -7897,11 +7937,11 @@ msgstr "" msgid "One or more of your selected files are too large. Maximum size is {VIDEO_MAX_SIZE_MB} MB." msgstr "One or more of your selected files are too large. Maximum size is {VIDEO_MAX_SIZE_MB} MB." -#: src/view/com/composer/Composer.tsx:682 +#: src/view/com/composer/Composer.tsx:749 msgid "One or more posts are too long to save as a draft. {MAX_DRAFT_GRAPHEME_LENGTH, plural, one {The maximum number of characters is # character.} other {The maximum number of characters is # characters.}}" msgstr "" -#: src/view/com/composer/Composer.tsx:894 +#: src/view/com/composer/Composer.tsx:961 msgid "One or more videos is missing alt text." msgstr "" @@ -7919,7 +7959,7 @@ msgstr "" #. placeholder {0}: result.accepted.length #. placeholder {1}: next.length #. placeholder {2}: next.length -#: src/view/com/composer/Composer.tsx:242 +#: src/view/com/composer/Composer.tsx:258 msgid "Only {0} of {1} {2, plural, one {image} other {images}} added; limit is {MAX_GALLERY_IMAGES}" msgstr "Only {0} of {1} {2, plural, one {image} other {images}} added; limit is {MAX_GALLERY_IMAGES}" @@ -7955,10 +7995,14 @@ msgstr "Only people {0} follows can join." msgid "Only people the chat owner follows can join" msgstr "Only people the chat owner follows can join" -#: src/components/CommunityOnlyBadge.tsx:38 +#: src/components/CommunityOnlyBadge.tsx:28 msgid "Only visible to members of the Blacksky community" msgstr "Only visible to members of the Blacksky community" +#: src/components/CommunityOnlyBadge.tsx:27 +msgid "Only visible to members of this community" +msgstr "Only visible to members of this community" + #: src/view/com/composer/videos/SubtitleFilePicker.tsx:41 msgid "Only WebVTT (.vtt) files are supported" msgstr "" @@ -8012,10 +8056,15 @@ msgstr "" #: src/screens/Messages/components/MessageComposer.tsx:204 #: src/screens/Messages/components/MessageInput.web.tsx:174 -#: src/view/com/composer/Composer.tsx:2234 +#: src/view/com/composer/Composer.tsx:2340 msgid "Open emoji picker" msgstr "" +#: src/components/intents/GroupInviteDialog.tsx:462 +#: src/components/intents/GroupInviteDialog.tsx:467 +msgid "Open feed" +msgstr "Open feed" + #: src/screens/Profile/components/ProfileFeedHeader.tsx:192 msgid "Open feed info screen" msgstr "" @@ -8081,7 +8130,7 @@ msgstr "Open QR code scanner" msgid "Open settings" msgstr "Open settings" -#: src/components/PostControls/ShareMenu/index.tsx:100 +#: src/components/PostControls/ShareMenu/index.tsx:96 msgid "Open share menu" msgstr "" @@ -8329,6 +8378,8 @@ msgid "Party GIFs" msgstr "Party GIFs" #: src/screens/Deactivated.tsx:219 +#: src/screens/Login/LoginForm.tsx:284 +#: src/screens/Login/LoginForm.tsx:289 #: src/screens/Settings/AccountSettings.tsx:141 #: src/screens/Settings/AccountSettings.tsx:145 #: src/screens/Settings/AppPasswords.tsx:106 @@ -8349,7 +8400,7 @@ msgstr "" msgid "Password must be at least 8 characters long." msgstr "" -#: src/screens/Login/index.tsx:183 +#: src/screens/Login/index.tsx:184 msgid "Password updated" msgstr "" @@ -8389,12 +8440,12 @@ msgid "People {ownerName} follows can request to join" msgstr "People {ownerName} follows can request to join" #. placeholder {0}: route.params.name -#: src/Navigation.tsx:247 +#: src/Navigation.tsx:251 msgid "People followed by @{0}" msgstr "" #. placeholder {0}: route.params.name -#: src/Navigation.tsx:240 +#: src/Navigation.tsx:244 msgid "People following @{0}" msgstr "" @@ -8458,6 +8509,10 @@ msgstr "" msgid "Photography" msgstr "" +#: src/lib/api/space-post.ts:40 +msgid "Photos, videos, and GIFs are not available in private spaces yet." +msgstr "Photos, videos, and GIFs are not available in private spaces yet." + #: src/features/inviteFriends/components/ThemePicker.tsx:37 msgid "Pick a color theme" msgstr "Pick a color theme" @@ -8473,6 +8528,11 @@ msgstr "" msgid "Pin feed" msgstr "" +#: src/components/intents/GroupInviteDialog.tsx:426 +#: src/components/intents/GroupInviteDialog.tsx:437 +msgid "Pin selected feeds" +msgstr "Pin selected feeds" + #: src/screens/ProfileList/components/Header.tsx:151 #: src/screens/ProfileList/components/Header.tsx:158 msgid "Pin to home" @@ -8482,8 +8542,8 @@ msgstr "" msgid "Pin to Home" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:500 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:505 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:504 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:509 msgid "Pin to your profile" msgstr "" @@ -8634,6 +8694,10 @@ msgstr "" msgid "Please enter your new email address." msgstr "" +#: src/screens/Login/LoginForm.tsx:153 +msgid "Please enter your password" +msgstr "Please enter your password" + #: src/screens/Settings/components/DeactivateAccountDialog.tsx:140 msgid "Please enter your password to continue." msgstr "Please enter your password to continue." @@ -8643,7 +8707,7 @@ msgstr "Please enter your password to continue." msgid "Please enter your password." msgstr "Please enter your password." -#: src/screens/Login/LoginForm.tsx:70 +#: src/screens/Login/LoginForm.tsx:74 msgid "Please enter your username or handle" msgstr "Please enter your username or handle" @@ -8708,7 +8772,7 @@ msgstr "" msgid "Porn" msgstr "" -#: src/screens/PostThread/index.tsx:553 +#: src/screens/PostThread/index.tsx:555 msgctxt "description" msgid "Post" msgstr "" @@ -8723,7 +8787,7 @@ msgstr "" msgid "Post a video" msgstr "" -#: src/view/com/composer/Composer.tsx:1506 +#: src/view/com/composer/Composer.tsx:1600 msgid "Post anyway" msgstr "Post anyway" @@ -8732,27 +8796,27 @@ msgid "Post blocked" msgstr "" #. placeholder {0}: route.params.name -#: src/Navigation.tsx:273 -#: src/Navigation.tsx:280 -#: src/Navigation.tsx:287 -#: src/Navigation.tsx:294 +#: src/Navigation.tsx:277 +#: src/Navigation.tsx:284 +#: src/Navigation.tsx:291 +#: src/Navigation.tsx:298 msgid "Post by @{0}" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:200 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:204 msgctxt "toast" msgid "Post deleted" msgstr "" -#: src/lib/api/index.ts:218 -#: src/lib/api/index.ts:441 +#: src/lib/api/index.ts:313 +#: src/lib/api/index.ts:560 msgid "Post failed to upload. Please check your Internet connection and try again." msgstr "" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:132 -#: src/screens/PostThread/components/ThreadItemPost.tsx:117 -#: src/screens/PostThread/components/ThreadItemTreePost.tsx:110 -#: src/screens/VideoFeed/index.tsx:547 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:134 +#: src/screens/PostThread/components/ThreadItemPost.tsx:118 +#: src/screens/PostThread/components/ThreadItemTreePost.tsx:111 +#: src/screens/VideoFeed/index.tsx:548 msgid "Post has been deleted" msgstr "" @@ -8774,7 +8838,7 @@ msgstr "" msgid "Post interaction settings" msgstr "" -#: src/Navigation.tsx:207 +#: src/Navigation.tsx:211 #: src/screens/ModerationInteractionSettings/index.tsx:35 msgid "Post Interaction Settings" msgstr "" @@ -8794,20 +8858,29 @@ msgstr "Post link" msgid "Post not found" msgstr "" -#: src/state/queries/pinned-post.ts:59 +#: src/state/queries/pinned-post.ts:66 msgctxt "toast" msgid "Post pinned" msgstr "" +#. placeholder {0}: contextualCommunityFeedTarget.name +#: src/view/com/composer/PostTargetControls.tsx:68 +msgid "Post publicly or to {0}" +msgstr "Post publicly or to {0}" + #: src/components/PostControls/BookmarkButton.tsx:67 msgid "Post saved" msgstr "" -#: src/state/queries/pinned-post.ts:61 +#: src/state/queries/pinned-post.ts:68 msgctxt "toast" msgid "Post unpinned" msgstr "" +#: src/lib/api/space-post.ts:99 +msgid "Posting to the private feed..." +msgstr "Posting to the private feed..." + #: src/components/activity-notifications/SubscribeProfileDialog.tsx:261 #: src/components/activity-notifications/SubscribeProfileDialog.tsx:273 #: src/screens/ProfileList/index.tsx:167 @@ -8876,8 +8949,8 @@ msgstr "" msgid "Privacy and security" msgstr "" -#: src/Navigation.tsx:447 -#: src/Navigation.tsx:455 +#: src/Navigation.tsx:451 +#: src/Navigation.tsx:459 #: src/screens/Settings/ActivityPrivacySettings.tsx:41 #: src/screens/Settings/PrivacyAndSecuritySettings.tsx:51 msgid "Privacy and Security" @@ -8887,7 +8960,7 @@ msgstr "" msgid "Privacy and Security settings" msgstr "" -#: src/Navigation.tsx:355 +#: src/Navigation.tsx:359 #: src/screens/Settings/AboutSettings.tsx:93 #: src/screens/Settings/AboutSettings.tsx:96 #: src/view/screens/PrivacyPolicy.tsx:25 @@ -8900,15 +8973,15 @@ msgstr "" msgid "Privacy violation of a minor" msgstr "" -#: src/view/com/composer/Composer.tsx:2668 +#: src/view/com/composer/Composer.tsx:2790 msgid "Processing GIF..." msgstr "" -#: src/view/com/composer/Composer.tsx:2670 +#: src/view/com/composer/Composer.tsx:2792 msgid "Processing video..." msgstr "" -#: src/lib/api/index.ts:68 +#: src/lib/api/index.ts:127 #: src/screens/Login/ForgotPasswordForm.tsx:150 #: src/view/screens/SupportStripeCheckout.web.tsx:194 msgid "Processing..." @@ -8920,7 +8993,7 @@ msgstr "" #: src/screens/Profile/components/ProfileStatusError.tsx:144 #: src/view/shell/bottom-bar/BottomBar.tsx:311 -#: src/view/shell/desktop/LeftNav.tsx:751 +#: src/view/shell/desktop/LeftNav.tsx:769 #: src/view/shell/Drawer.tsx:92 #: src/view/shell/Drawer.tsx:720 msgid "Profile" @@ -8958,22 +9031,22 @@ msgid "Public, sharable lists of users to mute or block in bulk." msgstr "" #. Accessibility label for button to publish a single post -#: src/view/com/composer/Composer.tsx:1830 +#: src/view/com/composer/Composer.tsx:1924 msgid "Publish post" msgstr "" #. Accessibility label for button to publish multiple posts in a thread -#: src/view/com/composer/Composer.tsx:1825 +#: src/view/com/composer/Composer.tsx:1919 msgid "Publish posts" msgstr "" #. Accessibility label for button to publish multiple replies in a thread -#: src/view/com/composer/Composer.tsx:1814 +#: src/view/com/composer/Composer.tsx:1908 msgid "Publish replies" msgstr "" #. Accessibility label for button to publish a single reply -#: src/view/com/composer/Composer.tsx:1819 +#: src/view/com/composer/Composer.tsx:1913 msgid "Publish reply" msgstr "" @@ -9014,11 +9087,11 @@ msgstr "" msgid "Quote post" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:349 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:353 msgid "Quote post was re-attached" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:348 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:352 msgid "Quote post was successfully detached" msgstr "" @@ -9030,13 +9103,13 @@ msgid "Quote posts disabled" msgstr "" #: src/lib/hooks/useNotificationHandler.ts:188 -#: src/screens/Post/PostQuotes.tsx:31 +#: src/screens/Post/PostQuotes.tsx:56 #: src/screens/Settings/NotificationSettings/index.tsx:183 #: src/screens/Settings/NotificationSettings/index.tsx:292 msgid "Quotes" msgstr "" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:470 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:472 msgid "Quotes of this post" msgstr "" @@ -9048,8 +9121,8 @@ msgstr "" msgid "Rate limit exceeded. Please try again later." msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:652 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:661 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:656 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:665 msgid "Re-attach quote" msgstr "" @@ -9087,11 +9160,11 @@ msgstr "Reactivating will restore visibility of your profile and posts to other msgid "Read {0, plural, one {# more reply} other {# more replies}}" msgstr "" -#: src/screens/VideoFeed/index.tsx:984 +#: src/screens/VideoFeed/index.tsx:986 msgid "Read less" msgstr "" -#: src/screens/VideoFeed/index.tsx:984 +#: src/screens/VideoFeed/index.tsx:986 msgid "Read more" msgstr "" @@ -9343,11 +9416,11 @@ msgstr "" msgid "Remove your verification for this account?" msgstr "" -#: src/components/Post/Embed/index.tsx:237 +#: src/components/Post/Embed/index.tsx:236 msgid "Removed by author" msgstr "" -#: src/components/Post/Embed/index.tsx:235 +#: src/components/Post/Embed/index.tsx:234 msgid "Removed by you" msgstr "" @@ -9450,14 +9523,14 @@ msgstr "" msgid "Reply" msgstr "Reply" -#: src/view/com/composer/Composer.tsx:1842 +#: src/view/com/composer/Composer.tsx:1936 msgctxt "action" msgid "Reply" msgstr "" #. Accessibility label for the reply button, verb form followed by number of replies and noun form #. placeholder {0}: post.replyCount || 0 -#: src/components/PostControls/index.tsx:245 +#: src/components/PostControls/index.tsx:246 msgid "Reply ({0, plural, one {# reply} other {# replies}})" msgstr "" @@ -9479,12 +9552,12 @@ msgstr "" msgid "Reply sorting" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:386 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:390 msgctxt "toast" msgid "Reply visibility updated" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:385 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:389 msgid "Reply was successfully hidden" msgstr "" @@ -9525,8 +9598,8 @@ msgstr "" msgid "Report message" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:735 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:737 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:739 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:741 msgid "Report post" msgstr "" @@ -9605,7 +9678,7 @@ msgstr "" msgid "Repost or quote post" msgstr "" -#: src/screens/Post/PostRepostedBy.tsx:31 +#: src/screens/Post/PostRepostedBy.tsx:56 msgid "Reposted By" msgstr "" @@ -9632,7 +9705,7 @@ msgstr "" msgid "Reposts disabled" msgstr "Reposts disabled" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:449 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:451 msgid "Reposts of this post" msgstr "" @@ -9673,7 +9746,7 @@ msgstr "Requested" msgid "Requests" msgstr "Requests" -#: src/Navigation.tsx:528 +#: src/Navigation.tsx:532 #: src/screens/Messages/JoinRequests.tsx:415 msgid "Requests to join" msgstr "Requests to join" @@ -9802,7 +9875,7 @@ msgstr "" #: src/screens/ProfileList/components/ErrorScreen.tsx:36 #: src/screens/Settings/components/ChangeHandleDialog.tsx:637 -#: src/screens/VideoFeed/index.tsx:1169 +#: src/screens/VideoFeed/index.tsx:1171 #: src/view/screens/NotFound.tsx:54 msgid "Returns to previous page" msgstr "" @@ -9853,22 +9926,22 @@ msgstr "Save birthdate" #: src/screens/SavedFeeds.tsx:126 #: src/screens/SavedFeeds.tsx:314 #: src/screens/SavedFeeds.tsx:318 -#: src/view/com/composer/Composer.tsx:1487 +#: src/view/com/composer/Composer.tsx:1581 #: src/view/com/composer/drafts/DraftsButton.tsx:125 msgid "Save changes" msgstr "" -#: src/view/com/composer/Composer.tsx:1459 +#: src/view/com/composer/Composer.tsx:1553 #: src/view/com/composer/drafts/DraftsButton.tsx:93 msgid "Save changes?" msgstr "" -#: src/view/com/composer/Composer.tsx:1487 +#: src/view/com/composer/Composer.tsx:1581 #: src/view/com/composer/drafts/DraftsButton.tsx:125 msgid "Save draft" msgstr "" -#: src/view/com/composer/Composer.tsx:1461 +#: src/view/com/composer/Composer.tsx:1555 #: src/view/com/composer/drafts/DraftsButton.tsx:95 msgid "Save draft?" msgstr "" @@ -9899,7 +9972,7 @@ msgstr "" msgid "Save to my feeds" msgstr "" -#: src/view/shell/desktop/LeftNav.tsx:738 +#: src/view/shell/desktop/LeftNav.tsx:756 #: src/view/shell/Drawer.tsx:695 msgctxt "link to bookmarks screen" msgid "Saved" @@ -9910,7 +9983,7 @@ msgstr "" msgid "Saved Feeds" msgstr "" -#: src/Navigation.tsx:588 +#: src/Navigation.tsx:592 #: src/screens/Bookmarks/index.tsx:59 msgid "Saved Posts" msgstr "" @@ -9941,7 +10014,7 @@ msgstr "Scan" #: src/features/inviteFriends/InviteScannerScreen.tsx:83 #: src/features/inviteFriends/InviteScannerScreen.web.tsx:23 -#: src/Navigation.tsx:325 +#: src/Navigation.tsx:329 msgid "Scan QR code" msgstr "Scan QR code" @@ -9976,7 +10049,7 @@ msgstr "" #. placeholder {0}: profile.handle #. placeholder {0}: route.params.name -#: src/Navigation.tsx:266 +#: src/Navigation.tsx:270 #: src/screens/Profile/ProfileSearch.tsx:37 msgid "Search @{0}'s posts" msgstr "" @@ -10190,7 +10263,7 @@ msgstr "Select domain" msgid "Select duration" msgstr "" -#: src/screens/Login/index.tsx:143 +#: src/screens/Login/index.tsx:144 msgid "Select from an existing account" msgstr "" @@ -10351,10 +10424,10 @@ msgstr "" msgid "Send verification email" msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:116 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:122 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:105 -#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:111 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:112 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:118 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:101 +#: src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx:107 msgid "Send via direct message" msgstr "" @@ -10404,9 +10477,9 @@ msgstr "" msgid "Sets email for password reset" msgstr "" -#: src/Navigation.tsx:222 +#: src/Navigation.tsx:226 #: src/screens/Settings/Settings.tsx:94 -#: src/view/shell/desktop/LeftNav.tsx:761 +#: src/view/shell/desktop/LeftNav.tsx:779 #: src/view/shell/Drawer.tsx:733 msgid "Settings" msgstr "" @@ -10485,8 +10558,8 @@ msgstr "" msgid "Share anyway" msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:176 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:179 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:172 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:175 msgid "Share author DID" msgstr "" @@ -10517,8 +10590,8 @@ msgstr "" msgid "Share my profile" msgstr "Share my profile" -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:167 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:170 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:163 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:166 msgid "Share post at:// URI" msgstr "" @@ -10539,8 +10612,8 @@ msgstr "" msgid "Share this starter pack and help people join your community on Blacksky." msgstr "Share this starter pack and help people join your community on Blacksky." -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:132 -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:135 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:128 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:131 #: src/screens/ProfileList/components/MoreOptionsMenu.tsx:160 #: src/screens/ProfileList/components/MoreOptionsMenu.tsx:166 #: src/screens/StarterPack/StarterPackScreen.tsx:638 @@ -10554,7 +10627,7 @@ msgstr "" msgid "Share your contacts to find friends" msgstr "" -#: src/Navigation.tsx:335 +#: src/Navigation.tsx:339 msgid "Shared Preferences Tester" msgstr "" @@ -10573,8 +10646,8 @@ msgstr "" #: src/features/liveNow/components/LiveStatusDialog.tsx:318 #: src/features/liveNow/components/LiveStatusDialog.tsx:322 #: src/screens/List/ListHiddenScreen.tsx:194 -#: src/screens/VideoFeed/index.tsx:646 -#: src/screens/VideoFeed/index.tsx:652 +#: src/screens/VideoFeed/index.tsx:647 +#: src/screens/VideoFeed/index.tsx:653 msgid "Show anyway" msgstr "" @@ -10600,8 +10673,8 @@ msgstr "" msgid "Show group chat updates" msgstr "Show group chat updates" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:579 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:581 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:583 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:585 msgid "Show less like this" msgstr "" @@ -10622,8 +10695,8 @@ msgstr "" msgid "Show More" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:571 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:573 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:575 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:577 msgid "Show more like this" msgstr "" @@ -10649,8 +10722,8 @@ msgstr "" msgid "Show replies as" msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:627 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:637 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:631 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:641 msgid "Show reply for everyone" msgstr "" @@ -10672,7 +10745,7 @@ msgstr "" msgid "Show warning and filter from feeds" msgstr "" -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:605 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:607 msgid "Shows information about when this post was created" msgstr "" @@ -10689,10 +10762,11 @@ msgstr "" #: src/components/dialogs/Signin.tsx:100 #: src/components/WelcomeModal.tsx:197 #: src/components/WelcomeModal.tsx:209 +#: src/screens/GroupInviteLanding.tsx:81 #: src/screens/Hashtag.tsx:228 #: src/screens/Login/index.tsx:127 -#: src/screens/Login/index.tsx:142 -#: src/screens/Login/LoginForm.tsx:215 +#: src/screens/Login/index.tsx:143 +#: src/screens/Login/LoginForm.tsx:244 #: src/screens/Messages/JoinRequest.tsx:290 #: src/screens/Messages/JoinRequest.tsx:296 #: src/screens/Search/SearchResults.tsx:303 @@ -10718,7 +10792,7 @@ msgstr "" msgid "Sign in as {fullDraftHandle}" msgstr "Sign in as {fullDraftHandle}" -#: src/screens/Login/LoginForm.tsx:263 +#: src/screens/Login/LoginForm.tsx:313 msgid "Sign in as {handle}" msgstr "Sign in as {handle}" @@ -10760,12 +10834,16 @@ msgstr "Sign in to accept invite." msgid "Sign in to account that is not listed" msgstr "" +#: src/screens/GroupInviteLanding.tsx:89 +msgid "Sign in to join" +msgstr "Sign in to join" + #: src/screens/Messages/JoinRequest.tsx:215 msgid "Sign in to request access to this group chat." msgstr "Sign in to request access to this group chat." -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:557 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:559 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:561 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:563 msgid "Sign in to view post" msgstr "" @@ -10775,9 +10853,9 @@ msgstr "" #: src/screens/SignupQueued.tsx:94 #: src/screens/SignupQueued.tsx:97 #: src/screens/Takendown.tsx:90 -#: src/view/shell/desktop/LeftNav.tsx:231 -#: src/view/shell/desktop/LeftNav.tsx:286 +#: src/view/shell/desktop/LeftNav.tsx:234 #: src/view/shell/desktop/LeftNav.tsx:289 +#: src/view/shell/desktop/LeftNav.tsx:292 msgid "Sign out" msgstr "" @@ -10786,7 +10864,7 @@ msgid "Sign Out" msgstr "" #: src/screens/Settings/Settings.tsx:298 -#: src/view/shell/desktop/LeftNav.tsx:228 +#: src/view/shell/desktop/LeftNav.tsx:231 msgid "Sign out?" msgstr "" @@ -10805,7 +10883,7 @@ msgstr "" msgid "Signed in as @{0}" msgstr "" -#: src/Navigation.tsx:171 +#: src/Navigation.tsx:175 msgid "Signing in..." msgstr "Signing in..." @@ -10826,7 +10904,7 @@ msgstr "" msgid "Skip contact sharing and continue to the app" msgstr "" -#: src/view/com/composer/Composer.tsx:1504 +#: src/view/com/composer/Composer.tsx:1598 msgid "Skip empty posts?" msgstr "Skip empty posts?" @@ -11035,8 +11113,8 @@ msgstr "Start chat" msgid "Start chat with {displayName}" msgstr "" -#: src/Navigation.tsx:559 -#: src/Navigation.tsx:564 +#: src/Navigation.tsx:563 +#: src/Navigation.tsx:568 #: src/screens/StarterPack/Wizard/index.tsx:197 msgid "Starter Pack" msgstr "" @@ -11075,7 +11153,7 @@ msgstr "" msgid "Starter Packs let you share your favorite feeds and people with your friends." msgstr "" -#: src/screens/Login/LoginForm.tsx:317 +#: src/screens/Login/LoginForm.tsx:367 msgid "Starts the sign-in process" msgstr "Starts the sign-in process" @@ -11097,7 +11175,7 @@ msgstr "" msgid "Stored as part of a secure code for matching with others" msgstr "" -#: src/Navigation.tsx:315 +#: src/Navigation.tsx:319 #: src/screens/Settings/Settings.tsx:454 msgid "Storybook" msgstr "" @@ -11127,7 +11205,7 @@ msgstr "" msgid "Submit report" msgstr "" -#: src/lib/api/index.ts:317 +#: src/lib/api/index.ts:421 msgid "Submitting to community..." msgstr "Submitting to community..." @@ -11195,11 +11273,11 @@ msgstr "" msgid "Suggestive" msgstr "" -#: src/Navigation.tsx:345 -#: src/Navigation.tsx:350 +#: src/Navigation.tsx:349 +#: src/Navigation.tsx:354 #: src/view/screens/Support.tsx:31 #: src/view/screens/SupportReturn.tsx:64 -#: src/view/shell/desktop/LeftNav.tsx:771 +#: src/view/shell/desktop/LeftNav.tsx:789 msgid "Support" msgstr "" @@ -11258,16 +11336,16 @@ msgstr "Suspended accounts cannot participate in chat." #: src/screens/Settings/Settings.tsx:116 #: src/screens/Settings/Settings.tsx:128 #: src/screens/Settings/Settings.tsx:577 -#: src/view/shell/desktop/LeftNav.tsx:266 +#: src/view/shell/desktop/LeftNav.tsx:269 msgid "Switch account" msgstr "" -#: src/view/shell/desktop/LeftNav.tsx:128 +#: src/view/shell/desktop/LeftNav.tsx:131 msgid "Switch accounts" msgstr "" #. placeholder {0}: sanitizeHandle( profile?.handle ?? account.handle, '@', ) -#: src/view/shell/desktop/LeftNav.tsx:368 +#: src/view/shell/desktop/LeftNav.tsx:371 msgid "Switch to {0}" msgstr "" @@ -11402,7 +11480,7 @@ msgid "Terms" msgstr "" #: src/components/dialogs/BirthDateSettings.tsx:181 -#: src/Navigation.tsx:360 +#: src/Navigation.tsx:364 #: src/screens/Settings/AboutSettings.tsx:85 #: src/screens/Settings/AboutSettings.tsx:88 #: src/view/screens/TermsOfService.tsx:25 @@ -11450,11 +11528,11 @@ msgstr "That handle is already taken." msgid "That starter pack could not be found." msgstr "" -#: src/view/com/post-thread/PostQuotes.tsx:135 +#: src/view/com/post-thread/PostQuotes.tsx:136 msgid "That's all, folks!" msgstr "" -#: src/screens/VideoFeed/index.tsx:1141 +#: src/screens/VideoFeed/index.tsx:1143 msgid "That's everything!" msgstr "" @@ -11644,9 +11722,9 @@ msgid "There was an issue updating your feeds, please check your internet connec msgstr "" #. placeholder {0}: e.toString() -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:429 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:452 -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:472 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:433 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:456 +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:476 #: src/screens/Messages/ConversationSettings/Member.tsx:71 #: src/screens/Messages/ConversationSettings/MemberMenu.tsx:114 #: src/screens/Messages/ConversationSettings/MemberMenu.tsx:127 @@ -11880,7 +11958,7 @@ msgid "This feed is empty! You may need to follow more users or tune your langua msgstr "" #: src/components/StarterPack/Main/PostsList.tsx:41 -#: src/screens/Profile/ProfileFeed/index.tsx:171 +#: src/screens/Profile/ProfileFeed/index.tsx:178 #: src/screens/ProfileList/FeedSection.tsx:78 msgid "This feed is empty." msgstr "" @@ -11913,6 +11991,19 @@ msgstr "This invite link has been disabled." msgid "This invite link is invalid" msgstr "This invite link is invalid" +#: src/lib/api/space-post.ts:53 +msgid "This is a private post from another space. You can only quote it in a post to that space." +msgstr "This is a private post from another space. You can only quote it in a post to that space." + +#: src/lib/api/index.ts:146 +#: src/lib/api/index.ts:520 +msgid "This is a private post. You can only quote it in a post to that space." +msgstr "This is a private post. You can only quote it in a post to that space." + +#: src/lib/api/index.ts:612 +msgid "This is a private post. You can only reply to it in that space." +msgstr "This is a private post. You can only reply to it in that space." + #: src/view/screens/Debug.tsx:327 msgid "This is an empty state" msgstr "" @@ -11987,7 +12078,7 @@ msgstr "This person is blocking you" #. placeholder {0}: niceDate(i18n, createdAt) #. placeholder {1}: niceDate(i18n, indexedAt) -#: src/screens/PostThread/components/ThreadItemAnchor.tsx:645 +#: src/screens/PostThread/components/ThreadItemAnchor.tsx:647 msgid "This post claims to have been created on <0>{0}, but was first seen by Blacksky on <1>{1}." msgstr "This post claims to have been created on <0>{0}, but was first seen by Blacksky on <1>{1}." @@ -11995,11 +12086,15 @@ msgstr "This post claims to have been created on <0>{0}, but was first seen msgid "This post has an unknown type of threadgate on it. Your app may be out of date." msgstr "" -#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:157 +#: src/components/PostControls/ShareMenu/ShareMenuItems.tsx:153 msgid "This post is only visible to logged-in users." msgstr "" -#: src/components/CommunityOnlyBadge.tsx:60 +#: src/components/CommunityOnlyBadge.tsx:73 +msgid "This post is only visible to members of its community." +msgstr "This post is only visible to members of its community." + +#: src/components/CommunityOnlyBadge.tsx:77 msgid "This post is only visible to members of the Blacksky community." msgstr "This post is only visible to members of the Blacksky community." @@ -12011,7 +12106,7 @@ msgstr "" msgid "This post will be hidden from feeds and threads. This cannot be undone." msgstr "" -#: src/view/com/composer/Composer.tsx:1066 +#: src/view/com/composer/Composer.tsx:1134 msgid "This post's author has disabled quote posts." msgstr "" @@ -12019,7 +12114,11 @@ msgstr "" msgid "This profile is only visible to logged-in users. It won't be visible to people who aren't signed in." msgstr "" -#: src/components/PostControls/PostMenu/PostMenuItems.tsx:823 +#: src/lib/api/index.ts:108 +msgid "This reply targets a different private space than its parent." +msgstr "This reply targets a different private space than its parent." + +#: src/components/PostControls/PostMenu/PostMenuItems.tsx:827 msgid "This reply will be sorted into a hidden section at the bottom of your thread and will mute notifications for subsequent replies - both for yourself and others." msgstr "" @@ -12105,7 +12204,7 @@ msgstr "This will irreversibly delete your Blacksky account <0>{currentHandle}@{0}" msgstr "" -#: src/Navigation.tsx:484 +#: src/Navigation.tsx:488 #: src/screens/Search/modules/ExploreInterestsCard.tsx:68 #: src/screens/Settings/ContentAndMediaSettings.tsx:94 #: src/screens/Settings/ContentAndMediaSettings.tsx:97 @@ -14120,11 +14237,11 @@ msgstr "" msgid "Your payment is still being processed. Please check back later." msgstr "Your payment is still being processed. Please check back later." -#: src/view/com/composer/Composer.tsx:1164 +#: src/view/com/composer/Composer.tsx:1235 msgid "Your post was sent" msgstr "" -#: src/view/com/composer/Composer.tsx:1161 +#: src/view/com/composer/Composer.tsx:1232 msgid "Your posts were sent" msgstr "" @@ -14142,7 +14259,7 @@ msgstr "" msgid "Your profile, posts, feeds, and lists will no longer be visible to other {0} users. You can reactivate your account at any time by logging in." msgstr "Your profile, posts, feeds, and lists will no longer be visible to other {0} users. You can reactivate your account at any time by logging in." -#: src/view/com/composer/Composer.tsx:1163 +#: src/view/com/composer/Composer.tsx:1234 msgid "Your reply was sent" msgstr "" @@ -14163,7 +14280,7 @@ msgstr "Your session has expired. Please sign in again." msgid "Your support helps us maintain and improve the Blacksky community." msgstr "Your support helps us maintain and improve the Blacksky community." -#: src/view/com/composer/Composer.tsx:1505 +#: src/view/com/composer/Composer.tsx:1599 msgid "Your thread has empty posts that will be skipped. The remaining posts will be published as a thread." msgstr "Your thread has empty posts that will be skipped. The remaining posts will be published as a thread." -- knotmirror 0.0.1 From c472c95046f1ab8b9507496e43dba979559d78c3 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Fri, 4 Sep 2026 11:38:07 -0400 Subject: [PATCH 4/4] fix(notifications): consume private space queries (#183) --- package.json | 2 +- .../__tests__/community-notifications.test.ts | 204 +++++++++++++++ src/lib/api/__tests__/community.test.ts | 27 ++ src/lib/api/community-notifications.ts | 237 +++++++++++++++++ src/lib/api/community.ts | 21 +- .../__tests__/fetch-page.test.ts | 90 +++++++ .../__tests__/pagination.test.ts | 92 +++++++ .../notifications/__tests__/unread.test.tsx | 245 ++++++++++++++++++ src/state/queries/notifications/feed.ts | 32 ++- src/state/queries/notifications/pagination.ts | 36 +++ src/state/queries/notifications/unread.tsx | 105 ++++---- src/state/queries/notifications/util.ts | 21 +- 12 files changed, 1046 insertions(+), 66 deletions(-) create mode 100644 src/lib/api/__tests__/community-notifications.test.ts create mode 100644 src/lib/api/community-notifications.ts create mode 100644 src/state/queries/notifications/__tests__/fetch-page.test.ts create mode 100644 src/state/queries/notifications/__tests__/pagination.test.ts create mode 100644 src/state/queries/notifications/__tests__/unread.test.tsx create mode 100644 src/state/queries/notifications/pagination.ts diff --git a/package.json b/package.json index fb1e99fff..d0e7dba53 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.127.1", + "version": "1.127.2", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/lib/api/__tests__/community-notifications.test.ts b/src/lib/api/__tests__/community-notifications.test.ts new file mode 100644 index 000000000..203d5794a --- /dev/null +++ b/src/lib/api/__tests__/community-notifications.test.ts @@ -0,0 +1,204 @@ +import { + type AppBskyNotificationGetUnreadCount, + type AppBskyNotificationListNotifications, + type AtpAgent, + lexicons, +} from '@atproto/api' + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) +jest.mock('multiformats/cid', () => ({ + CID: { + asCID: () => null, + parse: (value: string) => { + if (!value.startsWith('bafy')) throw new Error('invalid cid') + return {toString: () => value} + }, + }, +})) + +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import { + type CommunityNotificationXrpcError, + GET_UNREAD_COUNT_METHOD, + getUnreadCount, + LIST_NOTIFICATIONS_METHOD, + listNotifications, +} from '../community-notifications' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const PRIVATE_URI = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kprivate` +const PUBLIC_URI = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' +const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' + +function notification(uri: string) { + return { + uri, + cid: CID, + author: {did: 'did:plc:alice', handle: 'alice.test'}, + reason: 'mention', + reasonSubject: uri, + record: { + $type: 'app.bsky.feed.post', + text: 'hello', + createdAt: '2026-09-01T00:00:00.000Z', + }, + isRead: false, + indexedAt: '2026-09-01T00:00:00.000Z', + } +} + +function listBody(uri = PRIVATE_URI) { + return { + cursor: 'next', + notifications: [notification(uri)], + priority: false, + seenAt: '2026-09-01T00:00:00.000Z', + } +} + +function mockAgent() { + const fetchHandler = jest.fn, [string, RequestInit]>() + const standardList = jest.fn< + Promise<{data: AppBskyNotificationListNotifications.OutputSchema}>, + [AppBskyNotificationListNotifications.QueryParams, unknown] + >() + const standardCount = jest.fn< + Promise<{data: AppBskyNotificationGetUnreadCount.OutputSchema}>, + [AppBskyNotificationGetUnreadCount.QueryParams, unknown] + >() + const agent = { + fetchHandler, + app: { + bsky: { + notification: { + listNotifications: standardList, + getUnreadCount: standardCount, + }, + }, + }, + } as unknown as AtpAgent + return {agent, fetchHandler, standardList, standardCount} +} + +describe('community notification API', () => { + it('accepts private notification output rejected by the standard catalog', async () => { + const {agent, fetchHandler} = mockAgent() + const body = listBody() + fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) + + expect(() => + lexicons.assertValidXrpcOutput( + 'app.bsky.notification.listNotifications', + body, + ), + ).toThrow() + await expect( + listNotifications(agent, {limit: 30, reasons: ['mention']}), + ).resolves.toEqual(body) + expect(fetchHandler).toHaveBeenCalledWith( + expect.stringContaining(`/xrpc/${LIST_NOTIFICATIONS_METHOD}?`), + expect.objectContaining({method: 'GET'}), + ) + }) + + it('keeps public notification output compatible', async () => { + const {agent, fetchHandler} = mockAgent() + const body = listBody(PUBLIC_URI) + fetchHandler.mockResolvedValue(new Response(JSON.stringify(body))) + + expect(() => + lexicons.assertValidXrpcOutput( + 'app.bsky.notification.listNotifications', + body, + ), + ).not.toThrow() + await expect(listNotifications(agent, {})).resolves.toEqual(body) + }) + + it('rejects malformed successful output before returning it', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({notifications: [{uri: PRIVATE_URI}]})), + ) + + await expect(listNotifications(agent, {})).rejects.toThrow() + }) + + it('falls back only for a 501 MethodNotImplemented response', async () => { + const {agent, fetchHandler, standardList, standardCount} = mockAgent() + fetchHandler + .mockResolvedValueOnce( + new Response(JSON.stringify({error: 'MethodNotImplemented'}), { + status: 501, + }), + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({error: 'MethodNotImplemented'}), { + status: 501, + }), + ) + standardList.mockResolvedValue({ + data: listBody(PUBLIC_URI), + }) + standardCount.mockResolvedValue({data: {count: 4}}) + + await expect(listNotifications(agent, {limit: 20})).resolves.toEqual( + listBody(PUBLIC_URI), + ) + await expect(getUnreadCount(agent, {priority: true})).resolves.toEqual({ + count: 4, + }) + expect(standardList).toHaveBeenCalledWith( + {limit: 20}, + HOME_APPVIEW_PINNED_OPTS, + ) + expect(standardCount).toHaveBeenCalledWith( + {priority: true}, + HOME_APPVIEW_PINNED_OPTS, + ) + }) + + it.each([ + [404, 'MethodNotImplemented'], + [501, 'UnknownMethod'], + [501, undefined], + [403, 'Forbidden'], + [503, 'UpstreamFailure'], + ])('does not fall back for status %s and error %s', async (status, error) => { + const {agent, fetchHandler, standardList} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify(error ? {error} : {}), {status}), + ) + + await expect(listNotifications(agent, {})).rejects.toEqual( + expect.objectContaining>({ + status, + error, + }), + ) + expect(standardList).not.toHaveBeenCalled() + }) + + it('surfaces transport failures without fallback', async () => { + const {agent, fetchHandler, standardList} = mockAgent() + const error = new Error('offline') + fetchHandler.mockRejectedValue(error) + + await expect(listNotifications(agent, {})).rejects.toBe(error) + expect(standardList).not.toHaveBeenCalled() + }) + + it('validates and returns the custom unread count', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response(JSON.stringify({count: 8}))) + + await expect(getUnreadCount(agent)).resolves.toEqual({count: 8}) + expect(fetchHandler).toHaveBeenCalledWith( + `/xrpc/${GET_UNREAD_COUNT_METHOD}`, + expect.objectContaining({method: 'GET'}), + ) + }) +}) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index 3ab2c7e8c..ced31d3f2 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -63,6 +63,33 @@ describe('communityXrpc', () => { ) }) + it('serializes repeated primitive parameters and omits empty values', async () => { + const {agent, fetchHandler} = mockAgent() + + await communityXrpc( + agent, + 'community.blacksky.notification.listNotifications', + { + params: { + reasons: ['mention', 'reply'], + empty: [], + limit: 30, + priority: false, + cursor: 'before value', + seenAt: undefined, + }, + }, + ) + + const url = new URL(fetchHandler.mock.calls[0][0], 'https://example.test') + expect(url.searchParams.getAll('reasons')).toEqual(['mention', 'reply']) + expect(url.searchParams.get('limit')).toBe('30') + expect(url.searchParams.get('priority')).toBe('false') + expect(url.searchParams.get('cursor')).toBe('before value') + expect(url.searchParams.has('empty')).toBe(false) + expect(url.searchParams.has('seenAt')).toBe(false) + }) + it('fetches space likes through the permission-aware endpoint', async () => { const {agent, fetchHandler} = mockAgent() fetchHandler.mockResolvedValue( diff --git a/src/lib/api/community-notifications.ts b/src/lib/api/community-notifications.ts new file mode 100644 index 000000000..3f59f88cc --- /dev/null +++ b/src/lib/api/community-notifications.ts @@ -0,0 +1,237 @@ +import { + type AppBskyNotificationGetUnreadCount, + type AppBskyNotificationListNotifications, + type AtpAgent, + jsonToLex, + lexicons, +} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' + +export const LIST_NOTIFICATIONS_METHOD = + 'community.blacksky.notification.listNotifications' +export const GET_UNREAD_COUNT_METHOD = + 'community.blacksky.notification.getUnreadCount' + +const listNotificationsSchema = { + lexicon: 1, + id: LIST_NOTIFICATIONS_METHOD, + defs: { + main: { + type: 'query', + description: + 'Enumerate public and authorized permissioned-space notifications for the requesting account. An empty page may include a cursor and should be continued.', + parameters: { + type: 'params', + properties: { + reasons: { + description: 'Notification reasons to include in response.', + type: 'array', + items: { + type: 'string', + description: + 'A reason that matches the reason property of #notification.', + }, + }, + limit: {type: 'integer', minimum: 1, maximum: 100, default: 50}, + priority: {type: 'boolean'}, + cursor: {type: 'string'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + output: { + encoding: 'application/json', + schema: { + type: 'object', + required: ['notifications'], + properties: { + cursor: {type: 'string'}, + notifications: { + type: 'array', + items: {type: 'ref', ref: '#notification'}, + }, + priority: {type: 'boolean'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + }, + }, + notification: { + type: 'object', + required: [ + 'uri', + 'cid', + 'author', + 'reason', + 'record', + 'isRead', + 'indexedAt', + ], + properties: { + uri: { + type: 'string', + description: + 'The public AT URI or permissioned-space record URI that caused the notification.', + }, + cid: {type: 'string', format: 'cid'}, + author: {type: 'ref', ref: 'app.bsky.actor.defs#profileView'}, + reason: { + type: 'string', + description: 'The reason why this notification was delivered.', + knownValues: [ + 'like', + 'repost', + 'follow', + 'mention', + 'reply', + 'quote', + 'starterpack-joined', + 'verified', + 'unverified', + 'like-via-repost', + 'repost-via-repost', + 'subscribed-post', + 'contact-match', + ], + }, + reasonSubject: { + type: 'string', + description: + 'The public AT URI or permissioned-space record URI that is the notification subject.', + }, + record: {type: 'unknown'}, + starterPack: { + description: 'The starter pack associated with this notification.', + type: 'ref', + ref: 'app.bsky.graph.defs#starterPackViewBasic', + }, + isRead: {type: 'boolean'}, + indexedAt: {type: 'string', format: 'datetime'}, + labels: { + type: 'array', + items: {type: 'ref', ref: 'com.atproto.label.defs#label'}, + }, + }, + }, + }, +} as const + +const getUnreadCountSchema = { + lexicon: 1, + id: GET_UNREAD_COUNT_METHOD, + defs: { + main: { + type: 'query', + description: + 'Count unread public and authorized permissioned-space notifications for the requesting account.', + parameters: { + type: 'params', + properties: { + priority: {type: 'boolean'}, + seenAt: {type: 'string', format: 'datetime'}, + }, + }, + output: { + encoding: 'application/json', + schema: { + type: 'object', + required: ['count'], + properties: {count: {type: 'integer'}}, + }, + }, + }, + }, +} as const + +type LexiconDoc = Parameters[0] + +function registerLexicon(doc: LexiconDoc) { + if (!lexicons.get(doc.id)) { + lexicons.add(doc) + } +} + +registerLexicon(listNotificationsSchema as unknown as LexiconDoc) +registerLexicon(getUnreadCountSchema as unknown as LexiconDoc) + +export class CommunityNotificationXrpcError extends Error { + constructor( + method: string, + public readonly status: number, + public readonly error?: string, + ) { + super(`${method} failed (${status}${error ? ` ${error}` : ''})`) + } +} + +export async function listNotifications( + agent: AtpAgent, + params: AppBskyNotificationListNotifications.QueryParams, +): Promise { + const response = await communityXrpc(agent, LIST_NOTIFICATIONS_METHOD, { + params, + }) + if (!response.ok) { + if (await isUnsupportedMethod(response)) { + const result = await agent.app.bsky.notification.listNotifications( + params, + HOME_APPVIEW_PINNED_OPTS, + ) + return result.data + } + throw await toXrpcError(LIST_NOTIFICATIONS_METHOD, response) + } + const data = jsonToLex(await response.json()) + lexicons.assertValidXrpcOutput(LIST_NOTIFICATIONS_METHOD, data) + return data as AppBskyNotificationListNotifications.OutputSchema +} + +export async function getUnreadCount( + agent: AtpAgent, + params: AppBskyNotificationGetUnreadCount.QueryParams = {}, +): Promise { + const response = await communityXrpc(agent, GET_UNREAD_COUNT_METHOD, { + params, + }) + if (!response.ok) { + if (await isUnsupportedMethod(response)) { + const result = await agent.app.bsky.notification.getUnreadCount( + params, + HOME_APPVIEW_PINNED_OPTS, + ) + return result.data + } + throw await toXrpcError(GET_UNREAD_COUNT_METHOD, response) + } + const data = jsonToLex(await response.json()) + lexicons.assertValidXrpcOutput(GET_UNREAD_COUNT_METHOD, data) + return data as AppBskyNotificationGetUnreadCount.OutputSchema +} + +async function parseXrpcError(response: Response): Promise<{ + error?: string +}> { + try { + const body: unknown = await response.clone().json() + return typeof body === 'object' && + body !== null && + 'error' in body && + typeof body.error === 'string' + ? {error: body.error} + : {} + } catch { + return {} + } +} + +async function isUnsupportedMethod(response: Response): Promise { + if (response.status !== 501) return false + const body = await parseXrpcError(response) + return body.error === 'MethodNotImplemented' +} + +async function toXrpcError(method: string, response: Response) { + const body = await parseXrpcError(response) + return new CommunityNotificationXrpcError(method, response.status, body.error) +} diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts index 817580059..9b03a78fa 100644 --- a/src/lib/api/community.ts +++ b/src/lib/api/community.ts @@ -8,18 +8,31 @@ import { import {HOME_PROXY_HEADER} from '#/lib/constants' import {toPostView} from './space-views' +export type CommunityXrpcParam = string | number | boolean + export async function communityXrpc( agent: BskyAgent, method: string, opts?: { - params?: Record + params?: Record< + string, + CommunityXrpcParam | readonly CommunityXrpcParam[] | undefined + > body?: unknown serviceDid?: string }, ): Promise { - const qs = opts?.params - ? '?' + new URLSearchParams(opts.params).toString() - : '' + const searchParams = new URLSearchParams() + for (const [key, value] of Object.entries(opts?.params ?? {})) { + const values = Array.isArray(value) ? value : [value] + for (const item of values) { + if (item !== undefined) { + searchParams.append(key, String(item)) + } + } + } + const encodedParams = searchParams.toString() + const qs = encodedParams ? `?${encodedParams}` : '' const path = `/xrpc/${method}${qs}` const headers: Record = { diff --git a/src/state/queries/notifications/__tests__/fetch-page.test.ts b/src/state/queries/notifications/__tests__/fetch-page.test.ts new file mode 100644 index 000000000..5eaa176ff --- /dev/null +++ b/src/state/queries/notifications/__tests__/fetch-page.test.ts @@ -0,0 +1,90 @@ +import {type AtpAgent} from '@atproto/api' +import {QueryClient} from '@tanstack/react-query' + +const mockListNotifications = jest.fn() + +jest.mock('#/lib/api/community-notifications', () => ({ + listNotifications: (...args: unknown[]) => mockListNotifications(...args), +})) +jest.mock('#/state/queries/profile', () => ({precacheProfile: jest.fn()})) + +import {fetchPage} from '../util' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const PRIVATE_URI = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kprivate` + +describe(fetchPage, () => { + const agent = {} as AtpAgent + const queryClient = new QueryClient() + + beforeEach(() => { + jest.clearAllMocks() + }) + + it('converts a private notification from the custom ordered stream', async () => { + mockListNotifications.mockResolvedValue({ + cursor: 'next', + priority: false, + seenAt: '2026-09-01T00:00:00.000Z', + notifications: [ + { + uri: PRIVATE_URI, + cid: 'bafyreiacsg6vsw7ppwbnowzsdgstulhrwftirtcnvkcbnfgvhwjrnzfmsu', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + reason: 'mention', + reasonSubject: PRIVATE_URI, + record: {$type: 'app.bsky.feed.post', text: 'private'}, + isRead: false, + indexedAt: '2026-09-01T00:00:00.000Z', + }, + ], + }) + + const result = await fetchPage({ + agent, + cursor: undefined, + limit: 30, + queryClient, + moderationOpts: undefined, + hideFollowNotifications: undefined, + fetchAdditionalData: false, + reasons: [], + }) + + expect(mockListNotifications).toHaveBeenCalledWith(agent, { + limit: 30, + cursor: undefined, + reasons: [], + }) + expect(result.page.cursor).toBe('next') + expect(result.page.items).toHaveLength(1) + expect(result.page.items[0].subjectUri).toBe(PRIVATE_URI) + }) + + it('preserves a cursor on an empty mentions page', async () => { + mockListNotifications.mockResolvedValue({ + cursor: 'continue', + notifications: [], + }) + + const result = await fetchPage({ + agent, + cursor: 'before', + limit: 30, + queryClient, + moderationOpts: undefined, + hideFollowNotifications: undefined, + fetchAdditionalData: false, + reasons: ['mention', 'reply', 'quote'], + }) + + expect(result.page).toMatchObject({cursor: 'continue', items: []}) + expect(mockListNotifications).toHaveBeenCalledWith( + agent, + expect.objectContaining({ + cursor: 'before', + reasons: ['mention', 'reply', 'quote'], + }), + ) + }) +}) diff --git a/src/state/queries/notifications/__tests__/pagination.test.ts b/src/state/queries/notifications/__tests__/pagination.test.ts new file mode 100644 index 000000000..7fe5334c4 --- /dev/null +++ b/src/state/queries/notifications/__tests__/pagination.test.ts @@ -0,0 +1,92 @@ +import {nextAutoPaginationAttemptCount, shouldAutoPaginate} from '../pagination' + +describe(shouldAutoPaginate, () => { + it('continues through an empty page that has a cursor', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 0, + }), + ).toBe(true) + }) + + it('continues when filtering leaves a short page', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 4, + wantedItemCount: 30, + attemptCount: 3, + }), + ).toBe(true) + }) + + it('stops on a terminal empty page', () => { + expect( + shouldAutoPaginate({ + hasNextPage: false, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 0, + }), + ).toBe(false) + }) + + it('stops at the 50-attempt safety bound', () => { + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 49, + }), + ).toBe(true) + expect( + shouldAutoPaginate({ + hasNextPage: true, + itemCount: 0, + wantedItemCount: 30, + attemptCount: 50, + }), + ).toBe(false) + }) +}) + +describe(nextAutoPaginationAttemptCount, () => { + it.each([ + {isLoading: true, isRefetching: false, hasNextPage: true}, + {isLoading: false, isRefetching: true, hasNextPage: true}, + {isLoading: false, isRefetching: false, hasNextPage: false}, + ])('resets attempts for $isLoading/$isRefetching/$hasNextPage', state => { + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + requestNextPage: false, + ...state, + }), + ).toBe(0) + }) + + it('increments only when the active cycle requests another page', () => { + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + hasNextPage: true, + isLoading: false, + isRefetching: false, + requestNextPage: true, + }), + ).toBe(18) + expect( + nextAutoPaginationAttemptCount({ + attemptCount: 17, + hasNextPage: true, + isLoading: false, + isRefetching: false, + requestNextPage: false, + }), + ).toBe(17) + }) +}) diff --git a/src/state/queries/notifications/__tests__/unread.test.tsx b/src/state/queries/notifications/__tests__/unread.test.tsx new file mode 100644 index 000000000..79a9770c3 --- /dev/null +++ b/src/state/queries/notifications/__tests__/unread.test.tsx @@ -0,0 +1,245 @@ +import {type PropsWithChildren} from 'react' +import {AppState} from 'react-native' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {act, renderHook} from '@testing-library/react-native' + +const mockGetUnreadCount = jest.fn() +const mockFetchPage = jest.fn() +const mockResetBadgeCount = jest.fn() +const mockTruncateAndInvalidate = jest.fn() +const mockUpdateSeen = jest.fn().mockResolvedValue(undefined) +const mockBroadcastPostMessage = jest.fn() +let mockBroadcastListener: ((event: MessageEvent) => void) | undefined +const mockAgent = { + session: {did: 'did:plc:viewer'}, + app: { + bsky: { + notification: {updateSeen: mockUpdateSeen}, + }, + }, +} + +jest.mock('#/lib/api/community-notifications', () => ({ + getUnreadCount: (...args: unknown[]) => mockGetUnreadCount(...args), +})) +jest.mock('#/lib/broadcast', () => + jest.fn().mockImplementation(() => ({ + postMessage: (...args: unknown[]) => mockBroadcastPostMessage(...args), + addEventListener: ( + _type: string, + listener: (event: MessageEvent) => void, + ) => { + mockBroadcastListener = listener + }, + removeEventListener: ( + _type: string, + listener: (event: MessageEvent) => void, + ) => { + if (mockBroadcastListener === listener) mockBroadcastListener = undefined + }, + })), +) +jest.mock('#/lib/notifications/notifications', () => ({ + resetBadgeCount: () => mockResetBadgeCount(), +})) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => undefined, +})) +jest.mock('#/state/queries/util', () => ({ + truncateAndInvalidate: (...args: unknown[]) => + mockTruncateAndInvalidate(...args), +})) +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, + useSession: () => ({hasSession: false}), +})) +jest.mock('../util', () => ({ + fetchPage: (...args: unknown[]) => mockFetchPage(...args), +})) + +import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import {type FeedPage} from '../types' +import { + Provider, + useUnreadNotifications, + useUnreadNotificationsApi, +} from '../unread' + +function deferred() { + let resolve!: (value: T) => void + let reject!: (reason: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return {promise, resolve, reject} +} + +const page: FeedPage = { + cursor: 'next', + seenAt: new Date('2026-09-01T00:00:00.000Z'), + items: [], + priority: false, +} + +describe('notification unread synchronization', () => { + let queryClient: QueryClient + + beforeEach(() => { + jest.clearAllMocks() + mockBroadcastListener = undefined + Object.defineProperty(AppState, 'currentState', { + configurable: true, + value: 'active', + }) + queryClient = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + }) + + function wrapper({children}: PropsWithChildren) { + return ( + + {children} + + ) + } + + function setup() { + return renderHook( + () => ({ + count: useUnreadNotifications(), + api: useUnreadNotificationsApi(), + }), + {wrapper}, + ) + } + + it('uses count-only polling without fetching or hydrating a page', async () => { + mockGetUnreadCount.mockResolvedValue({count: 6}) + const {result} = setup() + + await act(() => result.current.api.checkUnread()) + + expect(result.current.count).toBe('6') + expect(mockFetchPage).not.toHaveBeenCalled() + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + }) + + it('commits an invalidating page and authoritative count only after both resolve', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(async () => Promise.resolve()) + expect(result.current.count).toBe('') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + + countRequest.resolve({count: 7}) + await act(() => refresh) + + expect(result.current.count).toBe('7') + expect(result.current.api.getCachedUnreadPage()).toBe(page) + expect(mockFetchPage).toHaveBeenCalledWith( + expect.objectContaining({fetchAdditionalData: true, reasons: []}), + ) + expect(mockTruncateAndInvalidate).toHaveBeenCalledTimes(2) + }) + + it.each(['count', 'page'] as const)( + 'preserves the prior badge and cache when the %s request fails', + async failure => { + mockGetUnreadCount.mockResolvedValueOnce({count: 3}) + mockFetchPage.mockResolvedValueOnce({ + page, + indexedAt: '2026-09-01T00:00:00.000Z', + }) + const {result} = setup() + await act(() => result.current.api.checkUnread({invalidate: true})) + expect(result.current.count).toBe('3') + + const error = new Error(`${failure} failed`) + mockGetUnreadCount.mockImplementationOnce(() => + failure === 'count' + ? Promise.reject(error) + : Promise.resolve({count: 9}), + ) + mockFetchPage.mockImplementationOnce(() => + failure === 'page' + ? Promise.reject(error) + : Promise.resolve({page: {...page, cursor: 'new'}, indexedAt: ''}), + ) + + await expect( + act(() => result.current.api.checkUnread({invalidate: true})), + ).rejects.toBe(error) + expect(result.current.count).toBe('3') + expect(result.current.api.getCachedUnreadPage()).toBe(page) + }, + ) + + it('prevents an older refresh from resurrecting the badge after mark-all-read', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + await act(() => result.current.api.markAllRead()) + countRequest.resolve({count: 12}) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(() => refresh) + + expect(result.current.count).toBe('') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + expect(mockUpdateSeen).toHaveBeenCalledWith( + {seenAt: expect.any(String)}, + HOME_APPVIEW_PINNED_OPTS, + ) + expect(mockResetBadgeCount).toHaveBeenCalledTimes(1) + }) + + it('prevents an older refresh from overwriting a broadcast badge', async () => { + const countRequest = deferred<{count: number}>() + const pageRequest = deferred<{page: FeedPage; indexedAt: string}>() + mockGetUnreadCount.mockReturnValue(countRequest.promise) + mockFetchPage.mockReturnValue(pageRequest.promise) + const {result} = setup() + + let refresh!: Promise + act(() => { + refresh = result.current.api.checkUnread({invalidate: true}) + }) + act(() => { + mockBroadcastListener?.({data: {event: '4'}} as MessageEvent) + }) + expect(result.current.count).toBe('4') + + countRequest.resolve({count: 12}) + pageRequest.resolve({ + page, + indexedAt: '2099-09-01T00:00:00.000Z', + }) + await act(() => refresh) + + expect(result.current.count).toBe('4') + expect(result.current.api.getCachedUnreadPage()).toBeUndefined() + }) +}) diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index 97091e31e..745e61081 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -37,6 +37,7 @@ import { getEmbeddedPost, makeUriMatcher, } from '../util' +import {nextAutoPaginationAttemptCount, shouldAutoPaginate} from './pagination' import {type FeedPage} from './types' import {useUnreadNotificationsApi} from './unread' import {fetchPage} from './util' @@ -247,6 +248,13 @@ export function useNotificationFeedQuery(opts: { if (isLoading || isRefetching) { // During the initial fetch, we want to get an entire page's worth of items. wantedItemCount.current = PAGE_SIZE + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage: !!hasNextPage, + isLoading, + isRefetching, + requestNextPage: false, + }) } else if (isFetchingNextPage) { if (itemCount > wantedItemCount.current) { // We have more items than wantedItemCount, so wantedItemCount must be out of date. @@ -258,13 +266,33 @@ export function useNotificationFeedQuery(opts: { // At this point we're not fetching anymore, so it's time to make a decision. // If we didn't receive enough items from the server, paginate again until we do. if (itemCount < wantedItemCount.current) { - autoPaginationAttemptCount.current++ - if (autoPaginationAttemptCount.current < 50 /* failsafe */) { + const requestNextPage = shouldAutoPaginate({ + hasNextPage, + itemCount, + wantedItemCount: wantedItemCount.current, + attemptCount: autoPaginationAttemptCount.current, + }) + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage, + isLoading, + isRefetching, + requestNextPage, + }) + if (requestNextPage) { query.fetchNextPage() } } else { autoPaginationAttemptCount.current = 0 } + } else { + autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ + attemptCount: autoPaginationAttemptCount.current, + hasNextPage: false, + isLoading, + isRefetching, + requestNextPage: false, + }) } }, [query]) diff --git a/src/state/queries/notifications/pagination.ts b/src/state/queries/notifications/pagination.ts new file mode 100644 index 000000000..044adce63 --- /dev/null +++ b/src/state/queries/notifications/pagination.ts @@ -0,0 +1,36 @@ +const MAX_AUTO_PAGINATION_ATTEMPTS = 50 + +export function shouldAutoPaginate({ + hasNextPage, + itemCount, + wantedItemCount, + attemptCount, +}: { + hasNextPage: boolean + itemCount: number + wantedItemCount: number + attemptCount: number +}): boolean { + return ( + hasNextPage && + itemCount < wantedItemCount && + attemptCount < MAX_AUTO_PAGINATION_ATTEMPTS + ) +} + +export function nextAutoPaginationAttemptCount({ + attemptCount, + hasNextPage, + isLoading, + isRefetching, + requestNextPage, +}: { + attemptCount: number + hasNextPage: boolean + isLoading: boolean + isRefetching: boolean + requestNextPage: boolean +}): number { + if (isLoading || isRefetching || !hasNextPage) return 0 + return requestNextPage ? attemptCount + 1 : attemptCount +} diff --git a/src/state/queries/notifications/unread.tsx b/src/state/queries/notifications/unread.tsx index a3c4426f6..8d89ac6bd 100644 --- a/src/state/queries/notifications/unread.tsx +++ b/src/state/queries/notifications/unread.tsx @@ -14,6 +14,7 @@ import {AppState} from 'react-native' import {useQueryClient} from '@tanstack/react-query' import {EventEmitter} from 'eventemitter3' +import {getUnreadCount} from '#/lib/api/community-notifications' import BroadcastChannel from '#/lib/broadcast' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {resetBadgeCount} from '#/lib/notifications/notifications' @@ -60,6 +61,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { const [numUnread, setNumUnread] = useState('') const checkUnreadRef = useRef(null) + const refreshGenerationRef = useRef(0) const cacheRef = useRef({ usableInFeed: false, syncedAt: new Date(), @@ -95,6 +97,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { // listen for broadcasts useEffect(() => { const listener = ({data}: MessageEvent) => { + refreshGenerationRef.current += 1 cacheRef.current = { usableInFeed: false, syncedAt: new Date(), @@ -120,13 +123,22 @@ export function Provider({children}: React.PropsWithChildren<{}>) { const api = useMemo(() => { return { async markAllRead() { + refreshGenerationRef.current += 1 + const seenAt = cacheRef.current.syncedAt + // update server await agent.app.bsky.notification.updateSeen( - {seenAt: cacheRef.current.syncedAt.toISOString()}, + {seenAt: seenAt.toISOString()}, HOME_APPVIEW_PINNED_OPTS, ) // update & broadcast + cacheRef.current = { + ...cacheRef.current, + usableInFeed: false, + syncedAt: seenAt, + unreadCount: 0, + } setNumUnread('') broadcast.postMessage({event: ''}) resetBadgeCount() @@ -155,22 +167,53 @@ export function Provider({children}: React.PropsWithChildren<{}>) { } // Do not move this without ensuring it gets a symmetrical reset in the finally block. isFetchingRef.current = true + const generation = ++refreshGenerationRef.current - // count - const {page, indexedAt: lastIndexed} = await fetchPage({ - agent, - cursor: undefined, - limit: 40, - queryClient, - moderationOpts, - hideFollowNotifications: undefined, - reasons: [], - - // only fetch subjects when the page is going to be used - // in the notifications query, otherwise skip it - fetchAdditionalData: !!invalidate, - }) - const unreadCount = countUnread(page) + let nextCache: CachedFeedPage + if (invalidate) { + const [{count}, {page, indexedAt: lastIndexed}] = await Promise.all( + [ + getUnreadCount(agent), + fetchPage({ + agent, + cursor: undefined, + limit: 40, + queryClient, + moderationOpts, + hideFollowNotifications: undefined, + reasons: [], + fetchAdditionalData: true, + }), + ], + ) + const now = new Date() + const lastIndexedDate = lastIndexed + ? new Date(lastIndexed) + : undefined + nextCache = { + usableInFeed: true, + data: page, + syncedAt: + !lastIndexedDate || now > lastIndexedDate + ? now + : lastIndexedDate, + unreadCount: count, + } + } else { + const {count} = await getUnreadCount(agent) + nextCache = { + ...cacheRef.current, + usableInFeed: false, + syncedAt: new Date(), + unreadCount: count, + } + } + + if (generation !== refreshGenerationRef.current) { + return + } + + const unreadCount = nextCache.unreadCount const unreadCountStr = unreadCount >= 30 ? '30+' @@ -178,18 +221,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { ? '' : String(unreadCount) - // track last sync - const now = new Date() - const lastIndexedDate = lastIndexed - ? new Date(lastIndexed) - : undefined - cacheRef.current = { - usableInFeed: !!invalidate, // will be used immediately - data: page, - syncedAt: - !lastIndexedDate || now > lastIndexedDate ? now : lastIndexedDate, - unreadCount, - } + cacheRef.current = nextCache // update & broadcast setNumUnread(unreadCountStr) @@ -228,23 +260,6 @@ export function useUnreadNotificationsApi() { return useContext(apiContext) } -function countUnread(page: FeedPage) { - let num = 0 - for (const item of page.items) { - if (!item.notification.isRead) { - num++ - } - if (item.additional) { - for (const item2 of item.additional) { - if (!item2.isRead) { - num++ - } - } - } - } - return num -} - export function invalidateCachedUnreadPage() { emitter.emit('invalidate') } diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index 59e8f5d5f..e6637083c 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -16,9 +16,9 @@ import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' import {communityXrpc} from '#/lib/api/community' +import {listNotifications} from '#/lib/api/community-notifications' import {isCommunityPostUri} from '#/lib/api/community-post' import {toPostView} from '#/lib/api/space-views' -import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' import {precacheProfile} from '../profile' @@ -64,19 +64,12 @@ export async function fetchPage({ page: FeedPage indexedAt: string | undefined }> { - const res = await agent.app.bsky.notification.listNotifications( - { - limit, - cursor, - reasons, - }, - HOME_APPVIEW_PINNED_OPTS, - ) + const data = await listNotifications(agent, {limit, cursor, reasons}) - const indexedAt = res.data.notifications[0]?.indexedAt + const indexedAt = data.notifications[0]?.indexedAt // filter out notifs by mod rules - const notifs = res.data.notifications.filter( + const notifs = data.notifications.filter( notif => !shouldFilterNotif(notif, moderationOpts, hideFollowNotifications), ) @@ -106,17 +99,17 @@ export async function fetchPage({ } } - let seenAt = res.data.seenAt ? new Date(res.data.seenAt) : new Date() + let seenAt = data.seenAt ? new Date(data.seenAt) : new Date() if (Number.isNaN(seenAt.getTime())) { seenAt = new Date() } return { page: { - cursor: res.data.cursor, + cursor: data.cursor, seenAt, items: notifsGrouped, - priority: res.data.priority ?? false, + priority: data.priority ?? false, }, indexedAt, } -- knotmirror 0.0.1