diff options
Diffstat (limited to 'src')
74 files changed, 400 insertions, 438 deletions
diff --git a/src/components/ReportDialog/SubmitView.tsx b/src/components/ReportDialog/SubmitView.tsx index e921d102a..74ecf92e4 100644 --- a/src/components/ReportDialog/SubmitView.tsx +++ b/src/components/ReportDialog/SubmitView.tsx @@ -36,7 +36,7 @@ export function SubmitView({ }) { const t = useTheme() const {_} = useLingui() - const {getAgent} = useAgent() + const agent = useAgent() const [details, setDetails] = React.useState<string>('') const [submitting, setSubmitting] = React.useState<boolean>(false) const [selectedServices, setSelectedServices] = React.useState<string[]>([ @@ -62,7 +62,7 @@ export function SubmitView({ } const results = await Promise.all( selectedServices.map(did => - getAgent() + agent .withProxy('atproto_labeler', did) .createModerationReport(report) .then( @@ -92,7 +92,7 @@ export function SubmitView({ selectedServices, onSubmitComplete, setError, - getAgent, + agent, ]) return ( diff --git a/src/components/dms/ReportDialog.tsx b/src/components/dms/ReportDialog.tsx index 63e4cd79e..9c4ed2a0e 100644 --- a/src/components/dms/ReportDialog.tsx +++ b/src/components/dms/ReportDialog.tsx @@ -102,7 +102,7 @@ function SubmitStep({ const t = useTheme() const [details, setDetails] = useState('') const control = Dialog.useDialogContext() - const {getAgent} = useAgent() + const agent = useAgent() const { mutate: submit, @@ -124,7 +124,7 @@ function SubmitStep({ reason: details, } satisfies ComAtprotoModerationCreateReport.InputSchema - await getAgent().createModerationReport(report) + await agent.createModerationReport(report) } }, onSuccess: () => { diff --git a/src/components/hooks/useRichText.ts b/src/components/hooks/useRichText.ts index 4329638ea..caf6febc0 100644 --- a/src/components/hooks/useRichText.ts +++ b/src/components/hooks/useRichText.ts @@ -7,7 +7,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] { const [prevText, setPrevText] = React.useState(text) const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text})) const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null) - const {getAgent} = useAgent() + const agent = useAgent() if (text !== prevText) { setPrevText(text) setRawRT(new RichTextAPI({text})) @@ -19,7 +19,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] { async function resolveRTFacets() { // new each time const resolvedRT = new RichTextAPI({text}) - await resolvedRT.detectFacets(getAgent()) + await resolvedRT.detectFacets(agent) if (!ignore) { setResolvedRT(resolvedRT) } @@ -28,7 +28,7 @@ export function useRichText(text: string): [RichTextAPI, boolean] { return () => { ignore = true } - }, [text, getAgent]) + }, [text, agent]) const isResolving = resolvedRT === null return [resolvedRT ?? rawRT, isResolving] } diff --git a/src/components/moderation/LabelsOnMeDialog.tsx b/src/components/moderation/LabelsOnMeDialog.tsx index 2923981fd..7c76269ac 100644 --- a/src/components/moderation/LabelsOnMeDialog.tsx +++ b/src/components/moderation/LabelsOnMeDialog.tsx @@ -202,14 +202,14 @@ function AppealForm({ const {gtMobile} = useBreakpoints() const [details, setDetails] = React.useState('') const isAccountReport = 'did' in subject - const {getAgent} = useAgent() + const agent = useAgent() const {mutate, isPending} = useMutation({ mutationFn: async () => { const $type = !isAccountReport ? 'com.atproto.repo.strongRef' : 'com.atproto.admin.defs#repoRef' - await getAgent() + await agent .withProxy('atproto_labeler', label.src) .createModerationReport({ reasonType: ComAtprotoModerationDefs.REASONAPPEAL, diff --git a/src/lib/api/feed/author.ts b/src/lib/api/feed/author.ts index 85601d068..56eff1881 100644 --- a/src/lib/api/feed/author.ts +++ b/src/lib/api/feed/author.ts @@ -7,22 +7,22 @@ import { import {FeedAPI, FeedAPIResponse} from './types' export class AuthorFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent params: GetAuthorFeed.QueryParams constructor({ - getAgent, + agent, feedParams, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedParams: GetAuthorFeed.QueryParams }) { - this.getAgent = getAgent + this.agent = agent this.params = feedParams } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { - const res = await this.getAgent().getAuthorFeed({ + const res = await this.agent.getAuthorFeed({ ...this.params, limit: 1, }) @@ -36,7 +36,7 @@ export class AuthorFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise<FeedAPIResponse> { - const res = await this.getAgent().getAuthorFeed({ + const res = await this.agent.getAuthorFeed({ ...this.params, cursor, limit, diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index 87e45ceba..eb54dd29c 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -10,27 +10,27 @@ import {FeedAPI, FeedAPIResponse} from './types' import {createBskyTopicsHeader, isBlueskyOwnedFeed} from './utils' export class CustomFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent params: GetCustomFeed.QueryParams userInterests?: string constructor({ - getAgent, + agent, feedParams, userInterests, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedParams: GetCustomFeed.QueryParams userInterests?: string }) { - this.getAgent = getAgent + this.agent = agent this.params = feedParams this.userInterests = userInterests } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { const contentLangs = getContentLanguages().join(',') - const res = await this.getAgent().app.bsky.feed.getFeed( + const res = await this.agent.app.bsky.feed.getFeed( { ...this.params, limit: 1, @@ -48,11 +48,11 @@ export class CustomFeedAPI implements FeedAPI { limit: number }): Promise<FeedAPIResponse> { const contentLangs = getContentLanguages().join(',') - const agent = this.getAgent() + const agent = this.agent const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) const res = agent.session - ? await this.getAgent().app.bsky.feed.getFeed( + ? await this.agent.app.bsky.feed.getFeed( { ...this.params, cursor, diff --git a/src/lib/api/feed/following.ts b/src/lib/api/feed/following.ts index 36c376554..1004ccfb8 100644 --- a/src/lib/api/feed/following.ts +++ b/src/lib/api/feed/following.ts @@ -3,14 +3,14 @@ import {AppBskyFeedDefs, BskyAgent} from '@atproto/api' import {FeedAPI, FeedAPIResponse} from './types' export class FollowingFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent - constructor({getAgent}: {getAgent: () => BskyAgent}) { - this.getAgent = getAgent + constructor({agent}: {agent: BskyAgent}) { + this.agent = agent } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { - const res = await this.getAgent().getTimeline({ + const res = await this.agent.getTimeline({ limit: 1, }) return res.data.feed[0] @@ -23,7 +23,7 @@ export class FollowingFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise<FeedAPIResponse> { - const res = await this.getAgent().getTimeline({ + const res = await this.agent.getTimeline({ cursor, limit, }) diff --git a/src/lib/api/feed/home.ts b/src/lib/api/feed/home.ts index 270f3aacb..e6bc45bea 100644 --- a/src/lib/api/feed/home.ts +++ b/src/lib/api/feed/home.ts @@ -27,7 +27,7 @@ export const FALLBACK_MARKER_POST: AppBskyFeedDefs.FeedViewPost = { } export class HomeFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent following: FollowingFeedAPI discover: CustomFeedAPI usingDiscover = false @@ -36,24 +36,24 @@ export class HomeFeedAPI implements FeedAPI { constructor({ userInterests, - getAgent, + agent, }: { userInterests?: string - getAgent: () => BskyAgent + agent: BskyAgent }) { - this.getAgent = getAgent - this.following = new FollowingFeedAPI({getAgent}) + this.agent = agent + this.following = new FollowingFeedAPI({agent}) this.discover = new CustomFeedAPI({ - getAgent, + agent, feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')}, }) this.userInterests = userInterests } reset() { - this.following = new FollowingFeedAPI({getAgent: this.getAgent}) + this.following = new FollowingFeedAPI({agent: this.agent}) this.discover = new CustomFeedAPI({ - getAgent: this.getAgent, + agent: this.agent, feedParams: {feed: PROD_DEFAULT_FEED('whats-hot')}, userInterests: this.userInterests, }) diff --git a/src/lib/api/feed/likes.ts b/src/lib/api/feed/likes.ts index 1729ee05c..a4e84d8f1 100644 --- a/src/lib/api/feed/likes.ts +++ b/src/lib/api/feed/likes.ts @@ -7,22 +7,22 @@ import { import {FeedAPI, FeedAPIResponse} from './types' export class LikesFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent params: GetActorLikes.QueryParams constructor({ - getAgent, + agent, feedParams, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedParams: GetActorLikes.QueryParams }) { - this.getAgent = getAgent + this.agent = agent this.params = feedParams } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { - const res = await this.getAgent().getActorLikes({ + const res = await this.agent.getActorLikes({ ...this.params, limit: 1, }) @@ -36,7 +36,7 @@ export class LikesFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise<FeedAPIResponse> { - const res = await this.getAgent().getActorLikes({ + const res = await this.agent.getActorLikes({ ...this.params, cursor, limit, diff --git a/src/lib/api/feed/list.ts b/src/lib/api/feed/list.ts index 004685b99..9744e3d4c 100644 --- a/src/lib/api/feed/list.ts +++ b/src/lib/api/feed/list.ts @@ -7,22 +7,22 @@ import { import {FeedAPI, FeedAPIResponse} from './types' export class ListFeedAPI implements FeedAPI { - getAgent: () => BskyAgent + agent: BskyAgent params: GetListFeed.QueryParams constructor({ - getAgent, + agent, feedParams, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedParams: GetListFeed.QueryParams }) { - this.getAgent = getAgent + this.agent = agent this.params = feedParams } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { - const res = await this.getAgent().app.bsky.feed.getListFeed({ + const res = await this.agent.app.bsky.feed.getListFeed({ ...this.params, limit: 1, }) @@ -36,7 +36,7 @@ export class ListFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise<FeedAPIResponse> { - const res = await this.getAgent().app.bsky.feed.getListFeed({ + const res = await this.agent.app.bsky.feed.getListFeed({ ...this.params, cursor, limit, diff --git a/src/lib/api/feed/merge.ts b/src/lib/api/feed/merge.ts index b7ac8bce1..f551f5e4c 100644 --- a/src/lib/api/feed/merge.ts +++ b/src/lib/api/feed/merge.ts @@ -16,7 +16,7 @@ const POST_AGE_CUTOFF = 60e3 * 60 * 24 // 24hours export class MergeFeedAPI implements FeedAPI { userInterests?: string - getAgent: () => BskyAgent + agent: BskyAgent params: FeedParams feedTuners: FeedTunerFn[] following: MergeFeedSource_Following @@ -26,29 +26,29 @@ export class MergeFeedAPI implements FeedAPI { sampleCursor = 0 constructor({ - getAgent, + agent, feedParams, feedTuners, userInterests, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedParams: FeedParams feedTuners: FeedTunerFn[] userInterests?: string }) { - this.getAgent = getAgent + this.agent = agent this.params = feedParams this.feedTuners = feedTuners this.userInterests = userInterests this.following = new MergeFeedSource_Following({ - getAgent: this.getAgent, + agent: this.agent, feedTuners: this.feedTuners, }) } reset() { this.following = new MergeFeedSource_Following({ - getAgent: this.getAgent, + agent: this.agent, feedTuners: this.feedTuners, }) this.customFeeds = [] @@ -60,7 +60,7 @@ export class MergeFeedAPI implements FeedAPI { this.params.mergeFeedSources.map( feedUri => new MergeFeedSource_Custom({ - getAgent: this.getAgent, + agent: this.agent, feedUri, feedTuners: this.feedTuners, userInterests: this.userInterests, @@ -73,7 +73,7 @@ export class MergeFeedAPI implements FeedAPI { } async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> { - const res = await this.getAgent().getTimeline({ + const res = await this.agent.getTimeline({ limit: 1, }) return res.data.feed[0] @@ -167,7 +167,7 @@ export class MergeFeedAPI implements FeedAPI { } class MergeFeedSource { - getAgent: () => BskyAgent + agent: BskyAgent feedTuners: FeedTunerFn[] sourceInfo: ReasonFeedSource | undefined cursor: string | undefined = undefined @@ -175,13 +175,13 @@ class MergeFeedSource { hasMore = true constructor({ - getAgent, + agent, feedTuners, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedTuners: FeedTunerFn[] }) { - this.getAgent = getAgent + this.agent = agent this.feedTuners = feedTuners } @@ -245,7 +245,7 @@ class MergeFeedSource_Following extends MergeFeedSource { cursor: string | undefined, limit: number, ): Promise<AppBskyFeedGetTimeline.Response> { - const res = await this.getAgent().getTimeline({cursor, limit}) + const res = await this.agent.getTimeline({cursor, limit}) // run the tuner pre-emptively to ensure better mixing const slices = this.tuner.tune(res.data.feed, { dryRun: false, @@ -257,27 +257,27 @@ class MergeFeedSource_Following extends MergeFeedSource { } class MergeFeedSource_Custom extends MergeFeedSource { - getAgent: () => BskyAgent + agent: BskyAgent minDate: Date feedUri: string userInterests?: string constructor({ - getAgent, + agent, feedUri, feedTuners, userInterests, }: { - getAgent: () => BskyAgent + agent: BskyAgent feedUri: string feedTuners: FeedTunerFn[] userInterests?: string }) { super({ - getAgent, + agent, feedTuners, }) - this.getAgent = getAgent + this.agent = agent this.feedUri = feedUri this.userInterests = userInterests this.sourceInfo = { @@ -295,7 +295,7 @@ class MergeFeedSource_Custom extends MergeFeedSource { try { const contentLangs = getContentLanguages().join(',') const isBlueskyOwned = isBlueskyOwnedFeed(this.feedUri) - const res = await this.getAgent().app.bsky.feed.getFeed( + const res = await this.agent.app.bsky.feed.getFeed( { cursor, limit, diff --git a/src/lib/notifications/notifications.ts b/src/lib/notifications/notifications.ts index f9fbdb8bf..f0667b0cc 100644 --- a/src/lib/notifications/notifications.ts +++ b/src/lib/notifications/notifications.ts @@ -14,12 +14,12 @@ const SERVICE_DID = (serviceUrl?: string) => : 'did:web:api.bsky.app' async function registerPushToken( - getAgent: () => BskyAgent, + agent: BskyAgent, account: SessionAccount, token: Notifications.DevicePushToken, ) { try { - await getAgent().api.app.bsky.notification.registerPush({ + await agent.api.app.bsky.notification.registerPush({ serviceDid: SERVICE_DID(account.service), platform: devicePlatform, token: token.data, @@ -47,7 +47,7 @@ async function getPushToken(skipPermissionCheck = false) { } export function useNotificationsRegistration() { - const {getAgent} = useAgent() + const agent = useAgent() const {currentAccount} = useSession() React.useEffect(() => { @@ -60,13 +60,13 @@ export function useNotificationsRegistration() { // According to the Expo docs, there is a chance that the token will change while the app is open in some rare // cases. This will fire `registerPushToken` whenever that happens. const subscription = Notifications.addPushTokenListener(async newToken => { - registerPushToken(getAgent, currentAccount, newToken) + registerPushToken(agent, currentAccount, newToken) }) return () => { subscription.remove() } - }, [currentAccount, getAgent]) + }, [currentAccount, agent]) } export function useRequestNotificationsPermission() { diff --git a/src/screens/Deactivated.tsx b/src/screens/Deactivated.tsx index 08a2232df..c9e9f9525 100644 --- a/src/screens/Deactivated.tsx +++ b/src/screens/Deactivated.tsx @@ -24,7 +24,7 @@ export function Deactivated() { const {gtMobile} = useBreakpoints() const onboardingDispatch = useOnboardingDispatch() const {logout} = useSessionApi() - const {getAgent} = useAgent() + const agent = useAgent() const [isProcessing, setProcessing] = React.useState(false) const [estimatedTime, setEstimatedTime] = React.useState<string | undefined>( @@ -37,11 +37,11 @@ export function Deactivated() { const checkStatus = React.useCallback(async () => { setProcessing(true) try { - const res = await getAgent().com.atproto.temp.checkSignupQueue() + const res = await agent.com.atproto.temp.checkSignupQueue() if (res.data.activated) { // ready to go, exchange the access token for a usable one and kick off onboarding - await getAgent().refreshSession() - if (!isSessionDeactivated(getAgent().session?.accessJwt)) { + await agent.refreshSession() + if (!isSessionDeactivated(agent.session?.accessJwt)) { onboardingDispatch({type: 'start'}) } } else { @@ -61,7 +61,7 @@ export function Deactivated() { setEstimatedTime, setPlaceInQueue, onboardingDispatch, - getAgent, + agent, ]) React.useEffect(() => { diff --git a/src/screens/Messages/Conversation/ChatDisabled.tsx b/src/screens/Messages/Conversation/ChatDisabled.tsx index 6665dd171..5c6e61586 100644 --- a/src/screens/Messages/Conversation/ChatDisabled.tsx +++ b/src/screens/Messages/Conversation/ChatDisabled.tsx @@ -66,14 +66,14 @@ function DialogInner() { const control = Dialog.useDialogContext() const [details, setDetails] = useState('') const {gtMobile} = useBreakpoints() - const {getAgent} = useAgent() + const agent = useAgent() const {currentAccount} = useSession() const {mutate, isPending} = useMutation({ mutationFn: async () => { if (!currentAccount) throw new Error('No current account, should be unreachable') - await getAgent().createModerationReport({ + await agent.createModerationReport({ reasonType: ComAtprotoModerationDefs.REASONAPPEAL, subject: { $type: 'com.atproto.admin.defs#repoRef', diff --git a/src/screens/Messages/Conversation/MessagesList.tsx b/src/screens/Messages/Conversation/MessagesList.tsx index a03d6bc03..bee7f6cd8 100644 --- a/src/screens/Messages/Conversation/MessagesList.tsx +++ b/src/screens/Messages/Conversation/MessagesList.tsx @@ -79,7 +79,7 @@ export function MessagesList({ footer?: React.ReactNode }) { const convoState = useConvoActive() - const {getAgent} = useAgent() + const agent = useAgent() const flatListRef = useAnimatedRef<FlatList>() @@ -265,7 +265,7 @@ export function MessagesList({ const onSendMessage = useCallback( async (text: string) => { let rt = new RichText({text}, {cleanNewlines: true}) - await rt.detectFacets(getAgent()) + await rt.detectFacets(agent) rt = shortenLinks(rt) // filter out any mention facets that didn't map to a user @@ -288,7 +288,7 @@ export function MessagesList({ facets: rt.facets, }) }, - [convoState, getAgent, hasScrolled, setHasScrolled], + [convoState, agent, hasScrolled, setHasScrolled], ) // -- List layout changes (opening emoji keyboard, etc.) diff --git a/src/screens/Onboarding/StepFinished.tsx b/src/screens/Onboarding/StepFinished.tsx index 855e12ed0..9658cfe15 100644 --- a/src/screens/Onboarding/StepFinished.tsx +++ b/src/screens/Onboarding/StepFinished.tsx @@ -47,7 +47,7 @@ export function StepFinished() { const [saving, setSaving] = React.useState(false) const {mutateAsync: overwriteSavedFeeds} = useOverwriteSavedFeedsMutation() const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() const gate = useGate() const finishOnboarding = React.useCallback(async () => { @@ -70,12 +70,12 @@ export function StepFinished() { try { await Promise.all([ bulkWriteFollows( - getAgent, + agent, suggestedAccountsStepResults.accountDids.concat(BSKY_APP_ACCOUNT_DID), ), // these must be serial (async () => { - await getAgent().setInterestsPref({tags: selectedInterests}) + await agent.setInterestsPref({tags: selectedInterests}) /* * In the reduced onboading experiment, we'll rely on the default @@ -98,7 +98,7 @@ export function StepFinished() { * (mimics old behavior) */ if ( - IS_PROD_SERVICE(getAgent().service.toString()) && + IS_PROD_SERVICE(agent.service.toString()) && !otherFeeds.length ) { otherFeeds.push({ @@ -124,8 +124,8 @@ export function StepFinished() { const {imageUri, imageMime} = profileStepResults if (imageUri && imageMime) { - const blobPromise = uploadBlob(getAgent(), imageUri, imageMime) - await getAgent().upsertProfile(async existing => { + const blobPromise = uploadBlob(agent, imageUri, imageMime) + await agent.upsertProfile(async existing => { existing = existing ?? {} const res = await blobPromise if (res.data.blob) { @@ -156,7 +156,7 @@ export function StepFinished() { queryKey: preferencesQueryKey, }), queryClient.invalidateQueries({ - queryKey: profileRQKey(getAgent().session?.did ?? ''), + queryKey: profileRQKey(agent.session?.did ?? ''), }), ]).catch(e => { logger.error(e) @@ -176,7 +176,7 @@ export function StepFinished() { setSaving, overwriteSavedFeeds, track, - getAgent, + agent, gate, queryClient, ]) diff --git a/src/screens/Onboarding/StepInterests/index.tsx b/src/screens/Onboarding/StepInterests/index.tsx index d95445d79..2589e66c2 100644 --- a/src/screens/Onboarding/StepInterests/index.tsx +++ b/src/screens/Onboarding/StepInterests/index.tsx @@ -43,13 +43,12 @@ export function StepInterests() { state.interestsStepResults.selectedInterests.map(i => i), ) const onboardDispatch = useOnboardingDispatch() - const {getAgent} = useAgent() + const agent = useAgent() const {isLoading, isError, error, data, refetch, isFetching} = useQuery({ queryKey: ['interests'], queryFn: async () => { try { - const {data} = - await getAgent().app.bsky.unspecced.getTaggedSuggestions() + const {data} = await agent.app.bsky.unspecced.getTaggedSuggestions() return data.suggestions.reduce( (agg, s) => { const {tag, subject, subjectType} = s diff --git a/src/screens/Onboarding/util.ts b/src/screens/Onboarding/util.ts index fde4316e9..417417707 100644 --- a/src/screens/Onboarding/util.ts +++ b/src/screens/Onboarding/util.ts @@ -66,11 +66,8 @@ export function aggregateInterestItems( return Array.from(new Set(results)).slice(0, 20) } -export async function bulkWriteFollows( - getAgent: () => BskyAgent, - dids: string[], -) { - const session = getAgent().session +export async function bulkWriteFollows(agent: BskyAgent, dids: string[]) { + const session = agent.session if (!session) { throw new Error(`bulkWriteFollows failed: no session`) @@ -89,19 +86,15 @@ export async function bulkWriteFollows( value: r, })) - await getAgent().com.atproto.repo.applyWrites({ + await agent.com.atproto.repo.applyWrites({ repo: session.did, writes: followWrites, }) - await whenFollowsIndexed( - getAgent, - session.did, - res => !!res.data.follows.length, - ) + await whenFollowsIndexed(agent, session.did, res => !!res.data.follows.length) } async function whenFollowsIndexed( - getAgent: () => BskyAgent, + agent: BskyAgent, actor: string, fn: (res: AppBskyGraphGetFollows.Response) => boolean, ) { @@ -110,7 +103,7 @@ async function whenFollowsIndexed( 1e3, // 1s delay between tries fn, () => - getAgent().app.bsky.graph.getFollows({ + agent.app.bsky.graph.getFollows({ actor, limit: 1, }), diff --git a/src/screens/Signup/index.tsx b/src/screens/Signup/index.tsx index 3d8b505b9..2cc1bcab0 100644 --- a/src/screens/Signup/index.tsx +++ b/src/screens/Signup/index.tsx @@ -36,7 +36,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) { const [state, dispatch] = React.useReducer(reducer, initialState) const submit = useSubmitSignup({state, dispatch}) const {gtMobile} = useBreakpoints() - const {getAgent} = useAgent() + const agent = useAgent() const { data: serviceInfo, @@ -77,7 +77,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) { try { dispatch({type: 'setIsLoading', value: true}) - const res = await getAgent().resolveHandle({ + const res = await agent.resolveHandle({ handle: createFullHandle(state.handle, state.userDomain), }) @@ -115,7 +115,7 @@ export function Signup({onPressBack}: {onPressBack: () => void}) { state.serviceDescription?.phoneVerificationRequired, state.userDomain, submit, - getAgent, + agent, ]) const onBackPress = React.useCallback(() => { diff --git a/src/state/feed-feedback.tsx b/src/state/feed-feedback.tsx index 5bfc77d0a..64bdd4b89 100644 --- a/src/state/feed-feedback.tsx +++ b/src/state/feed-feedback.tsx @@ -25,7 +25,7 @@ const stateContext = React.createContext<StateContext>({ }) export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) { - const {getAgent} = useAgent() + const agent = useAgent() const enabled = isDiscoverFeed(feed) && hasSession const queue = React.useRef<Set<string>>(new Set()) const history = React.useRef< @@ -35,7 +35,7 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) { >(new WeakSet()) const sendToFeedNoDelay = React.useCallback(() => { - const proxyAgent = getAgent().withProxy( + const proxyAgent = agent.withProxy( // @ts-ignore TODO need to update withProxy() to support this key -prf 'bsky_fg', // TODO when we start sending to other feeds, we need to grab their DID -prf @@ -50,7 +50,7 @@ export function useFeedFeedback(feed: FeedDescriptor, hasSession: boolean) { .catch((e: any) => { logger.warn('Failed to send feed interactions', {error: e}) }) - }, [getAgent]) + }, [agent]) const sendToFeed = React.useMemo( () => diff --git a/src/state/messages/convo/index.tsx b/src/state/messages/convo/index.tsx index 7ba337e45..78c513909 100644 --- a/src/state/messages/convo/index.tsx +++ b/src/state/messages/convo/index.tsx @@ -58,13 +58,13 @@ export function ConvoProvider({ convoId, }: Pick<ConvoParams, 'convoId'> & {children: React.ReactNode}) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() const events = useMessagesEventBus() const [convo] = useState( () => new Convo({ convoId, - agent: getAgent(), + agent, events, }), ) diff --git a/src/state/messages/events/index.tsx b/src/state/messages/events/index.tsx index d972c8c6a..b3321df64 100644 --- a/src/state/messages/events/index.tsx +++ b/src/state/messages/events/index.tsx @@ -43,11 +43,11 @@ export function MessagesEventBusProviderInner({ }: { children: React.ReactNode }) { - const {getAgent} = useAgent() + const agent = useAgent() const [bus] = React.useState( () => new MessagesEventBus({ - agent: getAgent(), + agent, }), ) diff --git a/src/state/queries/actor-autocomplete.ts b/src/state/queries/actor-autocomplete.ts index 17b00dc26..7e997ea01 100644 --- a/src/state/queries/actor-autocomplete.ts +++ b/src/state/queries/actor-autocomplete.ts @@ -23,7 +23,7 @@ export function useActorAutocompleteQuery( limit?: number, ) { const moderationOpts = useModerationOpts() - const {getAgent} = useAgent() + const agent = useAgent() prefix = prefix.toLowerCase().trim() if (prefix.endsWith('.')) { @@ -36,7 +36,7 @@ export function useActorAutocompleteQuery( queryKey: RQKEY(prefix || ''), async queryFn() { const res = prefix - ? await getAgent().searchActorsTypeahead({ + ? await agent.searchActorsTypeahead({ q: prefix, limit: limit || 8, }) @@ -57,7 +57,7 @@ export type ActorAutocompleteFn = ReturnType<typeof useActorAutocompleteFn> export function useActorAutocompleteFn() { const queryClient = useQueryClient() const moderationOpts = useModerationOpts() - const {getAgent} = useAgent() + const agent = useAgent() return React.useCallback( async ({query, limit = 8}: {query: string; limit?: number}) => { @@ -69,7 +69,7 @@ export function useActorAutocompleteFn() { staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(query || ''), queryFn: () => - getAgent().searchActorsTypeahead({ + agent.searchActorsTypeahead({ q: query, limit, }), @@ -86,7 +86,7 @@ export function useActorAutocompleteFn() { moderationOpts || DEFAULT_MOD_OPTS, ) }, - [queryClient, moderationOpts, getAgent], + [queryClient, moderationOpts, agent], ) } diff --git a/src/state/queries/actor-search.ts b/src/state/queries/actor-search.ts index e50c68aac..1e301a1ba 100644 --- a/src/state/queries/actor-search.ts +++ b/src/state/queries/actor-search.ts @@ -14,12 +14,12 @@ export function useActorSearch({ query: string enabled?: boolean }) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyActorDefs.ProfileView[]>({ staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(query || ''), async queryFn() { - const res = await getAgent().searchActors({ + const res = await agent.searchActors({ q: query, }) return res.data.actors diff --git a/src/state/queries/app-passwords.ts b/src/state/queries/app-passwords.ts index 33009a3a4..bbf2dea97 100644 --- a/src/state/queries/app-passwords.ts +++ b/src/state/queries/app-passwords.ts @@ -8,12 +8,12 @@ const RQKEY_ROOT = 'app-passwords' export const RQKEY = () => [RQKEY_ROOT] export function useAppPasswordsQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ staleTime: STALE.MINUTES.FIVE, queryKey: RQKEY(), queryFn: async () => { - const res = await getAgent().com.atproto.server.listAppPasswords({}) + const res = await agent.com.atproto.server.listAppPasswords({}) return res.data.passwords }, }) @@ -21,7 +21,7 @@ export function useAppPasswordsQuery() { export function useAppPasswordCreateMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation< ComAtprotoServerCreateAppPassword.OutputSchema, Error, @@ -29,7 +29,7 @@ export function useAppPasswordCreateMutation() { >({ mutationFn: async ({name, privileged}) => { return ( - await getAgent().com.atproto.server.createAppPassword({ + await agent.com.atproto.server.createAppPassword({ name, privileged, }) @@ -45,10 +45,10 @@ export function useAppPasswordCreateMutation() { export function useAppPasswordDeleteMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {name: string}>({ mutationFn: async ({name}) => { - await getAgent().com.atproto.server.revokeAppPassword({ + await agent.com.atproto.server.revokeAppPassword({ name, }) }, diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index 19cded087..b599ac1a0 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -147,7 +147,7 @@ export function getAvatarTypeFromUri(uri: string) { export function useFeedSourceInfoQuery({uri}: {uri: string}) { const type = getFeedTypeFromUri(uri) - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ staleTime: STALE.INFINITY, @@ -156,10 +156,10 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) { let view: FeedSourceInfo if (type === 'feed') { - const res = await getAgent().app.bsky.feed.getFeedGenerator({feed: uri}) + const res = await agent.app.bsky.feed.getFeedGenerator({feed: uri}) view = hydrateFeedGenerator(res.data.view) } else { - const res = await getAgent().app.bsky.graph.getList({ + const res = await agent.app.bsky.graph.getList({ list: uri, limit: 1, }) @@ -174,7 +174,7 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) { export const useGetPopularFeedsQueryKey = ['getPopularFeeds'] export function useGetPopularFeedsQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyUnspeccedGetPopularFeedGenerators.OutputSchema, Error, @@ -184,7 +184,7 @@ export function useGetPopularFeedsQuery() { >({ queryKey: useGetPopularFeedsQueryKey, queryFn: async ({pageParam}) => { - const res = await getAgent().app.bsky.unspecced.getPopularFeedGenerators({ + const res = await agent.app.bsky.unspecced.getPopularFeedGenerators({ limit: 10, cursor: pageParam, }) @@ -196,10 +196,10 @@ export function useGetPopularFeedsQuery() { } export function useSearchPopularFeedsMutation() { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (query: string) => { - const res = await getAgent().app.bsky.unspecced.getPopularFeedGenerators({ + const res = await agent.app.bsky.unspecced.getPopularFeedGenerators({ limit: 10, query: query, }) @@ -241,7 +241,7 @@ const pinnedFeedInfosQueryKeyRoot = 'pinnedFeedsInfos' export function usePinnedFeedsInfos() { const {hasSession} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const {data: preferences, isLoading: isLoadingPrefs} = usePreferencesQuery() const pinnedItems = preferences?.savedFeeds.filter(feed => feed.pinned) ?? [] @@ -264,8 +264,8 @@ export function usePinnedFeedsInfos() { const pinnedFeeds = pinnedItems.filter(feed => feed.type === 'feed') let feedsPromise = Promise.resolve() if (pinnedFeeds.length > 0) { - feedsPromise = getAgent() - .app.bsky.feed.getFeedGenerators({ + feedsPromise = agent.app.bsky.feed + .getFeedGenerators({ feeds: pinnedFeeds.map(f => f.value), }) .then(res => { @@ -279,8 +279,8 @@ export function usePinnedFeedsInfos() { // Get all lists. This currently has to be done individually. const pinnedLists = pinnedItems.filter(feed => feed.type === 'list') const listsPromises = pinnedLists.map(list => - getAgent() - .app.bsky.graph.getList({ + agent.app.bsky.graph + .getList({ list: list.value, limit: 1, }) diff --git a/src/state/queries/handle.ts b/src/state/queries/handle.ts index 1ab275fcf..d2d79e12d 100644 --- a/src/state/queries/handle.ts +++ b/src/state/queries/handle.ts @@ -14,7 +14,7 @@ const fetchDidQueryKey = (handleOrDid: string) => [didQueryKeyRoot, handleOrDid] export function useFetchHandle() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return React.useCallback( async (handleOrDid: string) => { @@ -22,23 +22,23 @@ export function useFetchHandle() { const res = await queryClient.fetchQuery({ staleTime: STALE.MINUTES.FIVE, queryKey: fetchHandleQueryKey(handleOrDid), - queryFn: () => getAgent().getProfile({actor: handleOrDid}), + queryFn: () => agent.getProfile({actor: handleOrDid}), }) return res.data.handle } return handleOrDid }, - [queryClient, getAgent], + [queryClient, agent], ) } export function useUpdateHandleMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({handle}: {handle: string}) => { - await getAgent().updateHandle({handle}) + await agent.updateHandle({handle}) }, onSuccess(_data, variables) { queryClient.invalidateQueries({ @@ -50,7 +50,7 @@ export function useUpdateHandleMutation() { export function useFetchDid() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return React.useCallback( async (handleOrDid: string) => { @@ -60,13 +60,13 @@ export function useFetchDid() { queryFn: async () => { let identifier = handleOrDid if (!identifier.startsWith('did:')) { - const res = await getAgent().resolveHandle({handle: identifier}) + const res = await agent.resolveHandle({handle: identifier}) identifier = res.data.did } return identifier }, }) }, - [queryClient, getAgent], + [queryClient, agent], ) } diff --git a/src/state/queries/invites.ts b/src/state/queries/invites.ts index f9cf25c69..fdccac8cb 100644 --- a/src/state/queries/invites.ts +++ b/src/state/queries/invites.ts @@ -16,13 +16,13 @@ export type InviteCodesQueryResponse = Exclude< undefined > export function useInviteCodesQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ staleTime: STALE.MINUTES.FIVE, queryKey: [inviteCodesQueryKeyRoot], queryFn: async () => { - const res = await getAgent() - .com.atproto.server.getAccountInviteCodes({}) + const res = await agent.com.atproto.server + .getAccountInviteCodes({}) .catch(e => { if (cleanError(e) === 'Bad token scope') { return null diff --git a/src/state/queries/labeler.ts b/src/state/queries/labeler.ts index 359291636..058e8fcde 100644 --- a/src/state/queries/labeler.ts +++ b/src/state/queries/labeler.ts @@ -31,12 +31,12 @@ export function useLabelerInfoQuery({ did?: string enabled?: boolean }) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ enabled: !!did && enabled !== false, queryKey: labelerInfoQueryKey(did as string), queryFn: async () => { - const res = await getAgent().app.bsky.labeler.getServices({ + const res = await agent.app.bsky.labeler.getServices({ dids: [did as string], detailed: true, }) @@ -46,26 +46,26 @@ export function useLabelerInfoQuery({ } export function useLabelersInfoQuery({dids}: {dids: string[]}) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ enabled: !!dids.length, queryKey: labelersInfoQueryKey(dids), queryFn: async () => { - const res = await getAgent().app.bsky.labeler.getServices({dids}) + const res = await agent.app.bsky.labeler.getServices({dids}) return res.data.views as AppBskyLabelerDefs.LabelerView[] }, }) } export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ enabled: !!dids.length, queryKey: labelersDetailedInfoQueryKey(dids), gcTime: 1000 * 60 * 60 * 6, // 6 hours staleTime: STALE.MINUTES.ONE, queryFn: async () => { - const res = await getAgent().app.bsky.labeler.getServices({ + const res = await agent.app.bsky.labeler.getServices({ dids, detailed: true, }) @@ -76,7 +76,7 @@ export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) { export function useLabelerSubscriptionMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ async mutationFn({did, subscribe}: {did: string; subscribe: boolean}) { @@ -87,9 +87,9 @@ export function useLabelerSubscriptionMutation() { }).parse({did, subscribe}) if (subscribe) { - await getAgent().addLabeler(did) + await agent.addLabeler(did) } else { - await getAgent().removeLabeler(did) + await agent.removeLabeler(did) } }, onSuccess() { diff --git a/src/state/queries/like.ts b/src/state/queries/like.ts index 75e93951a..fa40300a4 100644 --- a/src/state/queries/like.ts +++ b/src/state/queries/like.ts @@ -3,20 +3,20 @@ import {useMutation} from '@tanstack/react-query' import {useAgent} from '#/state/session' export function useLikeMutation() { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({uri, cid}: {uri: string; cid: string}) => { - const res = await getAgent().like(uri, cid) + const res = await agent.like(uri, cid) return {uri: res.uri} }, }) } export function useUnlikeMutation() { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({uri}: {uri: string}) => { - await getAgent().deleteLike(uri) + await agent.deleteLike(uri) }, }) } diff --git a/src/state/queries/list-members.ts b/src/state/queries/list-members.ts index 6f87d53c0..de9a36ab7 100644 --- a/src/state/queries/list-members.ts +++ b/src/state/queries/list-members.ts @@ -16,7 +16,7 @@ const RQKEY_ROOT = 'list-members' export const RQKEY = (uri: string) => [RQKEY_ROOT, uri] export function useListMembersQuery(uri: string) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetList.OutputSchema, Error, @@ -27,7 +27,7 @@ export function useListMembersQuery(uri: string) { staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(uri), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getList({ + const res = await agent.app.bsky.graph.getList({ list: uri, limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/list-memberships.ts b/src/state/queries/list-memberships.ts index 46e6bdfc2..83a2c2db1 100644 --- a/src/state/queries/list-memberships.ts +++ b/src/state/queries/list-memberships.ts @@ -40,7 +40,7 @@ export interface ListMembersip { */ export function useDangerousListMembershipsQuery() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<ListMembersip[]>({ staleTime: STALE.MINUTES.FIVE, queryKey: RQKEY(), @@ -51,7 +51,7 @@ export function useDangerousListMembershipsQuery() { let cursor let arr: ListMembersip[] = [] for (let i = 0; i < SANITY_PAGE_LIMIT; i++) { - const res = await getAgent().app.bsky.graph.listitem.list({ + const res = await agent.app.bsky.graph.listitem.list({ repo: currentAccount.did, limit: PAGE_SIZE, cursor, @@ -92,7 +92,7 @@ export function getMembership( export function useListMembershipAddMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation< {uri: string; cid: string}, @@ -103,7 +103,7 @@ export function useListMembershipAddMutation() { if (!currentAccount) { throw new Error('Not logged in') } - const res = await getAgent().app.bsky.graph.listitem.create( + const res = await agent.app.bsky.graph.listitem.create( {repo: currentAccount.did}, { subject: actorDid, @@ -151,7 +151,7 @@ export function useListMembershipAddMutation() { export function useListMembershipRemoveMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation< void, @@ -163,7 +163,7 @@ export function useListMembershipRemoveMutation() { throw new Error('Not logged in') } const membershipUrip = new AtUri(membershipUri) - await getAgent().app.bsky.graph.listitem.delete({ + await agent.app.bsky.graph.listitem.delete({ repo: currentAccount.did, rkey: membershipUrip.rkey, }) diff --git a/src/state/queries/list.ts b/src/state/queries/list.ts index dd2e21fb6..eeb9c3b38 100644 --- a/src/state/queries/list.ts +++ b/src/state/queries/list.ts @@ -21,7 +21,7 @@ const RQKEY_ROOT = 'list' export const RQKEY = (uri: string) => [RQKEY_ROOT, uri] export function useListQuery(uri?: string) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyGraphDefs.ListView, Error>({ staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(uri || ''), @@ -29,7 +29,7 @@ export function useListQuery(uri?: string) { if (!uri) { throw new Error('URI not provided') } - const res = await getAgent().app.bsky.graph.getList({ + const res = await agent.app.bsky.graph.getList({ list: uri, limit: 1, }) @@ -49,7 +49,7 @@ export interface ListCreateMutateParams { export function useListCreateMutation() { const {currentAccount} = useSession() const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<{uri: string; cid: string}, Error, ListCreateMutateParams>( { async mutationFn({ @@ -77,10 +77,10 @@ export function useListCreateMutation() { createdAt: new Date().toISOString(), } if (avatar) { - const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime) + const blobRes = await uploadBlob(agent, avatar.path, avatar.mime) record.avatar = blobRes.data.blob } - const res = await getAgent().app.bsky.graph.list.create( + const res = await agent.app.bsky.graph.list.create( { repo: currentAccount.did, }, @@ -89,7 +89,7 @@ export function useListCreateMutation() { // wait for the appview to update await whenAppViewReady( - getAgent, + agent, res.uri, (v: AppBskyGraphGetList.Response) => { return typeof v?.data?.list.uri === 'string' @@ -116,7 +116,7 @@ export interface ListMetadataMutateParams { } export function useListMetadataMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation< {uri: string; cid: string}, @@ -133,7 +133,7 @@ export function useListMetadataMutation() { } // get the current record - const {value: record} = await getAgent().app.bsky.graph.list.get({ + const {value: record} = await agent.app.bsky.graph.list.get({ repo: currentAccount.did, rkey, }) @@ -143,13 +143,13 @@ export function useListMetadataMutation() { record.description = description record.descriptionFacets = descriptionFacets if (avatar) { - const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime) + const blobRes = await uploadBlob(agent, avatar.path, avatar.mime) record.avatar = blobRes.data.blob } else if (avatar === null) { record.avatar = undefined } const res = ( - await getAgent().com.atproto.repo.putRecord({ + await agent.com.atproto.repo.putRecord({ repo: currentAccount.did, collection: 'app.bsky.graph.list', rkey, @@ -159,7 +159,7 @@ export function useListMetadataMutation() { // wait for the appview to update await whenAppViewReady( - getAgent, + agent, res.uri, (v: AppBskyGraphGetList.Response) => { const list = v.data.list @@ -184,7 +184,7 @@ export function useListMetadataMutation() { export function useListDeleteMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation<void, Error, {uri: string}>({ mutationFn: async ({uri}) => { @@ -195,7 +195,7 @@ export function useListDeleteMutation() { let cursor let listitemRecordUris: string[] = [] for (let i = 0; i < 100; i++) { - const res = await getAgent().app.bsky.graph.listitem.list({ + const res = await agent.app.bsky.graph.listitem.list({ repo: currentAccount.did, cursor, limit: 100, @@ -226,20 +226,16 @@ export function useListDeleteMutation() { // apply in chunks for (const writesChunk of chunk(writes, 10)) { - await getAgent().com.atproto.repo.applyWrites({ + await agent.com.atproto.repo.applyWrites({ repo: currentAccount.did, writes: writesChunk, }) } // wait for the appview to update - await whenAppViewReady( - getAgent, - uri, - (v: AppBskyGraphGetList.Response) => { - return !v?.success - }, - ) + await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => { + return !v?.success + }) }, onSuccess() { invalidateMyLists(queryClient) @@ -253,22 +249,18 @@ export function useListDeleteMutation() { export function useListMuteMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {uri: string; mute: boolean}>({ mutationFn: async ({uri, mute}) => { if (mute) { - await getAgent().muteModList(uri) + await agent.muteModList(uri) } else { - await getAgent().unmuteModList(uri) + await agent.unmuteModList(uri) } - await whenAppViewReady( - getAgent, - uri, - (v: AppBskyGraphGetList.Response) => { - return Boolean(v?.data.list.viewer?.muted) === mute - }, - ) + await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => { + return Boolean(v?.data.list.viewer?.muted) === mute + }) }, onSuccess(data, variables) { queryClient.invalidateQueries({ @@ -280,24 +272,20 @@ export function useListMuteMutation() { export function useListBlockMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {uri: string; block: boolean}>({ mutationFn: async ({uri, block}) => { if (block) { - await getAgent().blockModList(uri) + await agent.blockModList(uri) } else { - await getAgent().unblockModList(uri) + await agent.unblockModList(uri) } - await whenAppViewReady( - getAgent, - uri, - (v: AppBskyGraphGetList.Response) => { - return block - ? typeof v?.data.list.viewer?.blocked === 'string' - : !v?.data.list.viewer?.blocked - }, - ) + await whenAppViewReady(agent, uri, (v: AppBskyGraphGetList.Response) => { + return block + ? typeof v?.data.list.viewer?.blocked === 'string' + : !v?.data.list.viewer?.blocked + }) }, onSuccess(data, variables) { queryClient.invalidateQueries({ @@ -308,7 +296,7 @@ export function useListBlockMutation() { } async function whenAppViewReady( - getAgent: () => BskyAgent, + agent: BskyAgent, uri: string, fn: (res: AppBskyGraphGetList.Response) => boolean, ) { @@ -317,7 +305,7 @@ async function whenAppViewReady( 1e3, // 1s delay between tries fn, () => - getAgent().app.bsky.graph.getList({ + agent.app.bsky.graph.getList({ list: uri, limit: 1, }), diff --git a/src/state/queries/messages/actor-declaration.ts b/src/state/queries/messages/actor-declaration.ts index d6a86cf69..1105e2b3c 100644 --- a/src/state/queries/messages/actor-declaration.ts +++ b/src/state/queries/messages/actor-declaration.ts @@ -14,12 +14,12 @@ export function useUpdateActorDeclaration({ }) { const queryClient = useQueryClient() const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (allowIncoming: 'all' | 'none' | 'following') => { if (!currentAccount) throw new Error('Not logged in') - const result = await getAgent().api.com.atproto.repo.putRecord({ + const result = await agent.api.com.atproto.repo.putRecord({ repo: currentAccount.did, collection: 'chat.bsky.actor.declaration', rkey: 'self', @@ -64,13 +64,13 @@ export function useUpdateActorDeclaration({ // for use in the settings screen for testing export function useDeleteActorDeclaration() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async () => { if (!currentAccount) throw new Error('Not logged in') // TODO(sam): remove validate: false once PDSes have the new lexicon - const result = await getAgent().api.com.atproto.repo.deleteRecord({ + const result = await agent.api.com.atproto.repo.deleteRecord({ repo: currentAccount.did, collection: 'chat.bsky.actor.declaration', rkey: 'self', diff --git a/src/state/queries/messages/conversation.ts b/src/state/queries/messages/conversation.ts index baf69223a..16ace3c5a 100644 --- a/src/state/queries/messages/conversation.ts +++ b/src/state/queries/messages/conversation.ts @@ -11,12 +11,12 @@ const RQKEY_ROOT = 'convo' export const RQKEY = (convoId: string) => [RQKEY_ROOT, convoId] export function useConvoQuery(convo: ChatBskyConvoDefs.ConvoView) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ queryKey: RQKEY(convo.id), queryFn: async () => { - const {data} = await getAgent().api.chat.bsky.convo.getConvo( + const {data} = await agent.api.chat.bsky.convo.getConvo( {convoId: convo.id}, {headers: DM_SERVICE_HEADERS}, ) @@ -30,7 +30,7 @@ export function useConvoQuery(convo: ChatBskyConvoDefs.ConvoView) { export function useMarkAsReadMutation() { const optimisticUpdate = useOnMarkAsRead() const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({ @@ -42,7 +42,7 @@ export function useMarkAsReadMutation() { }) => { if (!convoId) throw new Error('No convoId provided') - await getAgent().api.chat.bsky.convo.updateRead( + await agent.api.chat.bsky.convo.updateRead( { convoId, messageId, diff --git a/src/state/queries/messages/get-convo-for-members.ts b/src/state/queries/messages/get-convo-for-members.ts index a260d5416..7979e0665 100644 --- a/src/state/queries/messages/get-convo-for-members.ts +++ b/src/state/queries/messages/get-convo-for-members.ts @@ -18,11 +18,11 @@ export function useGetConvoForMembers({ onError?: (error: Error) => void }) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (members: string[]) => { - const {data} = await getAgent().api.chat.bsky.convo.getConvoForMembers( + const {data} = await agent.api.chat.bsky.convo.getConvoForMembers( {members: members}, {headers: DM_SERVICE_HEADERS}, ) @@ -44,16 +44,13 @@ export function useGetConvoForMembers({ * Gets the conversation ID for a given DID. Returns null if it's not possible to message them. */ export function useMaybeConvoForUser(did: string) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ queryKey: RQKEY(did), queryFn: async () => { - const convo = await getAgent() - .api.chat.bsky.convo.getConvoForMembers( - {members: [did]}, - {headers: DM_SERVICE_HEADERS}, - ) + const convo = await agent.api.chat.bsky.convo + .getConvoForMembers({members: [did]}, {headers: DM_SERVICE_HEADERS}) .catch(() => ({success: null})) if (convo.success) { diff --git a/src/state/queries/messages/leave-conversation.ts b/src/state/queries/messages/leave-conversation.ts index 9f45de544..29c71a606 100644 --- a/src/state/queries/messages/leave-conversation.ts +++ b/src/state/queries/messages/leave-conversation.ts @@ -17,13 +17,13 @@ export function useLeaveConvo( }, ) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async () => { if (!convoId) throw new Error('No convoId provided') - const {data} = await getAgent().api.chat.bsky.convo.leaveConvo( + const {data} = await agent.api.chat.bsky.convo.leaveConvo( {convoId}, {headers: DM_SERVICE_HEADERS, encoding: 'application/json'}, ) diff --git a/src/state/queries/messages/list-converations.tsx b/src/state/queries/messages/list-converations.tsx index 13a4a3bf2..46892f6ae 100644 --- a/src/state/queries/messages/list-converations.tsx +++ b/src/state/queries/messages/list-converations.tsx @@ -27,12 +27,12 @@ export const RQKEY = ['convo-list'] type RQPageParam = string | undefined export function useListConvosQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery({ queryKey: RQKEY, queryFn: async ({pageParam}) => { - const {data} = await getAgent().api.chat.bsky.convo.listConvos( + const {data} = await agent.api.chat.bsky.convo.listConvos( {cursor: pageParam}, {headers: DM_SERVICE_HEADERS}, ) diff --git a/src/state/queries/messages/mute-conversation.ts b/src/state/queries/messages/mute-conversation.ts index fa760e00d..bc383fde1 100644 --- a/src/state/queries/messages/mute-conversation.ts +++ b/src/state/queries/messages/mute-conversation.ts @@ -21,13 +21,11 @@ export function useMuteConvo( }, ) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({mute}: {mute: boolean}) => { if (!convoId) throw new Error('No convoId provided') - - const agent = getAgent() if (mute) { const {data} = await agent.api.chat.bsky.convo.muteConvo( {convoId}, diff --git a/src/state/queries/my-blocked-accounts.ts b/src/state/queries/my-blocked-accounts.ts index 73e289056..05a78825f 100644 --- a/src/state/queries/my-blocked-accounts.ts +++ b/src/state/queries/my-blocked-accounts.ts @@ -13,7 +13,7 @@ export const RQKEY = () => [RQKEY_ROOT] type RQPageParam = string | undefined export function useMyBlockedAccountsQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetBlocks.OutputSchema, Error, @@ -23,7 +23,7 @@ export function useMyBlockedAccountsQuery() { >({ queryKey: RQKEY(), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getBlocks({ + const res = await agent.app.bsky.graph.getBlocks({ limit: 30, cursor: pageParam, }) diff --git a/src/state/queries/my-lists.ts b/src/state/queries/my-lists.ts index 7fce8b68e..0f8721c61 100644 --- a/src/state/queries/my-lists.ts +++ b/src/state/queries/my-lists.ts @@ -16,7 +16,7 @@ export const RQKEY = (filter: MyListsFilter) => [RQKEY_ROOT, filter] export function useMyListsQuery(filter: MyListsFilter) { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyGraphDefs.ListView[]>({ staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(filter), @@ -24,8 +24,8 @@ export function useMyListsQuery(filter: MyListsFilter) { let lists: AppBskyGraphDefs.ListView[] = [] const promises = [ accumulate(cursor => - getAgent() - .app.bsky.graph.getLists({ + agent.app.bsky.graph + .getLists({ actor: currentAccount!.did, cursor, limit: 50, @@ -39,8 +39,8 @@ export function useMyListsQuery(filter: MyListsFilter) { if (filter === 'all-including-subscribed' || filter === 'mod') { promises.push( accumulate(cursor => - getAgent() - .app.bsky.graph.getListMutes({ + agent.app.bsky.graph + .getListMutes({ cursor, limit: 50, }) @@ -52,8 +52,8 @@ export function useMyListsQuery(filter: MyListsFilter) { ) promises.push( accumulate(cursor => - getAgent() - .app.bsky.graph.getListBlocks({ + agent.app.bsky.graph + .getListBlocks({ cursor, limit: 50, }) diff --git a/src/state/queries/my-muted-accounts.ts b/src/state/queries/my-muted-accounts.ts index 6eded3f83..5fb0fa79b 100644 --- a/src/state/queries/my-muted-accounts.ts +++ b/src/state/queries/my-muted-accounts.ts @@ -13,7 +13,7 @@ export const RQKEY = () => [RQKEY_ROOT] type RQPageParam = string | undefined export function useMyMutedAccountsQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetMutes.OutputSchema, Error, @@ -23,7 +23,7 @@ export function useMyMutedAccountsQuery() { >({ queryKey: RQKEY(), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getMutes({ + const res = await agent.app.bsky.graph.getMutes({ limit: 30, cursor: pageParam, }) diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index 80e5a4c47..523af2824 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -47,7 +47,7 @@ export function RQKEY() { } export function useNotificationFeedQuery(opts?: {enabled?: boolean}) { - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() const moderationOpts = useModerationOpts() const threadMutes = useMutedThreads() @@ -73,7 +73,7 @@ export function useNotificationFeedQuery(opts?: {enabled?: boolean}) { if (!page) { page = ( await fetchPage({ - getAgent, + agent, limit: PAGE_SIZE, cursor: pageParam, queryClient, diff --git a/src/state/queries/notifications/unread.tsx b/src/state/queries/notifications/unread.tsx index acc68c360..5f33cdf74 100644 --- a/src/state/queries/notifications/unread.tsx +++ b/src/state/queries/notifications/unread.tsx @@ -45,7 +45,7 @@ const apiContext = React.createContext<ApiContext>({ export function Provider({children}: React.PropsWithChildren<{}>) { const {hasSession} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() const moderationOpts = useModerationOpts() const threadMutes = useMutedThreads() @@ -112,7 +112,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { return { async markAllRead() { // update server - await getAgent().updateSeenNotifications( + await agent.updateSeenNotifications( cacheRef.current.syncedAt.toISOString(), ) @@ -127,7 +127,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { isPoll, }: {invalidate?: boolean; isPoll?: boolean} = {}) { try { - if (!getAgent().session) return + if (!agent.session) return if (AppState.currentState !== 'active') { return } @@ -142,7 +142,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { // count const {page, indexedAt: lastIndexed} = await fetchPage({ - getAgent, + agent, cursor: undefined, limit: 40, queryClient, @@ -192,7 +192,7 @@ export function Provider({children}: React.PropsWithChildren<{}>) { } }, } - }, [setNumUnread, queryClient, moderationOpts, threadMutes, getAgent]) + }, [setNumUnread, queryClient, moderationOpts, threadMutes, agent]) checkUnreadRef.current = api.checkUnread return ( diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index 5029a33cc..ebcdff686 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -23,7 +23,7 @@ const MS_2DAY = MS_1HR * 48 // = export async function fetchPage({ - getAgent, + agent, cursor, limit, queryClient, @@ -31,7 +31,7 @@ export async function fetchPage({ threadMutes, fetchAdditionalData, }: { - getAgent: () => BskyAgent + agent: BskyAgent cursor: string | undefined limit: number queryClient: QueryClient @@ -39,7 +39,7 @@ export async function fetchPage({ threadMutes: string[] fetchAdditionalData: boolean }): Promise<{page: FeedPage; indexedAt: string | undefined}> { - const res = await getAgent().listNotifications({ + const res = await agent.listNotifications({ limit, cursor, }) @@ -56,7 +56,7 @@ export async function fetchPage({ // we fetch subjects of notifications (usually posts) now instead of lazily // in the UI to avoid relayouts if (fetchAdditionalData) { - const subjects = await fetchSubjects(getAgent, notifsGrouped) + const subjects = await fetchSubjects(agent, notifsGrouped) for (const notif of notifsGrouped) { if (notif.subjectUri) { notif.subject = subjects.get(notif.subjectUri) @@ -140,7 +140,7 @@ export function groupNotifications( } async function fetchSubjects( - getAgent: () => BskyAgent, + agent: BskyAgent, groupedNotifs: FeedNotification[], ): Promise<Map<string, AppBskyFeedDefs.PostView>> { const uris = new Set<string>() @@ -152,9 +152,7 @@ async function fetchSubjects( const uriChunks = chunk(Array.from(uris), 25) const postsChunks = await Promise.all( uriChunks.map(uris => - getAgent() - .app.bsky.feed.getPosts({uris}) - .then(res => res.data.posts), + agent.app.bsky.feed.getPosts({uris}).then(res => res.data.posts), ), ) const map = new Map<string, AppBskyFeedDefs.PostView>() diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index 2851a0c2a..eeec692c6 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -117,7 +117,7 @@ export function usePostFeedQuery( f => f.pinned && f.value === 'following', ) ?? -1 const enableFollowingToDiscoverFallback = followingPinnedIndex === 0 - const {getAgent} = useAgent() + const agent = useAgent() const lastRun = useRef<{ data: InfiniteData<FeedPageUnselected> args: typeof selectArgs @@ -155,7 +155,7 @@ export function usePostFeedQuery( feedDesc, feedParams: params || {}, feedTuners, - getAgent, + agent, // Not in the query key because they don't change: userInterests, // Not in the query key. Reacting to it switching isn't important: @@ -173,7 +173,7 @@ export function usePostFeedQuery( * moderations happen later, which results in some posts being shown and * some not. */ - if (!getAgent().session) { + if (!agent.session) { assertSomePostsPassModeration(res.feed) } @@ -397,50 +397,50 @@ function createApi({ feedParams, feedTuners, userInterests, - getAgent, + agent, enableFollowingToDiscoverFallback, }: { feedDesc: FeedDescriptor feedParams: FeedParams feedTuners: FeedTunerFn[] userInterests?: string - getAgent: () => BskyAgent + agent: BskyAgent enableFollowingToDiscoverFallback: boolean }) { if (feedDesc === 'following') { if (feedParams.mergeFeedEnabled) { return new MergeFeedAPI({ - getAgent, + agent, feedParams, feedTuners, userInterests, }) } else { if (enableFollowingToDiscoverFallback) { - return new HomeFeedAPI({getAgent, userInterests}) + return new HomeFeedAPI({agent, userInterests}) } else { - return new FollowingFeedAPI({getAgent}) + return new FollowingFeedAPI({agent}) } } } else if (feedDesc.startsWith('author')) { const [_, actor, filter] = feedDesc.split('|') - return new AuthorFeedAPI({getAgent, feedParams: {actor, filter}}) + return new AuthorFeedAPI({agent, feedParams: {actor, filter}}) } else if (feedDesc.startsWith('likes')) { const [_, actor] = feedDesc.split('|') - return new LikesFeedAPI({getAgent, feedParams: {actor}}) + return new LikesFeedAPI({agent, feedParams: {actor}}) } else if (feedDesc.startsWith('feedgen')) { const [_, feed] = feedDesc.split('|') return new CustomFeedAPI({ - getAgent, + agent, feedParams: {feed}, userInterests, }) } else if (feedDesc.startsWith('list')) { const [_, list] = feedDesc.split('|') - return new ListFeedAPI({getAgent, feedParams: {list}}) + return new ListFeedAPI({agent, feedParams: {list}}) } else { // shouldnt happen - return new FollowingFeedAPI({getAgent}) + return new FollowingFeedAPI({agent}) } } diff --git a/src/state/queries/post-liked-by.ts b/src/state/queries/post-liked-by.ts index fdf694860..ab9f5c7bb 100644 --- a/src/state/queries/post-liked-by.ts +++ b/src/state/queries/post-liked-by.ts @@ -16,7 +16,7 @@ const RQKEY_ROOT = 'liked-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] export function useLikedByQuery(resolvedUri: string | undefined) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyFeedGetLikes.OutputSchema, Error, @@ -26,7 +26,7 @@ export function useLikedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().getLikes({ + const res = await agent.getLikes({ uri: resolvedUri || '', limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/post-reposted-by.ts b/src/state/queries/post-reposted-by.ts index 13643e98d..a27f203dd 100644 --- a/src/state/queries/post-reposted-by.ts +++ b/src/state/queries/post-reposted-by.ts @@ -16,7 +16,7 @@ const RQKEY_ROOT = 'post-reposted-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] export function usePostRepostedByQuery(resolvedUri: string | undefined) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyFeedGetRepostedBy.OutputSchema, Error, @@ -26,7 +26,7 @@ export function usePostRepostedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().getRepostedBy({ + const res = await agent.getRepostedBy({ uri: resolvedUri || '', limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/post-thread.ts b/src/state/queries/post-thread.ts index 4ee0eb3f9..6c70bbc5d 100644 --- a/src/state/queries/post-thread.ts +++ b/src/state/queries/post-thread.ts @@ -68,12 +68,12 @@ export type ThreadModerationCache = WeakMap<ThreadNode, ModerationDecision> export function usePostThreadQuery(uri: string | undefined) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<ThreadNode, Error>({ gcTime: 0, queryKey: RQKEY(uri || ''), async queryFn() { - const res = await getAgent().getPostThread({uri: uri!}) + const res = await agent.getPostThread({uri: uri!}) if (res.success) { return responseToThreadNodes(res.data.thread) } diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index d52c65713..f27628d69 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -14,11 +14,11 @@ const RQKEY_ROOT = 'post' export const RQKEY = (postUri: string) => [RQKEY_ROOT, postUri] export function usePostQuery(uri: string | undefined) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyFeedDefs.PostView>({ queryKey: RQKEY(uri || ''), async queryFn() { - const res = await getAgent().getPosts({uris: [uri!]}) + const res = await agent.getPosts({uris: [uri!]}) if (res.success && res.data.posts[0]) { return res.data.posts[0] } @@ -31,7 +31,7 @@ export function usePostQuery(uri: string | undefined) { export function useGetPost() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useCallback( async ({uri}: {uri: string}) => { return queryClient.fetchQuery({ @@ -40,13 +40,13 @@ export function useGetPost() { const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { - const res = await getAgent().resolveHandle({ + const res = await agent.resolveHandle({ handle: urip.host, }) urip.host = res.data.did } - const res = await getAgent().getPosts({ + const res = await agent.getPosts({ uris: [urip.toString()!], }) @@ -58,7 +58,7 @@ export function useGetPost() { }, }) }, - [queryClient, getAgent], + [queryClient, agent], ) } @@ -127,7 +127,7 @@ function usePostLikeMutation( const {currentAccount} = useSession() const queryClient = useQueryClient() const postAuthor = post.author - const {getAgent} = useAgent() + const agent = useAgent() return useMutation< {uri: string}, // responds with the uri of the like Error, @@ -154,7 +154,7 @@ function usePostLikeMutation( ? toClout(post.likeCount + post.repostCount + post.replyCount) : undefined, }) - return getAgent().like(uri, cid) + return agent.like(uri, cid) }, onSuccess() { track('Post:Like') @@ -165,11 +165,11 @@ function usePostLikeMutation( function usePostUnlikeMutation( logContext: LogEvents['post:unlike']['logContext'], ) { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {postUri: string; likeUri: string}>({ mutationFn: ({likeUri}) => { logEvent('post:unlike', {logContext}) - return getAgent().deleteLike(likeUri) + return agent.deleteLike(likeUri) }, onSuccess() { track('Post:Unlike') @@ -238,7 +238,7 @@ export function usePostRepostMutationQueue( function usePostRepostMutation( logContext: LogEvents['post:repost']['logContext'], ) { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation< {uri: string}, // responds with the uri of the repost Error, @@ -246,7 +246,7 @@ function usePostRepostMutation( >({ mutationFn: post => { logEvent('post:repost', {logContext}) - return getAgent().repost(post.uri, post.cid) + return agent.repost(post.uri, post.cid) }, onSuccess() { track('Post:Repost') @@ -257,11 +257,11 @@ function usePostRepostMutation( function usePostUnrepostMutation( logContext: LogEvents['post:unrepost']['logContext'], ) { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {postUri: string; repostUri: string}>({ mutationFn: ({repostUri}) => { logEvent('post:unrepost', {logContext}) - return getAgent().deleteRepost(repostUri) + return agent.deleteRepost(repostUri) }, onSuccess() { track('Post:Unrepost') @@ -271,10 +271,10 @@ function usePostUnrepostMutation( export function usePostDeleteMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {uri: string}>({ mutationFn: async ({uri}) => { - await getAgent().deletePost(uri) + await agent.deletePost(uri) }, onSuccess(data, variables) { updatePostShadow(queryClient, variables.uri, {isDeleted: true}) diff --git a/src/state/queries/preferences/index.ts b/src/state/queries/preferences/index.ts index 555fd85a4..672abfcac 100644 --- a/src/state/queries/preferences/index.ts +++ b/src/state/queries/preferences/index.ts @@ -30,15 +30,13 @@ const preferencesQueryKeyRoot = 'getPreferences' export const preferencesQueryKey = [preferencesQueryKeyRoot] export function usePreferencesQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ staleTime: STALE.SECONDS.FIFTEEN, structuralSharing: replaceEqualDeep, refetchOnWindowFocus: true, queryKey: preferencesQueryKey, queryFn: async () => { - const agent = getAgent() - if (agent.session?.did === undefined) { return DEFAULT_LOGGED_OUT_PREFERENCES } else { @@ -75,11 +73,11 @@ export function usePreferencesQuery() { export function useClearPreferencesMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async () => { - await getAgent().app.bsky.actor.putPreferences({preferences: []}) + await agent.app.bsky.actor.putPreferences({preferences: []}) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -89,7 +87,7 @@ export function useClearPreferencesMutation() { } export function usePreferencesSetContentLabelMutation() { - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation< @@ -98,7 +96,7 @@ export function usePreferencesSetContentLabelMutation() { {label: string; visibility: LabelPreference; labelerDid: string | undefined} >({ mutationFn: async ({label, visibility, labelerDid}) => { - await getAgent().setContentLabelPref(label, visibility, labelerDid) + await agent.setContentLabelPref(label, visibility, labelerDid) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -109,7 +107,7 @@ export function usePreferencesSetContentLabelMutation() { export function useSetContentLabelMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({ @@ -121,7 +119,7 @@ export function useSetContentLabelMutation() { visibility: LabelPreference labelerDid?: string }) => { - await getAgent().setContentLabelPref(label, visibility, labelerDid) + await agent.setContentLabelPref(label, visibility, labelerDid) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -132,11 +130,11 @@ export function useSetContentLabelMutation() { export function usePreferencesSetAdultContentMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, {enabled: boolean}>({ mutationFn: async ({enabled}) => { - await getAgent().setAdultContentEnabled(enabled) + await agent.setAdultContentEnabled(enabled) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -147,11 +145,11 @@ export function usePreferencesSetAdultContentMutation() { export function usePreferencesSetBirthDateMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, {birthDate: Date}>({ mutationFn: async ({birthDate}: {birthDate: Date}) => { - await getAgent().setPersonalDetails({birthDate: birthDate.toISOString()}) + await agent.setPersonalDetails({birthDate: birthDate.toISOString()}) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -162,7 +160,7 @@ export function usePreferencesSetBirthDateMutation() { export function useSetFeedViewPreferencesMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, Partial<BskyFeedViewPreference>>({ mutationFn: async prefs => { @@ -170,7 +168,7 @@ export function useSetFeedViewPreferencesMutation() { * special handling here, merged into `feedViewPrefs` above, since * following was previously called `home` */ - await getAgent().setFeedViewPrefs('home', prefs) + await agent.setFeedViewPrefs('home', prefs) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -181,11 +179,11 @@ export function useSetFeedViewPreferencesMutation() { export function useSetThreadViewPreferencesMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, Partial<ThreadViewPreferences>>({ mutationFn: async prefs => { - await getAgent().setThreadViewPrefs(prefs) + await agent.setThreadViewPrefs(prefs) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -196,11 +194,11 @@ export function useSetThreadViewPreferencesMutation() { export function useOverwriteSavedFeedsMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({ mutationFn: async savedFeeds => { - await getAgent().overwriteSavedFeeds(savedFeeds) + await agent.overwriteSavedFeeds(savedFeeds) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -211,7 +209,7 @@ export function useOverwriteSavedFeedsMutation() { export function useAddSavedFeedsMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation< void, @@ -219,7 +217,7 @@ export function useAddSavedFeedsMutation() { Pick<AppBskyActorDefs.SavedFeed, 'type' | 'value' | 'pinned'>[] >({ mutationFn: async savedFeeds => { - await getAgent().addSavedFeeds(savedFeeds) + await agent.addSavedFeeds(savedFeeds) track('CustomFeed:Save') // triggers a refetch await queryClient.invalidateQueries({ @@ -231,11 +229,11 @@ export function useAddSavedFeedsMutation() { export function useRemoveFeedMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, Pick<AppBskyActorDefs.SavedFeed, 'id'>>({ mutationFn: async savedFeed => { - await getAgent().removeSavedFeeds([savedFeed.id]) + await agent.removeSavedFeeds([savedFeed.id]) track('CustomFeed:Unsave') // triggers a refetch await queryClient.invalidateQueries({ @@ -247,7 +245,7 @@ export function useRemoveFeedMutation() { export function useReplaceForYouWithDiscoverFeedMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async ({ @@ -258,10 +256,10 @@ export function useReplaceForYouWithDiscoverFeedMutation() { discoverFeedConfig: AppBskyActorDefs.SavedFeed | undefined }) => { if (forYouFeedConfig) { - await getAgent().removeSavedFeeds([forYouFeedConfig.id]) + await agent.removeSavedFeeds([forYouFeedConfig.id]) } if (!discoverFeedConfig) { - await getAgent().addSavedFeeds([ + await agent.addSavedFeeds([ { type: 'feed', value: PROD_DEFAULT_FEED('whats-hot'), @@ -269,7 +267,7 @@ export function useReplaceForYouWithDiscoverFeedMutation() { }, ]) } else { - await getAgent().updateSavedFeeds([ + await agent.updateSavedFeeds([ { ...discoverFeedConfig, pinned: true, @@ -286,11 +284,11 @@ export function useReplaceForYouWithDiscoverFeedMutation() { export function useUpdateSavedFeedsMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, unknown, AppBskyActorDefs.SavedFeed[]>({ mutationFn: async feeds => { - await getAgent().updateSavedFeeds(feeds) + await agent.updateSavedFeeds(feeds) // triggers a refetch await queryClient.invalidateQueries({ @@ -302,11 +300,11 @@ export function useUpdateSavedFeedsMutation() { export function useUpsertMutedWordsMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (mutedWords: AppBskyActorDefs.MutedWord[]) => { - await getAgent().upsertMutedWords(mutedWords) + await agent.upsertMutedWords(mutedWords) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -317,11 +315,11 @@ export function useUpsertMutedWordsMutation() { export function useUpdateMutedWordMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => { - await getAgent().updateMutedWord(mutedWord) + await agent.updateMutedWord(mutedWord) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, @@ -332,11 +330,11 @@ export function useUpdateMutedWordMutation() { export function useRemoveMutedWordMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation({ mutationFn: async (mutedWord: AppBskyActorDefs.MutedWord) => { - await getAgent().removeMutedWord(mutedWord) + await agent.removeMutedWord(mutedWord) // triggers a refetch await queryClient.invalidateQueries({ queryKey: preferencesQueryKey, diff --git a/src/state/queries/profile-feedgens.ts b/src/state/queries/profile-feedgens.ts index 27f2d5aaa..e2508f994 100644 --- a/src/state/queries/profile-feedgens.ts +++ b/src/state/queries/profile-feedgens.ts @@ -15,7 +15,7 @@ export function useProfileFeedgensQuery( opts?: {enabled?: boolean}, ) { const enabled = opts?.enabled !== false - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyFeedGetActorFeeds.OutputSchema, Error, @@ -25,7 +25,7 @@ export function useProfileFeedgensQuery( >({ queryKey: RQKEY(did), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.feed.getActorFeeds({ + const res = await agent.app.bsky.feed.getActorFeeds({ actor: did, limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/profile-followers.ts b/src/state/queries/profile-followers.ts index d0cbccaf5..131343cd1 100644 --- a/src/state/queries/profile-followers.ts +++ b/src/state/queries/profile-followers.ts @@ -15,7 +15,7 @@ const RQKEY_ROOT = 'profile-followers' export const RQKEY = (did: string) => [RQKEY_ROOT, did] export function useProfileFollowersQuery(did: string | undefined) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetFollowers.OutputSchema, Error, @@ -25,7 +25,7 @@ export function useProfileFollowersQuery(did: string | undefined) { >({ queryKey: RQKEY(did || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getFollowers({ + const res = await agent.app.bsky.graph.getFollowers({ actor: did || '', limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/profile-follows.ts b/src/state/queries/profile-follows.ts index 1919409c7..6d832a841 100644 --- a/src/state/queries/profile-follows.ts +++ b/src/state/queries/profile-follows.ts @@ -26,7 +26,7 @@ export function useProfileFollowsQuery( limit: PAGE_SIZE, }, ) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetFollows.OutputSchema, Error, @@ -37,7 +37,7 @@ export function useProfileFollowsQuery( staleTime: STALE.MINUTES.ONE, queryKey: RQKEY(did || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getFollows({ + const res = await agent.app.bsky.graph.getFollows({ actor: did || '', limit: limit || PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/profile-lists.ts b/src/state/queries/profile-lists.ts index 543961d63..2bb5f4d28 100644 --- a/src/state/queries/profile-lists.ts +++ b/src/state/queries/profile-lists.ts @@ -11,7 +11,7 @@ export const RQKEY = (did: string) => [RQKEY_ROOT, did] export function useProfileListsQuery(did: string, opts?: {enabled?: boolean}) { const enabled = opts?.enabled !== false - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyGraphGetLists.OutputSchema, Error, @@ -21,7 +21,7 @@ export function useProfileListsQuery(did: string, opts?: {enabled?: boolean}) { >({ queryKey: RQKEY(did), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await getAgent().app.bsky.graph.getLists({ + const res = await agent.app.bsky.graph.getLists({ actor: did, limit: PAGE_SIZE, cursor: pageParam, diff --git a/src/state/queries/profile.ts b/src/state/queries/profile.ts index af8718c5e..7cc9f6911 100644 --- a/src/state/queries/profile.ts +++ b/src/state/queries/profile.ts @@ -52,7 +52,7 @@ export function useProfileQuery({ staleTime?: number }) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyActorDefs.ProfileViewDetailed>({ // WARNING // this staleTime is load-bearing @@ -62,7 +62,7 @@ export function useProfileQuery({ refetchOnWindowFocus: true, queryKey: RQKEY(did ?? ''), queryFn: async () => { - const res = await getAgent().getProfile({actor: did ?? ''}) + const res = await agent.getProfile({actor: did ?? ''}) return res.data }, placeholderData: () => { @@ -77,31 +77,31 @@ export function useProfileQuery({ } export function useProfilesQuery({handles}: {handles: string[]}) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery({ staleTime: STALE.MINUTES.FIVE, queryKey: profilesQueryKey(handles), queryFn: async () => { - const res = await getAgent().getProfiles({actors: handles}) + const res = await agent.getProfiles({actors: handles}) return res.data }, }) } export function usePrefetchProfileQuery() { - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() const prefetchProfileQuery = useCallback( async (did: string) => { await queryClient.prefetchQuery({ queryKey: RQKEY(did), queryFn: async () => { - const res = await getAgent().getProfile({actor: did || ''}) + const res = await agent.getProfile({actor: did || ''}) return res.data }, }) }, - [queryClient, getAgent], + [queryClient, agent], ) return prefetchProfileQuery } @@ -117,7 +117,7 @@ interface ProfileUpdateParams { } export function useProfileUpdateMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, ProfileUpdateParams>({ mutationFn: async ({ profile, @@ -131,7 +131,7 @@ export function useProfileUpdateMutation() { | undefined if (newUserAvatar) { newUserAvatarPromise = uploadBlob( - getAgent(), + agent, newUserAvatar.path, newUserAvatar.mime, ) @@ -141,12 +141,12 @@ export function useProfileUpdateMutation() { | undefined if (newUserBanner) { newUserBannerPromise = uploadBlob( - getAgent(), + agent, newUserBanner.path, newUserBanner.mime, ) } - await getAgent().upsertProfile(async existing => { + await agent.upsertProfile(async existing => { existing = existing || {} if (typeof updates === 'function') { existing = updates(existing) @@ -169,7 +169,7 @@ export function useProfileUpdateMutation() { return existing }) await whenAppViewReady( - getAgent, + agent, profile.did, checkCommitted || (res => { @@ -271,7 +271,7 @@ function useProfileFollowMutation( profile: Shadow<AppBskyActorDefs.ProfileViewDetailed>, ) { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation<{uri: string; cid: string}, Error, {did: string}>({ mutationFn: async ({did}) => { @@ -287,7 +287,7 @@ function useProfileFollowMutation( followeeClout: toClout(profile.followersCount), followerClout: toClout(ownProfile?.followersCount), }) - return await getAgent().follow(did) + return await agent.follow(did) }, onSuccess(data, variables) { track('Profile:Follow', {username: variables.did}) @@ -298,12 +298,12 @@ function useProfileFollowMutation( function useProfileUnfollowMutation( logContext: LogEvents['profile:unfollow']['logContext'], ) { - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {did: string; followUri: string}>({ mutationFn: async ({followUri}) => { logEvent('profile:unfollow', {logContext}) track('Profile:Unfollow', {username: followUri}) - return await getAgent().deleteFollow(followUri) + return await agent.deleteFollow(followUri) }, }) } @@ -359,10 +359,10 @@ export function useProfileMuteMutationQueue( function useProfileMuteMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {did: string}>({ mutationFn: async ({did}) => { - await getAgent().mute(did) + await agent.mute(did) }, onSuccess() { queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) @@ -372,10 +372,10 @@ function useProfileMuteMutation() { function useProfileUnmuteMutation() { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useMutation<void, Error, {did: string}>({ mutationFn: async ({did}) => { - await getAgent().unmute(did) + await agent.unmute(did) }, onSuccess() { queryClient.invalidateQueries({queryKey: RQKEY_MY_MUTED()}) @@ -440,14 +440,14 @@ export function useProfileBlockMutationQueue( function useProfileBlockMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + 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 getAgent().app.bsky.graph.block.create( + return await agent.app.bsky.graph.block.create( {repo: currentAccount.did}, {subject: did, createdAt: new Date().toISOString()}, ) @@ -461,7 +461,7 @@ function useProfileBlockMutation() { function useProfileUnblockMutation() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const queryClient = useQueryClient() return useMutation<void, Error, {did: string; blockUri: string}>({ mutationFn: async ({blockUri}) => { @@ -469,7 +469,7 @@ function useProfileUnblockMutation() { throw new Error('Not signed in') } const {rkey} = new AtUri(blockUri) - await getAgent().app.bsky.graph.block.delete({ + await agent.app.bsky.graph.block.delete({ repo: currentAccount.did, rkey, }) @@ -489,7 +489,7 @@ export function precacheProfile( } async function whenAppViewReady( - getAgent: () => BskyAgent, + agent: BskyAgent, actor: string, fn: (res: AppBskyActorGetProfile.Response) => boolean, ) { @@ -497,7 +497,7 @@ async function whenAppViewReady( 5, // 5 tries 1e3, // 1s delay between tries fn, - () => getAgent().app.bsky.actor.getProfile({actor}), + () => agent.app.bsky.actor.getProfile({actor}), ) } diff --git a/src/state/queries/resolve-uri.ts b/src/state/queries/resolve-uri.ts index b1980f07d..7bd26435c 100644 --- a/src/state/queries/resolve-uri.ts +++ b/src/state/queries/resolve-uri.ts @@ -24,7 +24,7 @@ export function useResolveUriQuery(uri: string | undefined): UriUseQueryResult { export function useResolveDidQuery(didOrHandle: string | undefined) { const queryClient = useQueryClient() - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<string, Error>({ staleTime: STALE.HOURS.ONE, @@ -34,7 +34,7 @@ export function useResolveDidQuery(didOrHandle: string | undefined) { // Just return the did if it's already one if (didOrHandle.startsWith('did:')) return didOrHandle - const res = await getAgent().resolveHandle({handle: didOrHandle}) + const res = await agent.resolveHandle({handle: didOrHandle}) return res.data.did }, initialData: () => { diff --git a/src/state/queries/search-posts.ts b/src/state/queries/search-posts.ts index b0720af3c..5bee96535 100644 --- a/src/state/queries/search-posts.ts +++ b/src/state/queries/search-posts.ts @@ -25,7 +25,7 @@ export function useSearchPostsQuery({ sort?: 'top' | 'latest' enabled?: boolean }) { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyFeedSearchPosts.OutputSchema, Error, @@ -35,7 +35,7 @@ export function useSearchPostsQuery({ >({ queryKey: searchPostsQueryKey({query, sort}), queryFn: async ({pageParam}) => { - const res = await getAgent().app.bsky.feed.searchPosts({ + const res = await agent.app.bsky.feed.searchPosts({ q: query, limit: 25, cursor: pageParam, diff --git a/src/state/queries/suggested-feeds.ts b/src/state/queries/suggested-feeds.ts index c7751448e..19614c2cb 100644 --- a/src/state/queries/suggested-feeds.ts +++ b/src/state/queries/suggested-feeds.ts @@ -8,7 +8,7 @@ const suggestedFeedsQueryKeyRoot = 'suggestedFeeds' export const suggestedFeedsQueryKey = [suggestedFeedsQueryKeyRoot] export function useSuggestedFeedsQuery() { - const {getAgent} = useAgent() + const agent = useAgent() return useInfiniteQuery< AppBskyFeedGetSuggestedFeeds.OutputSchema, Error, @@ -19,7 +19,7 @@ export function useSuggestedFeedsQuery() { staleTime: STALE.HOURS.ONE, queryKey: suggestedFeedsQueryKey, queryFn: async ({pageParam}) => { - const res = await getAgent().app.bsky.feed.getSuggestedFeeds({ + const res = await agent.app.bsky.feed.getSuggestedFeeds({ limit: 10, cursor: pageParam, }) diff --git a/src/state/queries/suggested-follows.ts b/src/state/queries/suggested-follows.ts index 7740b1977..59b8f7ed5 100644 --- a/src/state/queries/suggested-follows.ts +++ b/src/state/queries/suggested-follows.ts @@ -33,7 +33,7 @@ const suggestedFollowsByActorQueryKey = (did: string) => [ export function useSuggestedFollowsQuery() { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const moderationOpts = useModerationOpts() const {data: preferences} = usePreferencesQuery() @@ -49,7 +49,7 @@ export function useSuggestedFollowsQuery() { queryKey: suggestedFollowsQueryKey, queryFn: async ({pageParam}) => { const contentLangs = getContentLanguages().join(',') - const res = await getAgent().app.bsky.actor.getSuggestions( + const res = await agent.app.bsky.actor.getSuggestions( { limit: 25, cursor: pageParam, @@ -94,11 +94,11 @@ export function useSuggestedFollowsQuery() { } export function useSuggestedFollowsByActorQuery({did}: {did: string}) { - const {getAgent} = useAgent() + const agent = useAgent() return useQuery<AppBskyGraphGetSuggestedFollowsByActor.OutputSchema, Error>({ queryKey: suggestedFollowsByActorQueryKey(did), queryFn: async () => { - const res = await getAgent().app.bsky.graph.getSuggestedFollowsByActor({ + const res = await agent.app.bsky.graph.getSuggestedFollowsByActor({ actor: did, }) return res.data diff --git a/src/state/session/index.tsx b/src/state/session/index.tsx index af8417f8d..e38dd2bb5 100644 --- a/src/state/session/index.tsx +++ b/src/state/session/index.tsx @@ -268,17 +268,10 @@ export function useRequireAuth() { ) } -export function useAgent(): {getAgent: () => BskyAgent} { +export function useAgent(): BskyAgent { const agent = React.useContext(AgentContext) if (!agent) { throw Error('useAgent() must be below <SessionProvider>.') } - return React.useMemo( - () => ({ - getAgent() { - return agent - }, - }), - [agent], - ) + return agent } diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index 7b102c823..12e57c411 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -90,7 +90,7 @@ export const ComposePost = observer(function ComposePost({ imageUris: initImageUris, }: Props) { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const {data: currentProfile} = useProfileQuery({did: currentAccount!.did}) const {isModalActive} = useModals() const {closeComposer} = useComposerControls() @@ -260,7 +260,7 @@ export const ComposePost = observer(function ComposePost({ let postUri try { postUri = ( - await apilib.post(getAgent(), { + await apilib.post(agent, { rawText: richtext.text, replyTo: replyTo?.uri, images: gallery.images, diff --git a/src/view/com/composer/useExternalLinkFetch.e2e.ts b/src/view/com/composer/useExternalLinkFetch.e2e.ts index 65ecb866e..257a3e8e5 100644 --- a/src/view/com/composer/useExternalLinkFetch.e2e.ts +++ b/src/view/com/composer/useExternalLinkFetch.e2e.ts @@ -8,7 +8,7 @@ import {ComposerOpts} from 'state/shell/composer' export function useExternalLinkFetch({}: { setQuote: (opts: ComposerOpts['quote']) => void }) { - const {getAgent} = useAgent() + const agent = useAgent() const [extLink, setExtLink] = useState<apilib.ExternalEmbedDraft | undefined>( undefined, ) @@ -22,7 +22,7 @@ export function useExternalLinkFetch({}: { return cleanup } if (!extLink.meta) { - getLinkMeta(getAgent(), extLink.uri).then(meta => { + getLinkMeta(agent, extLink.uri).then(meta => { if (aborted) { return } @@ -41,7 +41,7 @@ export function useExternalLinkFetch({}: { }) } return cleanup - }, [extLink, getAgent]) + }, [extLink, agent]) return {extLink, setExtLink} } diff --git a/src/view/com/composer/useExternalLinkFetch.ts b/src/view/com/composer/useExternalLinkFetch.ts index d51dec42b..2e0297a47 100644 --- a/src/view/com/composer/useExternalLinkFetch.ts +++ b/src/view/com/composer/useExternalLinkFetch.ts @@ -31,7 +31,7 @@ export function useExternalLinkFetch({ ) const getPost = useGetPost() const fetchDid = useFetchDid() - const {getAgent} = useAgent() + const agent = useAgent() useEffect(() => { let aborted = false @@ -59,7 +59,7 @@ export function useExternalLinkFetch({ }, ) } else if (isBskyCustomFeedUrl(extLink.uri)) { - getFeedAsEmbed(getAgent(), fetchDid, extLink.uri).then( + getFeedAsEmbed(agent, fetchDid, extLink.uri).then( ({embed, meta}) => { if (aborted) { return @@ -77,7 +77,7 @@ export function useExternalLinkFetch({ }, ) } else if (isBskyListUrl(extLink.uri)) { - getListAsEmbed(getAgent(), fetchDid, extLink.uri).then( + getListAsEmbed(agent, fetchDid, extLink.uri).then( ({embed, meta}) => { if (aborted) { return @@ -95,7 +95,7 @@ export function useExternalLinkFetch({ }, ) } else { - getLinkMeta(getAgent(), extLink.uri).then(meta => { + getLinkMeta(agent, extLink.uri).then(meta => { if (aborted) { return } @@ -137,7 +137,7 @@ export function useExternalLinkFetch({ }) } return cleanup - }, [extLink, setQuote, getPost, fetchDid, getAgent]) + }, [extLink, setQuote, getPost, fetchDid, agent]) return {extLink, setExtLink} } diff --git a/src/view/com/modals/ChangeEmail.tsx b/src/view/com/modals/ChangeEmail.tsx index b940b2d6d..a214627e2 100644 --- a/src/view/com/modals/ChangeEmail.tsx +++ b/src/view/com/modals/ChangeEmail.tsx @@ -27,7 +27,7 @@ export const snapPoints = ['90%'] export function Component() { const pal = usePalette('default') const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const {_} = useLingui() const [stage, setStage] = useState<Stages>(Stages.InputEmail) const [email, setEmail] = useState<string>(currentAccount?.email || '') @@ -45,12 +45,12 @@ export function Component() { setError('') setIsProcessing(true) try { - const res = await getAgent().com.atproto.server.requestEmailUpdate() + const res = await agent.com.atproto.server.requestEmailUpdate() if (res.data.tokenRequired) { setStage(Stages.ConfirmCode) } else { - await getAgent().com.atproto.server.updateEmail({email: email.trim()}) - await getAgent().resumeSession(getAgent().session!) + await agent.com.atproto.server.updateEmail({email: email.trim()}) + await agent.resumeSession(agent.session!) Toast.show(_(msg`Email updated`)) setStage(Stages.Done) } @@ -75,11 +75,11 @@ export function Component() { setError('') setIsProcessing(true) try { - await getAgent().com.atproto.server.updateEmail({ + await agent.com.atproto.server.updateEmail({ email: email.trim(), token: confirmationCode.trim(), }) - await getAgent().resumeSession(getAgent().session!) + await agent.resumeSession(agent.session!) Toast.show(_(msg`Email updated`)) setStage(Stages.Done) } catch (e) { diff --git a/src/view/com/modals/ChangeHandle.tsx b/src/view/com/modals/ChangeHandle.tsx index 52eb51031..f2094ed75 100644 --- a/src/view/com/modals/ChangeHandle.tsx +++ b/src/view/com/modals/ChangeHandle.tsx @@ -35,12 +35,12 @@ export type Props = {onChanged: () => void} export function Component(props: Props) { const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const { isLoading, data: serviceInfo, error: serviceInfoError, - } = useServiceQuery(getAgent().service.toString()) + } = useServiceQuery(agent.service.toString()) return isLoading || !currentAccount ? ( <View style={{padding: 18}}> @@ -71,7 +71,7 @@ export function Inner({ const {closeModal} = useModalControls() const {mutateAsync: updateHandle, isPending: isUpdateHandlePending} = useUpdateHandleMutation() - const {getAgent} = useAgent() + const agent = useAgent() const [error, setError] = useState<string>('') @@ -111,7 +111,7 @@ export function Inner({ await updateHandle({ handle: newHandle, }) - await getAgent().resumeSession(getAgent().session!) + await agent.resumeSession(agent.session!) closeModal() onChanged() } catch (err: any) { @@ -129,7 +129,7 @@ export function Inner({ closeModal, updateHandle, serviceInfo, - getAgent, + agent, ]) // rendering diff --git a/src/view/com/modals/ChangePassword.tsx b/src/view/com/modals/ChangePassword.tsx index 3ce7306b9..196715b49 100644 --- a/src/view/com/modals/ChangePassword.tsx +++ b/src/view/com/modals/ChangePassword.tsx @@ -37,7 +37,7 @@ export const snapPoints = isAndroid ? ['90%'] : ['45%'] export function Component() { const pal = usePalette('default') const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const {_} = useLingui() const [stage, setStage] = useState<Stages>(Stages.RequestCode) const [isProcessing, setIsProcessing] = useState<boolean>(false) @@ -46,7 +46,6 @@ export function Component() { const [error, setError] = useState<string>('') const {isMobile} = useWebMediaQueries() const {closeModal} = useModalControls() - const agent = getAgent() const onRequestCode = async () => { if ( diff --git a/src/view/com/modals/CreateOrEditList.tsx b/src/view/com/modals/CreateOrEditList.tsx index 2dff636af..2ea34e808 100644 --- a/src/view/com/modals/CreateOrEditList.tsx +++ b/src/view/com/modals/CreateOrEditList.tsx @@ -62,7 +62,7 @@ export function Component({ const {_} = useLingui() const listCreateMutation = useListCreateMutation() const listMetadataMutation = useListMetadataMutation() - const {getAgent} = useAgent() + const agent = useAgent() const activePurpose = useMemo(() => { if (list?.purpose) { @@ -157,7 +157,7 @@ export function Component({ {cleanNewlines: true}, ) - await richText.detectFacets(getAgent()) + await richText.detectFacets(agent) richText = shortenLinks(richText) // filter out any mention facets that didn't map to a user @@ -229,7 +229,7 @@ export function Component({ listMetadataMutation, listCreateMutation, _, - getAgent, + agent, ]) return ( diff --git a/src/view/com/modals/DeleteAccount.tsx b/src/view/com/modals/DeleteAccount.tsx index cab5dc289..06f1e111a 100644 --- a/src/view/com/modals/DeleteAccount.tsx +++ b/src/view/com/modals/DeleteAccount.tsx @@ -31,7 +31,7 @@ export function Component({}: {}) { const pal = usePalette('default') const theme = useTheme() const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const {removeAccount} = useSessionApi() const {_} = useLingui() const {closeModal} = useModalControls() @@ -45,7 +45,7 @@ export function Component({}: {}) { setError('') setIsProcessing(true) try { - await getAgent().com.atproto.server.requestAccountDelete() + await agent.com.atproto.server.requestAccountDelete() setIsEmailSent(true) } catch (e: any) { setError(cleanError(e)) @@ -63,7 +63,7 @@ export function Component({}: {}) { try { // inform chat service of intent to delete account - const {success} = await getAgent().api.chat.bsky.actor.deleteAccount( + const {success} = await agent.api.chat.bsky.actor.deleteAccount( undefined, { headers: DM_SERVICE_HEADERS, @@ -72,7 +72,7 @@ export function Component({}: {}) { if (!success) { throw new Error('Failed to inform chat service of account deletion') } - await getAgent().com.atproto.server.deleteAccount({ + await agent.com.atproto.server.deleteAccount({ did: currentAccount.did, password, token, diff --git a/src/view/com/modals/VerifyEmail.tsx b/src/view/com/modals/VerifyEmail.tsx index 3fdde330d..7c1146a01 100644 --- a/src/view/com/modals/VerifyEmail.tsx +++ b/src/view/com/modals/VerifyEmail.tsx @@ -41,7 +41,7 @@ export function Component({ onSuccess?: () => void }) { const pal = usePalette('default') - const {getAgent} = useAgent() + const agent = useAgent() const {currentAccount} = useSession() const {_} = useLingui() const [stage, setStage] = useState<Stages>( @@ -64,7 +64,7 @@ export function Component({ setError('') setIsProcessing(true) try { - await getAgent().com.atproto.server.requestEmailConfirmation() + await agent.com.atproto.server.requestEmailConfirmation() setStage(Stages.ConfirmCode) } catch (e) { setError(cleanError(String(e))) @@ -77,11 +77,11 @@ export function Component({ setError('') setIsProcessing(true) try { - await getAgent().com.atproto.server.confirmEmail({ + await agent.com.atproto.server.confirmEmail({ email: (currentAccount?.email || '').trim(), token: confirmationCode.trim(), }) - await getAgent().resumeSession(getAgent().session!) + await agent.resumeSession(agent.session!) Toast.show(_(msg`Email verified`)) closeModal() onSuccess?.() diff --git a/src/view/screens/Profile.tsx b/src/view/screens/Profile.tsx index 4fa46a4cf..734230c6c 100644 --- a/src/view/screens/Profile.tsx +++ b/src/view/screens/Profile.tsx @@ -470,7 +470,7 @@ function ProfileScreenLoaded({ } function useRichText(text: string): [RichTextAPI, boolean] { - const {getAgent} = useAgent() + const agent = useAgent() const [prevText, setPrevText] = React.useState(text) const [rawRT, setRawRT] = React.useState(() => new RichTextAPI({text})) const [resolvedRT, setResolvedRT] = React.useState<RichTextAPI | null>(null) @@ -485,7 +485,7 @@ function useRichText(text: string): [RichTextAPI, boolean] { async function resolveRTFacets() { // new each time const resolvedRT = new RichTextAPI({text}) - await resolvedRT.detectFacets(getAgent()) + await resolvedRT.detectFacets(agent) if (!ignore) { setResolvedRT(resolvedRT) } @@ -494,7 +494,7 @@ function useRichText(text: string): [RichTextAPI, boolean] { return () => { ignore = true } - }, [text, getAgent]) + }, [text, agent]) const isResolving = resolvedRT === null return [resolvedRT ?? rawRT, isResolving] } diff --git a/src/view/screens/Settings/DisableEmail2FADialog.tsx b/src/view/screens/Settings/DisableEmail2FADialog.tsx index b52dcc7a3..a27cff9a3 100644 --- a/src/view/screens/Settings/DisableEmail2FADialog.tsx +++ b/src/view/screens/Settings/DisableEmail2FADialog.tsx @@ -30,7 +30,7 @@ export function DisableEmail2FADialog({ const t = useTheme() const {gtMobile} = useBreakpoints() const {currentAccount} = useSession() - const {getAgent} = useAgent() + const agent = useAgent() const [stage, setStage] = useState<Stages>(Stages.Email) const [confirmationCode, setConfirmationCode] = useState<string>('') @@ -41,7 +41,7 @@ export function DisableEmail2FADialog({ setError('') setIsProcessing(true) try { - await getAgent().com.atproto.server.requestEmailUpdate() + await agent.com.atproto.server.requestEmailUpdate() setStage(Stages.ConfirmCode) } catch (e) { setError(cleanError(String(e))) @@ -55,12 +55,12 @@ export function DisableEmail2FADialog({ setIsProcessing(true) try { if (currentAccount?.email) { - await getAgent().com.atproto.server.updateEmail({ + await agent.com.atproto.server.updateEmail({ email: currentAccount!.email, token: confirmationCode.trim(), emailAuthFactor: false, }) - await getAgent().resumeSession(getAgent().session!) + await agent.resumeSession(agent.session!) Toast.show(_(msg`Email 2FA disabled`)) } control.close() diff --git a/src/view/screens/Settings/Email2FAToggle.tsx b/src/view/screens/Settings/Email2FAToggle.tsx index efeb7e4d7..b5e7adddb 100644 --- a/src/view/screens/Settings/Email2FAToggle.tsx +++ b/src/view/screens/Settings/Email2FAToggle.tsx @@ -13,17 +13,17 @@ export function Email2FAToggle() { const {currentAccount} = useSession() const {openModal} = useModalControls() const disableDialogCtrl = useDialogControl() - const {getAgent} = useAgent() + const agent = useAgent() const enableEmailAuthFactor = React.useCallback(async () => { if (currentAccount?.email) { - await getAgent().com.atproto.server.updateEmail({ + await agent.com.atproto.server.updateEmail({ email: currentAccount.email, emailAuthFactor: true, }) - await getAgent().resumeSession(getAgent().session!) + await agent.resumeSession(agent.session!) } - }, [currentAccount, getAgent]) + }, [currentAccount, agent]) const onToggle = React.useCallback(() => { if (!currentAccount) { diff --git a/src/view/screens/Settings/ExportCarDialog.tsx b/src/view/screens/Settings/ExportCarDialog.tsx index af835cb62..72d943bcf 100644 --- a/src/view/screens/Settings/ExportCarDialog.tsx +++ b/src/view/screens/Settings/ExportCarDialog.tsx @@ -21,11 +21,10 @@ export function ExportCarDialog({ }) { const {_} = useLingui() const t = useTheme() - const {getAgent} = useAgent() + const agent = useAgent() const [loading, setLoading] = React.useState(false) const download = React.useCallback(async () => { - const agent = getAgent() if (!agent.session) { return // shouldnt ever happen } @@ -49,7 +48,7 @@ export function ExportCarDialog({ setLoading(false) control.close() } - }, [_, control, getAgent]) + }, [_, control, agent]) return ( <Dialog.Outer control={control}> |