migrate the threadgate and postgate records to the pds client

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Samuel Newman
2026-08-03 23:11:47 +03:00
parent a6682ebf1d
commit 0c8cdba703
10 changed files with 214 additions and 180 deletions
+2 -14
View File
@@ -1400,16 +1400,13 @@
}, },
"src/state/queries/postgate/index.ts": { "src/state/queries/postgate/index.ts": {
"typescript/no-explicit-any": { "typescript/no-explicit-any": {
"count": 2 "count": 1
}, },
"typescript/no-floating-promises": { "typescript/no-floating-promises": {
"count": 1 "count": 1
}, },
"typescript/no-unsafe-call": {
"count": 2
},
"typescript/no-unsafe-member-access": { "typescript/no-unsafe-member-access": {
"count": 3 "count": 1
}, },
"typescript/require-await": { "typescript/require-await": {
"count": 2 "count": 2
@@ -1426,18 +1423,9 @@
} }
}, },
"src/state/queries/threadgate/index.ts": { "src/state/queries/threadgate/index.ts": {
"typescript/no-explicit-any": {
"count": 1
},
"typescript/no-floating-promises": { "typescript/no-floating-promises": {
"count": 3 "count": 3
}, },
"typescript/no-unsafe-call": {
"count": 2
},
"typescript/no-unsafe-member-access": {
"count": 2
},
"typescript/require-await": { "typescript/require-await": {
"count": 3 "count": 3
} }
@@ -1,10 +1,7 @@
import {useCallback, useMemo, useState} from 'react' import {useCallback, useMemo, useState} from 'react'
import {LayoutAnimation, Text as NestedText, View} from 'react-native' import {LayoutAnimation, Text as NestedText, View} from 'react-native'
import { import {type AppBskyFeedDefs} from '@atproto/api'
type AppBskyFeedDefs, import {AtUri} from '@atproto/syntax'
type AppBskyFeedPostgate,
AtUri,
} from '@atproto/api'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Plural, Trans} from '@lingui/react/macro' import {Plural, Trans} from '@lingui/react/macro'
@@ -36,7 +33,7 @@ import {
PostThreadContextProvider, PostThreadContextProvider,
usePostThreadContext, usePostThreadContext,
} from '#/state/queries/usePostThread' } from '#/state/queries/usePostThread'
import {useAgent, useSession} from '#/state/session' import {usePdsClient, useSession} from '#/state/session'
import {UserAvatar} from '#/view/com/util/UserAvatar' import {UserAvatar} from '#/view/com/util/UserAvatar'
import {atoms as a, useTheme, web} from '#/alf' import {atoms as a, useTheme, web} from '#/alf'
import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {Button, ButtonIcon, ButtonText} from '#/components/Button'
@@ -53,6 +50,7 @@ import * as Toast from '#/components/Toast'
import {Text} from '#/components/Typography' import {Text} from '#/components/Typography'
import {useAnalytics} from '#/analytics' import {useAnalytics} from '#/analytics'
import {IS_IOS} from '#/env' import {IS_IOS} from '#/env'
import {type app} from '#/lexicons'
export type PostInteractionSettingsFormProps = { export type PostInteractionSettingsFormProps = {
canSave?: boolean canSave?: boolean
@@ -63,8 +61,8 @@ export type PostInteractionSettingsFormProps = {
persist?: boolean persist?: boolean
onChangePersist?: (v: boolean) => void onChangePersist?: (v: boolean) => void
postgate: AppBskyFeedPostgate.Record postgate: app.bsky.feed.postgate.Main
onChangePostgate: (v: AppBskyFeedPostgate.Record) => void onChangePostgate: (v: app.bsky.feed.postgate.Main) => void
threadgateAllowUISettings: ThreadgateAllowUISetting[] threadgateAllowUISettings: ThreadgateAllowUISetting[]
onChangeThreadgateAllowUISettings: (v: ThreadgateAllowUISetting[]) => void onChangeThreadgateAllowUISettings: (v: ThreadgateAllowUISetting[]) => void
@@ -178,7 +176,7 @@ export function PostInteractionSettingsDialogControlledInner(
const {mutateAsync: setThreadgateAllow} = useSetThreadgateAllowMutation() const {mutateAsync: setThreadgateAllow} = useSetThreadgateAllowMutation()
const [editedPostgate, setEditedPostgate] = const [editedPostgate, setEditedPostgate] =
useState<AppBskyFeedPostgate.Record>() useState<app.bsky.feed.postgate.Main>()
const [editedAllowUISettings, setEditedAllowUISettings] = const [editedAllowUISettings, setEditedAllowUISettings] =
useState<ThreadgateAllowUISetting[]>() useState<ThreadgateAllowUISetting[]>()
@@ -697,7 +695,7 @@ export function usePrefetchPostInteractionSettings({
}) { }) {
const ax = useAnalytics() const ax = useAnalytics()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const agent = useAgent() const pdsClient = usePdsClient()
const getPost = useGetPost() const getPost = useGetPost()
return useCallback(async () => { return useCallback(async () => {
@@ -706,7 +704,7 @@ export function usePrefetchPostInteractionSettings({
queryClient.prefetchQuery({ queryClient.prefetchQuery({
queryKey: createPostgateQueryKey(postUri), queryKey: createPostgateQueryKey(postUri),
queryFn: () => queryFn: () =>
getPostgateRecord({agent, postUri}).then(res => res ?? null), getPostgateRecord({pdsClient, postUri}).then(res => res ?? null),
staleTime: STALE.SECONDS.THIRTY, staleTime: STALE.SECONDS.THIRTY,
}), }),
queryClient.prefetchQuery({ queryClient.prefetchQuery({
@@ -723,5 +721,5 @@ export function usePrefetchPostInteractionSettings({
safeMessage: e.message, safeMessage: e.message,
}) })
} }
}, [ax, queryClient, agent, postUri, rootPostUri, getPost]) }, [ax, queryClient, pdsClient, postUri, rootPostUri, getPost])
} }
+2 -1
View File
@@ -16,6 +16,7 @@ import {
} from '@atproto/api' } from '@atproto/api'
import {TID} from '@atproto/common-web' import {TID} from '@atproto/common-web'
import {type Client} from '@atproto/lex' import {type Client} from '@atproto/lex'
import {toDatetimeString} from '@atproto/syntax'
import {RichText} from '@bsky.app/sdk/richtext' import {RichText} from '@bsky.app/sdk/richtext'
import {t} from '@lingui/core/macro' import {t} from '@lingui/core/macro'
import {type QueryClient} from '@tanstack/react-query' import {type QueryClient} from '@tanstack/react-query'
@@ -145,7 +146,7 @@ export async function post(
collection: 'app.bsky.feed.threadgate', collection: 'app.bsky.feed.threadgate',
rkey: rkey, rkey: rkey,
value: createThreadgateRecord({ value: createThreadgateRecord({
createdAt: now.toISOString(), createdAt: toDatetimeString(now),
post: uri, post: uri,
allow: threadgateAllowUISettingToAllowRecordValue(thread.threadgate), allow: threadgateAllowUISettingToAllowRecordValue(thread.threadgate),
}), }),
@@ -1,5 +1,6 @@
import {useCallback, useMemo, useState} from 'react' import {useCallback, useMemo, useState} from 'react'
import {View} from 'react-native' import {View} from 'react-native'
import {type AtUriString, toDatetimeString} from '@atproto/syntax'
import {msg} from '@lingui/core/macro' import {msg} from '@lingui/core/macro'
import {useLingui} from '@lingui/react' import {useLingui} from '@lingui/react'
import {Trans} from '@lingui/react/macro' import {Trans} from '@lingui/react/macro'
@@ -22,6 +23,7 @@ import {PostInteractionSettingsForm} from '#/components/dialogs/PostInteractionS
import * as Layout from '#/components/Layout' import * as Layout from '#/components/Layout'
import {Loader} from '#/components/Loader' import {Loader} from '#/components/Loader'
import * as Toast from '#/components/Toast' import * as Toast from '#/components/Toast'
import {type app} from '#/lexicons'
export function Screen() { export function Screen() {
const gutters = useGutters(['base']) const gutters = useGutters(['base'])
@@ -68,16 +70,21 @@ function Inner({preferences}: {preferences: UsePreferencesQueryResponse}) {
const allowUI = useMemo(() => { const allowUI = useMemo(() => {
return threadgateRecordToAllowUISetting({ return threadgateRecordToAllowUISetting({
$type: 'app.bsky.feed.threadgate', $type: 'app.bsky.feed.threadgate',
post: '', post: '' as AtUriString,
createdAt: new Date().toString(), createdAt: toDatetimeString(new Date()),
allow: preferences.postInteractionSettings.threadgateAllowRules, /*
* Preferences are still typed against the legacy client, so the stored
* rules arrive unbranded. Wave B migrates `getPreferences`.
*/
allow: preferences.postInteractionSettings
.threadgateAllowRules as app.bsky.feed.threadgate.Main['allow'],
}) })
}, [preferences.postInteractionSettings.threadgateAllowRules]) }, [preferences.postInteractionSettings.threadgateAllowRules])
const postgate = useMemo(() => { const postgate = useMemo(() => {
return createPostgateRecord({ return createPostgateRecord({
post: '', post: '',
embeddingRules: embeddingRules: preferences.postInteractionSettings
preferences.postInteractionSettings.postgateEmbeddingRules, .postgateEmbeddingRules as app.bsky.feed.postgate.Main['embeddingRules'],
}) })
}, [preferences.postInteractionSettings.postgateEmbeddingRules]) }, [preferences.postInteractionSettings.postgateEmbeddingRules])
+41 -42
View File
@@ -3,13 +3,13 @@ import {
AppBskyEmbedRecord, AppBskyEmbedRecord,
AppBskyEmbedRecordWithMedia, AppBskyEmbedRecordWithMedia,
type AppBskyFeedDefs, type AppBskyFeedDefs,
AppBskyFeedPostgate,
type AtpAgent,
AtUri,
} from '@atproto/api' } from '@atproto/api'
import {type Client} from '@atproto/lex'
import {AtUri, type HandleString} from '@atproto/syntax'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {networkRetry, retry} from '#/lib/async/retry' import {networkRetry, retry} from '#/lib/async/retry'
import {isRecordNotFoundError} from '#/lib/xrpc-error'
import {logger} from '#/logger' import {logger} from '#/logger'
import {updatePostShadow} from '#/state/cache/post-shadow' import {updatePostShadow} from '#/state/cache/post-shadow'
import {STALE} from '#/state/queries' import {STALE} from '#/state/queries'
@@ -20,28 +20,28 @@ import {
mergePostgateRecords, mergePostgateRecords,
POSTGATE_COLLECTION, POSTGATE_COLLECTION,
} from '#/state/queries/postgate/util' } from '#/state/queries/postgate/util'
import {useAgent} from '#/state/session' import {usePdsClient} from '#/state/session'
import {app, com} from '#/lexicons'
import * as bsky from '#/types/bsky' import * as bsky from '#/types/bsky'
export async function getPostgateRecord({ export async function getPostgateRecord({
agent, pdsClient,
postUri, postUri,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
}): Promise<AppBskyFeedPostgate.Record | undefined> { }): Promise<app.bsky.feed.postgate.Main | undefined> {
const urip = new AtUri(postUri) const urip = new AtUri(postUri)
if (!urip.host.startsWith('did:')) { if (!urip.host.startsWith('did:')) {
const res = await agent.resolveHandle({ const {did} = await pdsClient.call(com.atproto.identity.resolveHandle, {
handle: urip.host, handle: urip.host as HandleString,
}) })
// @ts-expect-error TODO new-sdk-migration urip.host = did
urip.host = res.data.did
} }
try { try {
const {data} = await retry( const data = await retry(
2, 2,
e => { e => {
/* /*
@@ -49,34 +49,31 @@ export async function getPostgateRecord({
* throwing an error. NB: This will also catch reference errors, such as * throwing an error. NB: This will also catch reference errors, such as
* a typo in the URI. * a typo in the URI.
*/ */
if (e.message.includes(`Could not locate record:`)) { if (isRecordNotFoundError(e)) {
return false return false
} }
return true return true
}, },
() => () =>
agent.api.com.atproto.repo.getRecord({ pdsClient.call(com.atproto.repo.getRecord, {
repo: urip.host, repo: urip.host,
collection: POSTGATE_COLLECTION, collection: POSTGATE_COLLECTION,
rkey: urip.rkey, rkey: urip.rkeySafe,
}), }),
) )
if ( if (data.value && bsky.matches(app.bsky.feed.postgate, data.value)) {
data.value &&
bsky.validate(data.value, AppBskyFeedPostgate.validateRecord)
) {
return data.value return data.value
} else { } else {
return undefined return undefined
} }
} catch (e: any) { } catch (e) {
/* /*
* If the record doesn't exist, we want to return null instead of * If the record doesn't exist, we want to return null instead of
* throwing an error. NB: This will also catch reference errors, such as * throwing an error. NB: This will also catch reference errors, such as
* a typo in the URI. * a typo in the URI.
*/ */
if (e.message.includes(`Could not locate record:`)) { if (isRecordNotFoundError(e)) {
return undefined return undefined
} else { } else {
throw e throw e
@@ -85,21 +82,21 @@ export async function getPostgateRecord({
} }
export async function writePostgateRecord({ export async function writePostgateRecord({
agent, pdsClient,
postUri, postUri,
postgate, postgate,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
postgate: AppBskyFeedPostgate.Record postgate: app.bsky.feed.postgate.Main
}) { }) {
const postUrip = new AtUri(postUri) const postUrip = new AtUri(postUri)
await networkRetry(2, () => await networkRetry(2, () =>
agent.api.com.atproto.repo.putRecord({ pdsClient.call(com.atproto.repo.putRecord, {
repo: agent.session!.did, repo: pdsClient.assertDid,
collection: POSTGATE_COLLECTION, collection: POSTGATE_COLLECTION,
rkey: postUrip.rkey, rkey: postUrip.rkeySafe,
record: postgate, record: postgate,
}), }),
) )
@@ -107,24 +104,24 @@ export async function writePostgateRecord({
export async function upsertPostgate( export async function upsertPostgate(
{ {
agent, pdsClient,
postUri, postUri,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
}, },
callback: ( callback: (
postgate: AppBskyFeedPostgate.Record | undefined, postgate: app.bsky.feed.postgate.Main | undefined,
) => Promise<AppBskyFeedPostgate.Record | undefined>, ) => Promise<app.bsky.feed.postgate.Main | undefined>,
) { ) {
const prev = await getPostgateRecord({ const prev = await getPostgateRecord({
agent, pdsClient,
postUri, postUri,
}) })
const next = await callback(prev) const next = await callback(prev)
if (!next) return if (!next) return
await writePostgateRecord({ await writePostgateRecord({
agent, pdsClient,
postUri, postUri,
postgate: next, postgate: next,
}) })
@@ -135,18 +132,20 @@ export const createPostgateQueryKey = (postUri: string) => [
postUri, postUri,
] ]
export function usePostgateQuery({postUri}: {postUri: string}) { export function usePostgateQuery({postUri}: {postUri: string}) {
const agent = useAgent() const pdsClient = usePdsClient()
return useQuery({ return useQuery({
staleTime: STALE.SECONDS.THIRTY, staleTime: STALE.SECONDS.THIRTY,
queryKey: createPostgateQueryKey(postUri), queryKey: createPostgateQueryKey(postUri),
async queryFn() { async queryFn() {
return await getPostgateRecord({agent, postUri}).then(res => res ?? null) return await getPostgateRecord({pdsClient, postUri}).then(
res => res ?? null,
)
}, },
}) })
} }
export function useWritePostgateMutation() { export function useWritePostgateMutation() {
const agent = useAgent() const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
@@ -154,10 +153,10 @@ export function useWritePostgateMutation() {
postgate, postgate,
}: { }: {
postUri: string postUri: string
postgate: AppBskyFeedPostgate.Record postgate: app.bsky.feed.postgate.Main
}) => { }) => {
return writePostgateRecord({ return writePostgateRecord({
agent, pdsClient,
postUri, postUri,
postgate, postgate,
}) })
@@ -171,7 +170,7 @@ export function useWritePostgateMutation() {
} }
export function useToggleQuoteDetachmentMutation() { export function useToggleQuoteDetachmentMutation() {
const agent = useAgent() const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const getPosts = useGetPosts() const getPosts = useGetPosts()
const prevEmbed = useRef<AppBskyFeedDefs.PostView['embed']>(undefined) const prevEmbed = useRef<AppBskyFeedDefs.PostView['embed']>(undefined)
@@ -200,7 +199,7 @@ export function useToggleQuoteDetachmentMutation() {
}) })
} }
await upsertPostgate({agent, postUri: quoteUri}, async prev => { await upsertPostgate({pdsClient, postUri: quoteUri}, async prev => {
if (prev) { if (prev) {
if (action === 'detach') { if (action === 'detach') {
return mergePostgateRecords(prev, { return mergePostgateRecords(prev, {
@@ -264,7 +263,7 @@ export function useToggleQuoteDetachmentMutation() {
} }
export function useToggleQuotepostEnabledMutation() { export function useToggleQuotepostEnabledMutation() {
const agent = useAgent() const pdsClient = usePdsClient()
return useMutation({ return useMutation({
mutationFn: async ({ mutationFn: async ({
@@ -274,7 +273,7 @@ export function useToggleQuotepostEnabledMutation() {
postUri: string postUri: string
action: 'enable' | 'disable' action: 'enable' | 'disable'
}) => { }) => {
await upsertPostgate({agent, postUri: postUri}, async prev => { await upsertPostgate({pdsClient, postUri: postUri}, async prev => {
if (prev) { if (prev) {
if (action === 'disable') { if (action === 'disable') {
return mergePostgateRecords(prev, { return mergePostgateRecords(prev, {
+24 -10
View File
@@ -3,29 +3,43 @@ import {
AppBskyEmbedRecord, AppBskyEmbedRecord,
AppBskyEmbedRecordWithMedia, AppBskyEmbedRecordWithMedia,
type AppBskyFeedDefs, type AppBskyFeedDefs,
type AppBskyFeedPostgate,
AtUri, AtUri,
} from '@atproto/api' } from '@atproto/api'
import {type AtUriString, toDatetimeString} from '@atproto/syntax'
import {type app} from '#/lexicons'
export const POSTGATE_COLLECTION = 'app.bsky.feed.postgate' export const POSTGATE_COLLECTION = 'app.bsky.feed.postgate'
/**
* Create a new {@link app.bsky.feed.postgate.Main}. URIs are accepted as plain
* strings (callers hold raw AT-URIs, often from legacy-typed views) and
* asserted to the branded `AtUriString` here.
*/
export function createPostgateRecord( export function createPostgateRecord(
postgate: Partial<AppBskyFeedPostgate.Record> & { postgate: Omit<
post: AppBskyFeedPostgate.Record['post'] Partial<app.bsky.feed.postgate.Main>,
'post' | 'detachedEmbeddingUris'
> & {
post: string
detachedEmbeddingUris?: string[]
}, },
): AppBskyFeedPostgate.Record { ): app.bsky.feed.postgate.Main {
return { return {
$type: POSTGATE_COLLECTION, $type: POSTGATE_COLLECTION,
createdAt: new Date().toISOString(), createdAt: toDatetimeString(new Date()),
post: postgate.post, post: postgate.post as AtUriString,
detachedEmbeddingUris: postgate.detachedEmbeddingUris || [], detachedEmbeddingUris: (postgate.detachedEmbeddingUris ||
[]) as AtUriString[],
embeddingRules: postgate.embeddingRules || [], embeddingRules: postgate.embeddingRules || [],
} }
} }
export function mergePostgateRecords( export function mergePostgateRecords(
prev: AppBskyFeedPostgate.Record, prev: app.bsky.feed.postgate.Main,
next: Partial<AppBskyFeedPostgate.Record>, next: Omit<Partial<app.bsky.feed.postgate.Main>, 'detachedEmbeddingUris'> & {
detachedEmbeddingUris?: string[]
},
) { ) {
const detachedEmbeddingUris = Array.from( const detachedEmbeddingUris = Array.from(
new Set([ new Set([
@@ -199,5 +213,5 @@ export function getMaybeDetachedQuoteEmbed({
} }
export const embeddingRules = { export const embeddingRules = {
disableRule: {$type: 'app.bsky.feed.postgate#disableRule'}, disableRule: {$type: 'app.bsky.feed.postgate#disableRule'} as const,
} }
+43 -48
View File
@@ -1,12 +1,10 @@
import { import {type AppBskyFeedDefs} from '@atproto/api'
type AppBskyFeedDefs, import {type Client} from '@atproto/lex'
AppBskyFeedThreadgate, import {AtUri, type HandleString} from '@atproto/syntax'
type AtpAgent,
AtUri,
} from '@atproto/api'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {networkRetry, retry} from '#/lib/async/retry' import {networkRetry, retry} from '#/lib/async/retry'
import {isRecordNotFoundError} from '#/lib/xrpc-error'
import {STALE} from '#/state/queries' import {STALE} from '#/state/queries'
import {useGetPost} from '#/state/queries/post' import {useGetPost} from '#/state/queries/post'
import {type ThreadgateAllowUISetting} from '#/state/queries/threadgate/types' import {type ThreadgateAllowUISetting} from '#/state/queries/threadgate/types'
@@ -17,8 +15,9 @@ import {
threadgateViewToAllowUISetting, threadgateViewToAllowUISetting,
} from '#/state/queries/threadgate/util' } from '#/state/queries/threadgate/util'
import {useUpdatePostThreadThreadgateQueryCache} from '#/state/queries/usePostThread' import {useUpdatePostThreadThreadgateQueryCache} from '#/state/queries/usePostThread'
import {useAgent} from '#/state/session' import {usePdsClient} from '#/state/session'
import {useThreadgateHiddenReplyUrisAPI} from '#/state/threadgate-hidden-replies' import {useThreadgateHiddenReplyUrisAPI} from '#/state/threadgate-hidden-replies'
import {app, com} from '#/lexicons'
import * as bsky from '#/types/bsky' import * as bsky from '#/types/bsky'
export * from '#/state/queries/threadgate/types' export * from '#/state/queries/threadgate/types'
@@ -40,9 +39,9 @@ export function useThreadgateRecordQuery({
initialData, initialData,
}: { }: {
postUri?: string postUri?: string
initialData?: AppBskyFeedThreadgate.Record initialData?: app.bsky.feed.threadgate.Main
} = {}) { } = {}) {
const agent = useAgent() const pdsClient = usePdsClient()
return useQuery({ return useQuery({
enabled: !!postUri, enabled: !!postUri,
@@ -51,7 +50,7 @@ export function useThreadgateRecordQuery({
staleTime: STALE.MINUTES.ONE, staleTime: STALE.MINUTES.ONE,
async queryFn() { async queryFn() {
return getThreadgateRecord({ return getThreadgateRecord({
agent, pdsClient,
postUri: postUri!, postUri: postUri!,
}) })
}, },
@@ -85,24 +84,23 @@ export function useThreadgateViewQuery({
} }
export async function getThreadgateRecord({ export async function getThreadgateRecord({
agent, pdsClient,
postUri, postUri,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
}): Promise<AppBskyFeedThreadgate.Record | null> { }): Promise<app.bsky.feed.threadgate.Main | null> {
const urip = new AtUri(postUri) const urip = new AtUri(postUri)
if (!urip.host.startsWith('did:')) { if (!urip.host.startsWith('did:')) {
const res = await agent.resolveHandle({ const {did} = await pdsClient.call(com.atproto.identity.resolveHandle, {
handle: urip.host, handle: urip.host as HandleString,
}) })
// @ts-expect-error TODO new-sdk-migration urip.host = did
urip.host = res.data.did
} }
try { try {
const {data} = await retry( const data = await retry(
2, 2,
e => { e => {
/* /*
@@ -110,34 +108,31 @@ export async function getThreadgateRecord({
* throwing an error. NB: This will also catch reference errors, such as * throwing an error. NB: This will also catch reference errors, such as
* a typo in the URI. * a typo in the URI.
*/ */
if (e.message.includes(`Could not locate record:`)) { if (isRecordNotFoundError(e)) {
return false return false
} }
return true return true
}, },
() => () =>
agent.api.com.atproto.repo.getRecord({ pdsClient.call(com.atproto.repo.getRecord, {
repo: urip.host, repo: urip.host,
collection: 'app.bsky.feed.threadgate', collection: 'app.bsky.feed.threadgate',
rkey: urip.rkey, rkey: urip.rkeySafe,
}), }),
) )
if ( if (data.value && bsky.matches(app.bsky.feed.threadgate, data.value)) {
data.value &&
bsky.validate(data.value, AppBskyFeedThreadgate.validateRecord)
) {
return data.value return data.value
} else { } else {
return null return null
} }
} catch (e: any) { } catch (e) {
/* /*
* If the record doesn't exist, we want to return null instead of * If the record doesn't exist, we want to return null instead of
* throwing an error. NB: This will also catch reference errors, such as * throwing an error. NB: This will also catch reference errors, such as
* a typo in the URI. * a typo in the URI.
*/ */
if (e.message.includes(`Could not locate record:`)) { if (isRecordNotFoundError(e)) {
return null return null
} else { } else {
throw e throw e
@@ -146,13 +141,13 @@ export async function getThreadgateRecord({
} }
export async function writeThreadgateRecord({ export async function writeThreadgateRecord({
agent, pdsClient,
postUri, postUri,
threadgate, threadgate,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
threadgate: AppBskyFeedThreadgate.Record threadgate: app.bsky.feed.threadgate.Main
}) { }) {
const postUrip = new AtUri(postUri) const postUrip = new AtUri(postUri)
const record = createThreadgateRecord({ const record = createThreadgateRecord({
@@ -162,10 +157,10 @@ export async function writeThreadgateRecord({
}) })
await networkRetry(2, () => await networkRetry(2, () =>
agent.api.com.atproto.repo.putRecord({ pdsClient.call(com.atproto.repo.putRecord, {
repo: agent.session!.did, repo: pdsClient.assertDid,
collection: 'app.bsky.feed.threadgate', collection: 'app.bsky.feed.threadgate',
rkey: postUrip.rkey, rkey: postUrip.rkeySafe,
record, record,
}), }),
) )
@@ -173,25 +168,25 @@ export async function writeThreadgateRecord({
export async function upsertThreadgate( export async function upsertThreadgate(
{ {
agent, pdsClient,
postUri, postUri,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
}, },
callback: ( callback: (
threadgate: AppBskyFeedThreadgate.Record | null, threadgate: app.bsky.feed.threadgate.Main | null,
) => Promise<AppBskyFeedThreadgate.Record | undefined>, ) => Promise<app.bsky.feed.threadgate.Main | undefined>,
) { ) {
const prev = await getThreadgateRecord({ const prev = await getThreadgateRecord({
agent, pdsClient,
postUri, postUri,
}) })
const next = await callback(prev) const next = await callback(prev)
if (!next) return if (!next) return
validateThreadgateRecordOrThrow(next) validateThreadgateRecordOrThrow(next)
await writeThreadgateRecord({ await writeThreadgateRecord({
agent, pdsClient,
postUri, postUri,
threadgate: next, threadgate: next,
}) })
@@ -201,15 +196,15 @@ export async function upsertThreadgate(
* Update the allow list for a threadgate record. * Update the allow list for a threadgate record.
*/ */
export async function updateThreadgateAllow({ export async function updateThreadgateAllow({
agent, pdsClient,
postUri, postUri,
allow, allow,
}: { }: {
agent: AtpAgent pdsClient: Client
postUri: string postUri: string
allow: ThreadgateAllowUISetting[] allow: ThreadgateAllowUISetting[]
}) { }) {
return upsertThreadgate({agent, postUri}, async prev => { return upsertThreadgate({pdsClient, postUri}, async prev => {
if (prev) { if (prev) {
return { return {
...prev, ...prev,
@@ -225,7 +220,7 @@ export async function updateThreadgateAllow({
} }
export function useSetThreadgateAllowMutation() { export function useSetThreadgateAllowMutation() {
const agent = useAgent() const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const getPost = useGetPost() const getPost = useGetPost()
const updatePostThreadThreadgate = useUpdatePostThreadThreadgateQueryCache() const updatePostThreadThreadgate = useUpdatePostThreadThreadgateQueryCache()
@@ -238,7 +233,7 @@ export function useSetThreadgateAllowMutation() {
postUri: string postUri: string
allow: ThreadgateAllowUISetting[] allow: ThreadgateAllowUISetting[]
}) => { }) => {
return upsertThreadgate({agent, postUri}, async prev => { return upsertThreadgate({pdsClient, postUri}, async prev => {
if (prev) { if (prev) {
return { return {
...prev, ...prev,
@@ -290,7 +285,7 @@ export function useSetThreadgateAllowMutation() {
} }
export function useToggleReplyVisibilityMutation() { export function useToggleReplyVisibilityMutation() {
const agent = useAgent() const pdsClient = usePdsClient()
const queryClient = useQueryClient() const queryClient = useQueryClient()
const hiddenReplies = useThreadgateHiddenReplyUrisAPI() const hiddenReplies = useThreadgateHiddenReplyUrisAPI()
@@ -310,7 +305,7 @@ export function useToggleReplyVisibilityMutation() {
hiddenReplies.removeHiddenReplyUri(replyUri) hiddenReplies.removeHiddenReplyUri(replyUri)
} }
await upsertThreadgate({agent, postUri}, async prev => { await upsertThreadgate({pdsClient, postUri}, async prev => {
if (prev) { if (prev) {
if (action === 'hide') { if (action === 'hide') {
return mergeThreadgateRecords(prev, { return mergeThreadgateRecords(prev, {
@@ -363,9 +358,9 @@ export class InvalidInteractionSettingsError extends Error {
} }
export function validateThreadgateRecordOrThrow( export function validateThreadgateRecordOrThrow(
record: AppBskyFeedThreadgate.Record, record: app.bsky.feed.threadgate.Main,
) { ) {
const result = AppBskyFeedThreadgate.validateRecord(record) const result = bsky.safeParse(app.bsky.feed.threadgate, record)
if (result.success) { if (result.success) {
if ((result.value.hiddenReplies?.length ?? 0) > MAX_HIDDEN_REPLIES) { if ((result.value.hiddenReplies?.length ?? 0) > MAX_HIDDEN_REPLIES) {
+42 -25
View File
@@ -1,26 +1,34 @@
import {type AppBskyFeedDefs, AppBskyFeedThreadgate} from '@atproto/api' import {type AppBskyFeedDefs} from '@atproto/api'
import {type AtUriString, toDatetimeString} from '@atproto/syntax'
import {type ThreadgateAllowUISetting} from '#/state/queries/threadgate/types' import {type ThreadgateAllowUISetting} from '#/state/queries/threadgate/types'
import {app} from '#/lexicons'
import * as bsky from '#/types/bsky' import * as bsky from '#/types/bsky'
/*
* Threadgate VIEWS stay on the legacy client types: they are read-only inputs
* from the appview, and branding them here would ripple through every post
* component. Only the threadgate RECORD is migrated, because it is written
* through `com.atproto.repo.putRecord`, whose body is typed as a lex `LexMap`.
*/
export function threadgateViewToAllowUISetting( export function threadgateViewToAllowUISetting(
threadgateView: AppBskyFeedDefs.ThreadgateView | undefined, threadgateView: AppBskyFeedDefs.ThreadgateView | undefined,
): ThreadgateAllowUISetting[] { ): ThreadgateAllowUISetting[] {
// Validate the record for clarity, since backwards compat code is a little confusing // Validate the record for clarity, since backwards compat code is a little confusing
const threadgate = const threadgate =
threadgateView && threadgateView &&
bsky.validate(threadgateView.record, AppBskyFeedThreadgate.validateRecord) bsky.matches(app.bsky.feed.threadgate, threadgateView.record)
? threadgateView.record ? threadgateView.record
: undefined : undefined
return threadgateRecordToAllowUISetting(threadgate) return threadgateRecordToAllowUISetting(threadgate)
} }
/** /**
* Converts a full {@link AppBskyFeedThreadgate.Record} to a list of * Converts a full {@link app.bsky.feed.threadgate.Main} to a list of
* {@link ThreadgateAllowUISetting}, for use by app UI. * {@link ThreadgateAllowUISetting}, for use by app UI.
*/ */
export function threadgateRecordToAllowUISetting( export function threadgateRecordToAllowUISetting(
threadgate: AppBskyFeedThreadgate.Record | undefined, threadgate: app.bsky.feed.threadgate.Main | undefined,
): ThreadgateAllowUISetting[] { ): ThreadgateAllowUISetting[] {
/* /*
* If `threadgate` doesn't exist (default), or if `threadgate.allow === undefined`, it means * If `threadgate` doesn't exist (default), or if `threadgate.allow === undefined`, it means
@@ -40,13 +48,13 @@ export function threadgateRecordToAllowUISetting(
const settings: ThreadgateAllowUISetting[] = threadgate.allow const settings: ThreadgateAllowUISetting[] = threadgate.allow
.map(allow => { .map(allow => {
let setting: ThreadgateAllowUISetting | undefined let setting: ThreadgateAllowUISetting | undefined
if (AppBskyFeedThreadgate.isMentionRule(allow)) { if (bsky.isType(app.bsky.feed.threadgate.mentionRule, allow)) {
setting = {type: 'mention'} setting = {type: 'mention'}
} else if (AppBskyFeedThreadgate.isFollowingRule(allow)) { } else if (bsky.isType(app.bsky.feed.threadgate.followingRule, allow)) {
setting = {type: 'following'} setting = {type: 'following'}
} else if (AppBskyFeedThreadgate.isListRule(allow)) { } else if (bsky.isType(app.bsky.feed.threadgate.listRule, allow)) {
setting = {type: 'list', list: allow.list} setting = {type: 'list', list: allow.list}
} else if (AppBskyFeedThreadgate.isFollowerRule(allow)) { } else if (bsky.isType(app.bsky.feed.threadgate.followerRule, allow)) {
setting = {type: 'followers'} setting = {type: 'followers'}
} }
return setting return setting
@@ -57,7 +65,7 @@ export function threadgateRecordToAllowUISetting(
/** /**
* Converts an array of {@link ThreadgateAllowUISetting} to the `allow` prop on * Converts an array of {@link ThreadgateAllowUISetting} to the `allow` prop on
* {@link AppBskyFeedThreadgate.Record}. * {@link app.bsky.feed.threadgate.Main}.
* *
* If the `allow` property on the record is undefined, we infer that to mean * If the `allow` property on the record is undefined, we infer that to mean
* that everyone can reply. If it's an empty array, we infer that to mean that * that everyone can reply. If it's an empty array, we infer that to mean that
@@ -65,12 +73,12 @@ export function threadgateRecordToAllowUISetting(
*/ */
export function threadgateAllowUISettingToAllowRecordValue( export function threadgateAllowUISettingToAllowRecordValue(
threadgate: ThreadgateAllowUISetting[], threadgate: ThreadgateAllowUISetting[],
): AppBskyFeedThreadgate.Record['allow'] { ): app.bsky.feed.threadgate.Main['allow'] {
if (threadgate.find(v => v.type === 'everybody')) { if (threadgate.find(v => v.type === 'everybody')) {
return undefined return undefined
} }
let allow: Exclude<AppBskyFeedThreadgate.Record['allow'], undefined> = [] let allow: Exclude<app.bsky.feed.threadgate.Main['allow'], undefined> = []
if (!threadgate.find(v => v.type === 'nobody')) { if (!threadgate.find(v => v.type === 'nobody')) {
for (const rule of threadgate) { for (const rule of threadgate) {
@@ -83,7 +91,7 @@ export function threadgateAllowUISettingToAllowRecordValue(
} else if (rule.type === 'list') { } else if (rule.type === 'list') {
allow.push({ allow.push({
$type: 'app.bsky.feed.threadgate#listRule', $type: 'app.bsky.feed.threadgate#listRule',
list: rule.list, list: rule.list as AtUriString,
}) })
} }
} }
@@ -93,18 +101,20 @@ export function threadgateAllowUISettingToAllowRecordValue(
} }
/** /**
* Merges two {@link AppBskyFeedThreadgate.Record} objects, combining their * Merges two {@link app.bsky.feed.threadgate.Main} objects, combining their
* `allow` and `hiddenReplies` arrays and de-deduplicating them. * `allow` and `hiddenReplies` arrays and de-deduplicating them.
* *
* Note: `allow` can be undefined here, be sure you don't accidentally set it * Note: `allow` can be undefined here, be sure you don't accidentally set it
* to an empty array. See other comments in this file. * to an empty array. See other comments in this file.
*/ */
export function mergeThreadgateRecords( export function mergeThreadgateRecords(
prev: AppBskyFeedThreadgate.Record, prev: app.bsky.feed.threadgate.Main,
next: Partial<AppBskyFeedThreadgate.Record>, next: Omit<Partial<app.bsky.feed.threadgate.Main>, 'hiddenReplies'> & {
): AppBskyFeedThreadgate.Record { hiddenReplies?: string[]
},
): app.bsky.feed.threadgate.Main {
// can be undefined if everyone can reply! // can be undefined if everyone can reply!
const allow: AppBskyFeedThreadgate.Record['allow'] | undefined = const allow: app.bsky.feed.threadgate.Main['allow'] | undefined =
prev.allow || next.allow prev.allow || next.allow
? [...(prev.allow || []), ...(next.allow || [])].filter( ? [...(prev.allow || []), ...(next.allow || [])].filter(
(v, i, a) => a.findIndex(t => t.$type === v.$type) === i, (v, i, a) => a.findIndex(t => t.$type === v.$type) === i,
@@ -112,7 +122,7 @@ export function mergeThreadgateRecords(
: undefined : undefined
const hiddenReplies = Array.from( const hiddenReplies = Array.from(
new Set([...(prev.hiddenReplies || []), ...(next.hiddenReplies || [])]), new Set([...(prev.hiddenReplies || []), ...(next.hiddenReplies || [])]),
) ) as AtUriString[]
return createThreadgateRecord({ return createThreadgateRecord({
post: prev.post, post: prev.post,
@@ -122,21 +132,28 @@ export function mergeThreadgateRecords(
} }
/** /**
* Create a new {@link AppBskyFeedThreadgate.Record} object with the given * Create a new {@link app.bsky.feed.threadgate.Main} object with the given
* properties. * properties. `post` is accepted as a plain string (callers hold raw AT-URIs)
* and asserted to the branded `AtUriString` here.
*/ */
export function createThreadgateRecord( export function createThreadgateRecord(
threadgate: Partial<AppBskyFeedThreadgate.Record>, threadgate: Omit<
): AppBskyFeedThreadgate.Record { Partial<app.bsky.feed.threadgate.Main>,
'post' | 'hiddenReplies'
> & {
post?: string
hiddenReplies?: string[]
},
): app.bsky.feed.threadgate.Main {
if (!threadgate.post) { if (!threadgate.post) {
throw new Error('Cannot create a threadgate record without a post URI') throw new Error('Cannot create a threadgate record without a post URI')
} }
return { return {
$type: 'app.bsky.feed.threadgate', $type: 'app.bsky.feed.threadgate',
post: threadgate.post, post: threadgate.post as AtUriString,
createdAt: new Date().toISOString(), createdAt: toDatetimeString(new Date()),
allow: threadgate.allow, // can be undefined! allow: threadgate.allow, // can be undefined!
hiddenReplies: threadgate.hiddenReplies || [], hiddenReplies: (threadgate.hiddenReplies || []) as AtUriString[],
} }
} }
+23 -15
View File
@@ -1,9 +1,6 @@
import {type ImagePickerAsset} from 'expo-image-picker' import {type ImagePickerAsset} from 'expo-image-picker'
import { import {type AppBskyActorDefs, type AppBskyDraftDefs} from '@atproto/api'
type AppBskyActorDefs, import {type AtUriString, toDatetimeString} from '@atproto/syntax'
type AppBskyDraftDefs,
type AppBskyFeedPostgate,
} from '@atproto/api'
import {RichText} from '@bsky.app/sdk/richtext' import {RichText} from '@bsky.app/sdk/richtext'
import {nanoid} from 'nanoid/non-secure' import {nanoid} from 'nanoid/non-secure'
@@ -103,7 +100,7 @@ export type PostAction =
export type ThreadDraft = { export type ThreadDraft = {
posts: PostDraft[] posts: PostDraft[]
postgate: AppBskyFeedPostgate.Record postgate: app.bsky.feed.postgate.Main
threadgate: ThreadgateAllowUISetting[] threadgate: ThreadgateAllowUISetting[]
} }
@@ -122,7 +119,7 @@ export type ComposerState = {
} }
export type ComposerAction = export type ComposerAction =
| {type: 'update_postgate'; postgate: AppBskyFeedPostgate.Record} | {type: 'update_postgate'; postgate: app.bsky.feed.postgate.Main}
| {type: 'update_threadgate'; threadgate: ThreadgateAllowUISetting[]} | {type: 'update_threadgate'; threadgate: ThreadgateAllowUISetting[]}
| { | {
type: 'update_post' type: 'update_post'
@@ -319,13 +316,18 @@ export function composerReducer(
posts, posts,
postgate: createPostgateRecord({ postgate: createPostgateRecord({
post: '', post: '',
embeddingRules: postgateEmbeddingRules, /*
* Draft records are still typed against the legacy client, so the
* stored rules arrive unbranded. Wave B migrates the draft types.
*/
embeddingRules:
postgateEmbeddingRules as app.bsky.feed.postgate.Main['embeddingRules'],
}), }),
threadgate: threadgateRecordToAllowUISetting({ threadgate: threadgateRecordToAllowUISetting({
$type: 'app.bsky.feed.threadgate', $type: 'app.bsky.feed.threadgate',
post: '', post: '' as AtUriString,
createdAt: new Date().toString(), createdAt: toDatetimeString(new Date()),
allow: threadgateAllow, allow: threadgateAllow as app.bsky.feed.threadgate.Main['allow'],
}), }),
}, },
} }
@@ -744,13 +746,19 @@ export function createComposerState({
], ],
postgate: createPostgateRecord({ postgate: createPostgateRecord({
post: '', post: '',
embeddingRules: initInteractionSettings?.postgateEmbeddingRules || [], /*
* Preferences are still typed against the legacy client, so the stored
* rules arrive unbranded. Wave B migrates `getPreferences`.
*/
embeddingRules: (initInteractionSettings?.postgateEmbeddingRules ||
[]) as app.bsky.feed.postgate.Main['embeddingRules'],
}), }),
threadgate: threadgateRecordToAllowUISetting({ threadgate: threadgateRecordToAllowUISetting({
$type: 'app.bsky.feed.threadgate', $type: 'app.bsky.feed.threadgate',
post: '', post: '' as AtUriString,
createdAt: new Date().toString(), createdAt: toDatetimeString(new Date()),
allow: initInteractionSettings?.threadgateAllowRules, allow:
initInteractionSettings?.threadgateAllowRules as app.bsky.feed.threadgate.Main['allow'],
}), }),
}, },
} }
@@ -1,7 +1,7 @@
import {useEffect, useMemo, useState} from 'react' import {useEffect, useMemo, useState} from 'react'
import {Keyboard, type StyleProp, type ViewStyle} from 'react-native' import {Keyboard, type StyleProp, type ViewStyle} from 'react-native'
import {type AnimatedStyle} from 'react-native-reanimated' import {type AnimatedStyle} from 'react-native-reanimated'
import {type AppBskyFeedPostgate} from '@atproto/api' import {type AtUriString, toDatetimeString} from '@atproto/syntax'
import {Trans, useLingui} from '@lingui/react/macro' import {Trans, useLingui} from '@lingui/react/macro'
import deepEqual from 'fast-deep-equal' import deepEqual from 'fast-deep-equal'
@@ -24,6 +24,7 @@ import {Group3_Stroke2_Corner0_Rounded as GroupIcon} from '#/components/icons/Gr
import * as Tooltip from '#/components/Tooltip' import * as Tooltip from '#/components/Tooltip'
import {useAnalytics} from '#/analytics' import {useAnalytics} from '#/analytics'
import {IS_NATIVE} from '#/env' import {IS_NATIVE} from '#/env'
import {type app} from '#/lexicons'
import {useThreadgateNudged} from '#/storage/hooks/threadgate-nudged' import {useThreadgateNudged} from '#/storage/hooks/threadgate-nudged'
export function ThreadgateBtn({ export function ThreadgateBtn({
@@ -32,8 +33,8 @@ export function ThreadgateBtn({
threadgateAllowUISettings, threadgateAllowUISettings,
onChangeThreadgateAllowUISettings, onChangeThreadgateAllowUISettings,
}: { }: {
postgate: AppBskyFeedPostgate.Record postgate: app.bsky.feed.postgate.Main
onChangePostgate: (v: AppBskyFeedPostgate.Record) => void onChangePostgate: (v: app.bsky.feed.postgate.Main) => void
threadgateAllowUISettings: ThreadgateAllowUISetting[] threadgateAllowUISettings: ThreadgateAllowUISetting[]
onChangeThreadgateAllowUISettings: (v: ThreadgateAllowUISetting[]) => void onChangeThreadgateAllowUISettings: (v: ThreadgateAllowUISetting[]) => void
@@ -83,14 +84,20 @@ export function ThreadgateBtn({
const prefThreadgateAllowUISettings = threadgateRecordToAllowUISetting({ const prefThreadgateAllowUISettings = threadgateRecordToAllowUISetting({
$type: 'app.bsky.feed.threadgate', $type: 'app.bsky.feed.threadgate',
post: '', post: '' as AtUriString,
createdAt: new Date().toISOString(), createdAt: toDatetimeString(new Date()),
allow: preferences?.postInteractionSettings.threadgateAllowRules, /*
* Preferences are still typed against the legacy client, so the stored
* rules arrive unbranded. Wave B migrates `getPreferences`.
*/
allow: preferences?.postInteractionSettings
.threadgateAllowRules as app.bsky.feed.threadgate.Main['allow'],
}) })
const prefPostgate = createPostgateRecord({ const prefPostgate = createPostgateRecord({
post: '', post: '',
embeddingRules: embeddingRules: (preferences?.postInteractionSettings
preferences?.postInteractionSettings?.postgateEmbeddingRules || [], ?.postgateEmbeddingRules ||
[]) as app.bsky.feed.postgate.Main['embeddingRules'],
}) })
const isDirty = useMemo(() => { const isDirty = useMemo(() => {