Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755import {useCallback} from 'react'import { type AppBskyActorDefs, type AppBskyActorGetProfile, type AppBskyActorGetProfiles, type AppBskyActorProfile, type AppBskyGraphGetFollows, AtUri, type BskyAgent, type ComAtprotoRepoUploadBlob, type Un$Typed,} from '@atproto/api'import { type InfiniteData, keepPreviousData, type QueryClient, useMutation, useQuery, useQueryClient,} from '@tanstack/react-query'
import {uploadBlob} from '#/lib/api'import {until} from '#/lib/async/until'import {PUBLIC_BSKY_API} from '#/lib/constants'import {useToggleMutationQueue} from '#/lib/hooks/useToggleMutationQueue'import {updateProfileShadow} from '#/state/cache/profile-shadow'import {type Shadow} from '#/state/cache/types'import {type ImageMeta} from '#/state/gallery'import {STALE} from '#/state/queries'import {resetProfilePostsQueries} from '#/state/queries/post-feed'import {RQKEY as PROFILE_FOLLOWS_RQKEY} from '#/state/queries/profile-follows'import {classifyProfileError} from '#/state/queries/profile-status'import { unstableCacheProfileView, useUnstableProfileViewCache,} from '#/state/queries/unstable-profile-cache'import {useUpdateProfileVerificationCache} from '#/state/queries/verification/useUpdateProfileVerificationCache'import {useAgent, useSession} from '#/state/session'import * as userActionHistory from '#/state/userActionHistory'import {useAnalytics} from '#/analytics'import {type Metrics, toClout} from '#/analytics/metrics'import {ALT_PROXY_DID} from '#/env'import type * as bsky from '#/types/bsky'import { ProgressGuideAction, useProgressGuideControls,} from '../shell/progress-guide'import {RQKEY_ROOT as RQKEY_LIST_CONVOS} from './messages/list-conversations'import {RQKEY as RQKEY_MY_BLOCKED} from './my-blocked-accounts'import {RQKEY as RQKEY_MY_MUTED} from './my-muted-accounts'
export * from '#/state/queries/unstable-profile-cache'/** * @deprecated use {@link unstableCacheProfileView} instead */export const precacheProfile = unstableCacheProfileView
const RQKEY_ROOT = 'profile'export const RQKEY = (did: string) => [RQKEY_ROOT, did]
export const profilesQueryKeyRoot = 'profiles'export const profilesQueryKey = (handles: string[]) => [ profilesQueryKeyRoot, handles,]
export function useProfileQuery({ did, staleTime = STALE.SECONDS.FIFTEEN,}: { did: string | undefined staleTime?: number}) { const agent = useAgent() const {getUnstableProfile} = useUnstableProfileViewCache() return useQuery<AppBskyActorDefs.ProfileViewDetailed>({ // WARNING // this staleTime is load-bearing // if you remove it, the UI infinite-loops // -prf staleTime, refetchOnWindowFocus: true, queryKey: RQKEY(did ?? ''), queryFn: async () => { const profilePromise = agent.getProfile({actor: did ?? ''}) const bskyPromise = agent.app.bsky.actor .getProfile({actor: did ?? ''}, {headers: BSKY_PROXY_HEADER}) .catch(() => null)
const [profileRes, bskyRes] = await Promise.all([ profilePromise, bskyPromise, ]) const profile = profileRes.data
// Prefer Bluesky's counts and known followers to avoid flickering // between our appview's counts and Bluesky's if (bskyRes?.data) { profile.followersCount = bskyRes.data.followersCount ?? profile.followersCount profile.followsCount = bskyRes.data.followsCount ?? profile.followsCount profile.postsCount = bskyRes.data.postsCount ?? profile.postsCount if (bskyRes.data.viewer?.knownFollowers) { profile.viewer = { ...profile.viewer, knownFollowers: bskyRes.data.viewer.knownFollowers, } } }
return profile }, placeholderData: () => { if (!did) return return getUnstableProfile(did) as AppBskyActorDefs.ProfileViewDetailed }, enabled: !!did, retry: (failureCount, error) => classifyProfileError(error) === 'unknown' && failureCount < 1, })}
export function usePublicProfileQuery({did}: {did: string | undefined}) { return useQuery<{ followersCount?: number followsCount?: number postsCount?: number } | null>({ staleTime: STALE.MINUTES.FIVE, queryKey: ['public-profile', did ?? ''], queryFn: async () => { const res = await fetch( `${PUBLIC_BSKY_API}/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(did ?? '')}`, ) if (!res.ok) return null return res.json() }, enabled: !!did, })}
const BSKY_PROXY_HEADER = { 'atproto-proxy': `${ALT_PROXY_DID}#bsky_appview`,}
/** * Fetches a profile from Bluesky's appview via the PDS proxy. * Returns null if the user is suspended on Bluesky or the request fails. * Used to get accurate follower/following counts and known followers data. */export function useBskyProfileQuery({did}: {did: string | undefined}) { const agent = useAgent() return useQuery<AppBskyActorDefs.ProfileViewDetailed | null>({ staleTime: STALE.MINUTES.FIVE, queryKey: ['bsky-profile', did ?? ''], queryFn: async () => { try { const res = await agent.app.bsky.actor.getProfile( {actor: did ?? ''}, {headers: BSKY_PROXY_HEADER}, ) return res.data } catch { return null } }, enabled: !!did, })}
export function useProfilesQuery({ handles, maintainData, enabled,}: { handles: string[] maintainData?: boolean enabled?: boolean}) { const agent = useAgent() return useQuery({ staleTime: STALE.MINUTES.FIVE, queryKey: profilesQueryKey(handles), queryFn: async () => { const res = await agent.getProfiles({actors: handles}) return res.data }, placeholderData: maintainData ? keepPreviousData : undefined, enabled, })}
export function usePrefetchProfileQuery() { const agent = useAgent() const queryClient = useQueryClient() const prefetchProfileQuery = useCallback( async (did: string) => { await queryClient.prefetchQuery({ staleTime: STALE.SECONDS.THIRTY, queryKey: RQKEY(did), queryFn: async () => { const profilePromise = agent.getProfile({actor: did || ''}) const bskyPromise = agent.app.bsky.actor .getProfile({actor: did || ''}, {headers: BSKY_PROXY_HEADER}) .catch(() => null)
const [profileRes, bskyRes] = await Promise.all([ profilePromise, bskyPromise, ]) const profile = profileRes.data
if (bskyRes?.data) { profile.followersCount = bskyRes.data.followersCount ?? profile.followersCount profile.followsCount = bskyRes.data.followsCount ?? profile.followsCount profile.postsCount = bskyRes.data.postsCount ?? profile.postsCount if (bskyRes.data.viewer?.knownFollowers) { profile.viewer = { ...profile.viewer, knownFollowers: bskyRes.data.viewer.knownFollowers, } } }
return profile }, }) }, [queryClient, agent], ) return prefetchProfileQuery}
interface ProfileUpdateParams { profile: AppBskyActorDefs.ProfileViewDetailed updates: | Un$Typed<AppBskyActorProfile.Record> | (( existing: Un$Typed<AppBskyActorProfile.Record>, ) => Un$Typed<AppBskyActorProfile.Record>) newUserAvatar?: ImageMeta | undefined | null newUserBanner?: ImageMeta | undefined | null checkCommitted?: (res: AppBskyActorGetProfile.Response) => boolean}export function useProfileUpdateMutation() { const queryClient = useQueryClient() const agent = useAgent() const updateProfileVerificationCache = useUpdateProfileVerificationCache() return useMutation<void, Error, ProfileUpdateParams>({ mutationFn: async ({ profile, updates, newUserAvatar, newUserBanner, checkCommitted, }) => { let newUserAvatarPromise: | Promise<ComAtprotoRepoUploadBlob.Response> | undefined if (newUserAvatar) { newUserAvatarPromise = uploadBlob( agent, newUserAvatar.path, newUserAvatar.mime, ) } let newUserBannerPromise: | Promise<ComAtprotoRepoUploadBlob.Response> | undefined if (newUserBanner) { newUserBannerPromise = uploadBlob( agent, newUserBanner.path, newUserBanner.mime, ) } await agent.upsertProfile(async existing => { let next: Un$Typed<AppBskyActorProfile.Record> = existing || {} if (typeof updates === 'function') { next = updates(next) } else { next.displayName = updates.displayName next.description = updates.description if ('pronouns' in updates) { next.pronouns = updates.pronouns } if ('pinnedPost' in updates) { next.pinnedPost = updates.pinnedPost } } if (newUserAvatarPromise) { const res = await newUserAvatarPromise next.avatar = res.data.blob } else if (newUserAvatar === null) { next.avatar = undefined } if (newUserBannerPromise) { const res = await newUserBannerPromise next.banner = res.data.blob } else if (newUserBanner === null) { next.banner = undefined } return next }) await whenAppViewReady( agent, profile.did, checkCommitted || (res => { if (typeof newUserAvatar !== 'undefined') { if (newUserAvatar === null && res.data.avatar) { // url hasnt cleared yet return false } else if (res.data.avatar === profile.avatar) { // url hasnt changed yet return false } } if (typeof newUserBanner !== 'undefined') { if (newUserBanner === null && res.data.banner) { // url hasnt cleared yet return false } else if (res.data.banner === profile.banner) { // url hasnt changed yet return false } } if (typeof updates === 'function') { return true } return ( res.data.displayName === updates.displayName && res.data.description === updates.description && res.data.pronouns === updates.pronouns ) }), ) }, async onSuccess(_, variables) { // invalidate cache queryClient.invalidateQueries({ queryKey: RQKEY(variables.profile.did), }) queryClient.invalidateQueries({ queryKey: [profilesQueryKeyRoot, [variables.profile.did]], }) await updateProfileVerificationCache({profile: variables.profile}) }, })}
export function useProfileFollowMutationQueue( profile: Shadow<bsky.profile.AnyProfileView>, logContext: Metrics['profile:follow']['logContext'], position?: number, contextProfileDid?: string,) { const agent = useAgent() const queryClient = useQueryClient() const {currentAccount} = useSession() const did = profile.did const initialFollowingUri = profile.viewer?.following const followMutation = useProfileFollowMutation( logContext, profile, position, contextProfileDid, ) const unfollowMutation = useProfileUnfollowMutation(logContext)
const queueToggle = useToggleMutationQueue({ initialState: initialFollowingUri, runMutation: async (prevFollowingUri, shouldFollow) => { if (shouldFollow) { const {uri} = await followMutation.mutateAsync({ did, }) userActionHistory.follow([did]) return uri } else { if (prevFollowingUri) { await unfollowMutation.mutateAsync({ did, followUri: prevFollowingUri, }) userActionHistory.unfollow([did]) } return undefined } }, onSuccess(finalFollowingUri) { // finalize updateProfileShadow(queryClient, did, { followingUri: finalFollowingUri, })
// Optimistically update profile follows cache for avatar displays if (currentAccount?.did) { type FollowsQueryData = InfiniteData<AppBskyGraphGetFollows.OutputSchema> queryClient.setQueryData<FollowsQueryData>( PROFILE_FOLLOWS_RQKEY(currentAccount.did), old => { if (!old?.pages?.[0]) return old if (finalFollowingUri) { // Add the followed profile to the beginning const alreadyExists = old.pages[0].follows.some( f => f.did === profile.did, ) if (alreadyExists) return old return { ...old, pages: [ { ...old.pages[0], follows: [ profile as AppBskyActorDefs.ProfileView, ...old.pages[0].follows, ], }, ...old.pages.slice(1), ], } } else { // Remove the unfollowed profile return { ...old, pages: old.pages.map(page => ({ ...page, follows: page.follows.filter(f => f.did !== profile.did), })), } } }, ) }
if (finalFollowingUri) { agent.app.bsky.graph .getSuggestedFollowsByActor({ actor: did, }) .then(res => { const dids = res.data.suggestions .filter(a => !a.viewer?.following) .map(a => a.did) .slice(0, 8) userActionHistory.followSuggestion(dids) }) } }, })
const queueFollow = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { followingUri: 'pending', }) return queueToggle(true) }, [queryClient, did, queueToggle])
const queueUnfollow = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { followingUri: undefined, }) return queueToggle(false) }, [queryClient, did, queueToggle])
return [queueFollow, queueUnfollow]}
function useProfileFollowMutation( logContext: Metrics['profile:follow']['logContext'], profile: Shadow<bsky.profile.AnyProfileView>, position?: number, contextProfileDid?: string,) { const ax = useAnalytics() const {currentAccount} = useSession() const agent = useAgent() const queryClient = useQueryClient() const {captureAction} = useProgressGuideControls()
return useMutation<{uri: string; cid: string}, Error, {did: string}>({ mutationFn: async ({did}) => { let ownProfile: AppBskyActorDefs.ProfileViewDetailed | undefined if (currentAccount) { ownProfile = findProfileQueryData(queryClient, currentAccount.did) } captureAction(ProgressGuideAction.Follow) ax.metric('profile:follow', { logContext, didBecomeMutual: profile.viewer ? Boolean(profile.viewer.followedBy) : undefined, followeeClout: 'followersCount' in profile ? toClout(profile.followersCount) : undefined, followeeDid: did, followerClout: toClout(ownProfile?.followersCount), position, contextProfileDid, }) return await agent.follow(did) }, })}
function useProfileUnfollowMutation( logContext: Metrics['profile:unfollow']['logContext'],) { const ax = useAnalytics() const agent = useAgent() return useMutation<void, Error, {did: string; followUri: string}>({ mutationFn: async ({followUri}) => { ax.metric('profile:unfollow', {logContext}) return await agent.deleteFollow(followUri) }, })}
export function useProfileMuteMutationQueue( profile: Shadow<bsky.profile.AnyProfileView>,) { const queryClient = useQueryClient() const did = profile.did const initialMuted = profile.viewer?.muted const muteMutation = useProfileMuteMutation() const unmuteMutation = useProfileUnmuteMutation()
const queueToggle = useToggleMutationQueue({ initialState: initialMuted, runMutation: async (_prevMuted, shouldMute) => { if (shouldMute) { await muteMutation.mutateAsync({ did, }) return true } else { await unmuteMutation.mutateAsync({ did, }) return false } }, onSuccess(finalMuted) { // finalize updateProfileShadow(queryClient, did, {muted: finalMuted}) }, })
const queueMute = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { muted: true, }) return queueToggle(true) }, [queryClient, did, queueToggle])
const queueUnmute = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { muted: false, }) return queueToggle(false) }, [queryClient, did, queueToggle])
return [queueMute, queueUnmute]}
function useProfileMuteMutation() { const queryClient = useQueryClient() const agent = useAgent() return useMutation<void, Error, {did: string}>({ mutationFn: async ({did}) => { await agent.mute(did) }, onSuccess() { queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) }, })}
function useProfileUnmuteMutation() { const queryClient = useQueryClient() const agent = useAgent() return useMutation<void, Error, {did: string}>({ mutationFn: async ({did}) => { await agent.unmute(did) }, onSuccess() { queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) }, })}
export function useProfileBlockMutationQueue( profile: Shadow<bsky.profile.AnyProfileView>,) { const queryClient = useQueryClient() const did = profile.did const initialBlockingUri = profile.viewer?.blocking const blockMutation = useProfileBlockMutation() const unblockMutation = useProfileUnblockMutation()
const queueToggle = useToggleMutationQueue({ initialState: initialBlockingUri, runMutation: async (prevBlockUri, shouldFollow) => { if (shouldFollow) { const {uri} = await blockMutation.mutateAsync({ did, }) return uri } else { if (prevBlockUri) { await unblockMutation.mutateAsync({ did, blockUri: prevBlockUri, }) } return undefined } }, onSuccess(finalBlockingUri) { // finalize updateProfileShadow(queryClient, did, { blockingUri: finalBlockingUri, }) // The shadow only reaches components that read profiles through shadow // hooks. The convo list is also read raw (e.g. the unread badge's // calculateCount, getMessageInfo), and blocks emit no chat log event, // so without a refetch that data stays stale indefinitely. void queryClient.invalidateQueries({queryKey: [RQKEY_LIST_CONVOS]}) }, })
const queueBlock = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { blockingUri: 'pending', }) return queueToggle(true) }, [queryClient, did, queueToggle])
const queueUnblock = useCallback(() => { // optimistically update updateProfileShadow(queryClient, did, { blockingUri: undefined, }) return queueToggle(false) }, [queryClient, did, queueToggle])
return [queueBlock, queueUnblock]}
function useProfileBlockMutation() { const {currentAccount} = useSession() const agent = useAgent() const queryClient = useQueryClient() return useMutation<{uri: string; cid: string}, Error, {did: string}>({ mutationFn: async ({did}) => { if (!currentAccount) { throw new Error('Not signed in') } return await agent.app.bsky.graph.block.create( {repo: currentAccount.did}, {subject: did, createdAt: new Date().toISOString()}, ) }, onSuccess(_, {did}) { queryClient.invalidateQueries({queryKey: RQKEY_MY_BLOCKED()}) resetProfilePostsQueries(queryClient, did, 1000) }, })}
function useProfileUnblockMutation() { const {currentAccount} = useSession() const agent = useAgent() const queryClient = useQueryClient() return useMutation<void, Error, {did: string; blockUri: string}>({ mutationFn: async ({blockUri}) => { if (!currentAccount) { throw new Error('Not signed in') } const {rkey} = new AtUri(blockUri) await agent.app.bsky.graph.block.delete({ repo: currentAccount.did, rkey, }) }, onSuccess(_, {did}) { resetProfilePostsQueries(queryClient, did, 1000) }, })}
async function whenAppViewReady( agent: BskyAgent, actor: string, fn: (res: AppBskyActorGetProfile.Response) => boolean,) { await until( 5, // 5 tries 1e3, // 1s delay between tries fn, () => agent.app.bsky.actor.getProfile({actor}), )}
export function* findAllProfilesInQueryData( queryClient: QueryClient, did: string,): Generator<AppBskyActorDefs.ProfileViewDetailed, void> { const profileQueryDatas = queryClient.getQueriesData<AppBskyActorDefs.ProfileViewDetailed>({ queryKey: [RQKEY_ROOT], }) for (const [_queryKey, queryData] of profileQueryDatas) { if (!queryData) { continue } if (queryData.did === did) { yield queryData } } const profilesQueryDatas = queryClient.getQueriesData<AppBskyActorGetProfiles.OutputSchema>({ queryKey: [profilesQueryKeyRoot], }) for (const [_queryKey, queryData] of profilesQueryDatas) { if (!queryData) { continue } for (let profile of queryData.profiles) { if (profile.did === did) { yield profile } } }}
export function findProfileQueryData( queryClient: QueryClient, did: string,): AppBskyActorDefs.ProfileViewDetailed | undefined { return queryClient.getQueryData<AppBskyActorDefs.ProfileViewDetailed>( RQKEY(did), )}