Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378import { type AppBskyFeedDefs, AppBskyFeedThreadgate, type AtpAgent, AtUri,} from '@atproto/api'import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
import {networkRetry, retry} from '#/lib/async/retry'import {STALE} from '#/state/queries'import {useGetPost} from '#/state/queries/post'import {type ThreadgateAllowUISetting} from '#/state/queries/threadgate/types'import { createThreadgateRecord, mergeThreadgateRecords, threadgateAllowUISettingToAllowRecordValue, threadgateViewToAllowUISetting,} from '#/state/queries/threadgate/util'import {useUpdatePostThreadThreadgateQueryCache} from '#/state/queries/usePostThread'import {useAgent} from '#/state/session'import {useThreadgateHiddenReplyUrisAPI} from '#/state/threadgate-hidden-replies'import * as bsky from '#/types/bsky'
export * from '#/state/queries/threadgate/types'export * from '#/state/queries/threadgate/util'
/** * Must match the threadgate lexicon record definition. */export const MAX_HIDDEN_REPLIES = 300
export const threadgateRecordQueryKeyRoot = 'threadgate-record'export const createThreadgateRecordQueryKey = (uri: string) => [ threadgateRecordQueryKeyRoot, uri,]
export function useThreadgateRecordQuery({ postUri, initialData,}: { postUri?: string initialData?: AppBskyFeedThreadgate.Record} = {}) { const agent = useAgent()
return useQuery({ enabled: !!postUri, queryKey: createThreadgateRecordQueryKey(postUri || ''), placeholderData: initialData, staleTime: STALE.MINUTES.ONE, async queryFn() { return getThreadgateRecord({ agent, postUri: postUri!, }) }, })}
export const threadgateViewQueryKeyRoot = 'threadgate-view'export const createThreadgateViewQueryKey = (uri: string) => [ threadgateViewQueryKeyRoot, uri,]export function useThreadgateViewQuery({ postUri, initialData,}: { postUri?: string initialData?: AppBskyFeedDefs.ThreadgateView} = {}) { const getPost = useGetPost()
return useQuery({ enabled: !!postUri, queryKey: createThreadgateViewQueryKey(postUri || ''), placeholderData: initialData, staleTime: STALE.MINUTES.ONE, async queryFn() { const post = await getPost({uri: postUri!}) return post.threadgate ?? null }, })}
export async function getThreadgateRecord({ agent, postUri,}: { agent: AtpAgent postUri: string}): Promise<AppBskyFeedThreadgate.Record | null> { const urip = new AtUri(postUri)
if (!urip.host.startsWith('did:')) { const res = await agent.resolveHandle({ handle: urip.host, }) // @ts-expect-error TODO new-sdk-migration urip.host = res.data.did }
try { const {data} = await retry( 2, e => { /* * 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 * a typo in the URI. */ if (e.message.includes(`Could not locate record:`)) { return false } return true }, () => agent.api.com.atproto.repo.getRecord({ repo: urip.host, collection: 'app.bsky.feed.threadgate', rkey: urip.rkey, }), )
if ( data.value && bsky.validate(data.value, AppBskyFeedThreadgate.validateRecord) ) { return data.value } else { return null } } catch (e: any) { /* * 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 * a typo in the URI. */ if (e.message.includes(`Could not locate record:`)) { return null } else { throw e } }}
export async function writeThreadgateRecord({ agent, postUri, threadgate,}: { agent: AtpAgent postUri: string threadgate: AppBskyFeedThreadgate.Record}) { const postUrip = new AtUri(postUri) const record = createThreadgateRecord({ post: postUri, allow: threadgate.allow, // can/should be undefined! hiddenReplies: threadgate.hiddenReplies || [], })
await networkRetry(2, () => agent.api.com.atproto.repo.putRecord({ repo: agent.session!.did, collection: 'app.bsky.feed.threadgate', rkey: postUrip.rkey, record, }), )}
export async function upsertThreadgate( { agent, postUri, }: { agent: AtpAgent postUri: string }, callback: ( threadgate: AppBskyFeedThreadgate.Record | null, ) => Promise<AppBskyFeedThreadgate.Record | undefined>,) { const prev = await getThreadgateRecord({ agent, postUri, }) const next = await callback(prev) if (!next) return validateThreadgateRecordOrThrow(next) await writeThreadgateRecord({ agent, postUri, threadgate: next, })}
/** * Update the allow list for a threadgate record. */export async function updateThreadgateAllow({ agent, postUri, allow,}: { agent: AtpAgent postUri: string allow: ThreadgateAllowUISetting[]}) { return upsertThreadgate({agent, postUri}, async prev => { if (prev) { return { ...prev, allow: threadgateAllowUISettingToAllowRecordValue(allow), } } else { return createThreadgateRecord({ post: postUri, allow: threadgateAllowUISettingToAllowRecordValue(allow), }) } })}
export function useSetThreadgateAllowMutation() { const agent = useAgent() const queryClient = useQueryClient() const getPost = useGetPost() const updatePostThreadThreadgate = useUpdatePostThreadThreadgateQueryCache()
return useMutation({ mutationFn: async ({ postUri, allow, }: { postUri: string allow: ThreadgateAllowUISetting[] }) => { return upsertThreadgate({agent, postUri}, async prev => { if (prev) { return { ...prev, allow: threadgateAllowUISettingToAllowRecordValue(allow), } } else { return createThreadgateRecord({ post: postUri, allow: threadgateAllowUISettingToAllowRecordValue(allow), }) } }) }, async onSuccess(_, {postUri, allow}) { const data = await retry<AppBskyFeedDefs.ThreadgateView | undefined>( 5, // 5 tries _e => true, async () => { const post = await getPost({uri: postUri}) const threadgate = post.threadgate if (!threadgate) { throw new Error( `useSetThreadgateAllowMutation: could not fetch threadgate, appview may not be ready yet`, ) } const fetchedSettings = threadgateViewToAllowUISetting(threadgate) const isReady = JSON.stringify(fetchedSettings) === JSON.stringify(allow) if (!isReady) { throw new Error( `useSetThreadgateAllowMutation: appview isn't ready yet`, ) // try again } return threadgate }, 1e3, // 1s delay between tries ).catch(() => {})
if (data) updatePostThreadThreadgate(data)
queryClient.invalidateQueries({ queryKey: [threadgateRecordQueryKeyRoot], }) queryClient.invalidateQueries({ queryKey: [threadgateViewQueryKeyRoot], }) }, })}
export function useToggleReplyVisibilityMutation() { const agent = useAgent() const queryClient = useQueryClient() const hiddenReplies = useThreadgateHiddenReplyUrisAPI()
return useMutation({ mutationFn: async ({ postUri, replyUri, action, }: { postUri: string replyUri: string action: 'hide' | 'show' }) => { if (action === 'hide') { hiddenReplies.addHiddenReplyUri(replyUri) } else if (action === 'show') { hiddenReplies.removeHiddenReplyUri(replyUri) }
await upsertThreadgate({agent, postUri}, async prev => { if (prev) { if (action === 'hide') { return mergeThreadgateRecords(prev, { hiddenReplies: [replyUri], }) } else if (action === 'show') { return { ...prev, hiddenReplies: prev.hiddenReplies?.filter(uri => uri !== replyUri) || [], } } } else { if (action === 'hide') { return createThreadgateRecord({ post: postUri, hiddenReplies: [replyUri], }) } } }) }, onSuccess() { queryClient.invalidateQueries({ queryKey: [threadgateRecordQueryKeyRoot], }) }, onError(_, {replyUri, action}) { if (action === 'hide') { hiddenReplies.removeHiddenReplyUri(replyUri) } else if (action === 'show') { hiddenReplies.addHiddenReplyUri(replyUri) } }, })}
export class MaxHiddenRepliesError extends Error { constructor(message?: string) { super(message || 'Maximum number of hidden replies reached') this.name = 'MaxHiddenRepliesError' }}
export class InvalidInteractionSettingsError extends Error { constructor(message?: string) { super(message || 'Invalid interaction settings') this.name = 'InvalidInteractionSettingsError' }}
export function validateThreadgateRecordOrThrow( record: AppBskyFeedThreadgate.Record,) { const result = AppBskyFeedThreadgate.validateRecord(record)
if (result.success) { if ((result.value.hiddenReplies?.length ?? 0) > MAX_HIDDEN_REPLIES) { throw new MaxHiddenRepliesError() } } else { throw new InvalidInteractionSettingsError() }}