about summary refs log tree commit diff
path: root/src/state/queries/suggested-follows.ts
blob: 5b5e142ca78b411d38030ecc8abdd796e97c7aa0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import {
  AppBskyActorGetSuggestions,
  AppBskyGraphGetSuggestedFollowsByActor,
  moderateProfile,
} from '@atproto/api'
import {
  useInfiniteQuery,
  useMutation,
  useQuery,
  InfiniteData,
  QueryKey,
} from '@tanstack/react-query'

import {useSession} from '#/state/session'
import {useModerationOpts} from '#/state/queries/preferences'

const suggestedFollowsQueryKey = ['suggested-follows']
const suggestedFollowsByActorQuery = (did: string) => [
  'suggested-follows-by-actor',
  did,
]

export function useSuggestedFollowsQuery() {
  const {agent, currentAccount} = useSession()
  const moderationOpts = useModerationOpts()

  return useInfiniteQuery<
    AppBskyActorGetSuggestions.OutputSchema,
    Error,
    InfiniteData<AppBskyActorGetSuggestions.OutputSchema>,
    QueryKey,
    string | undefined
  >({
    enabled: !!moderationOpts,
    queryKey: suggestedFollowsQueryKey,
    queryFn: async ({pageParam}) => {
      const res = await agent.app.bsky.actor.getSuggestions({
        limit: 25,
        cursor: pageParam,
      })

      res.data.actors = res.data.actors
        .filter(
          actor => !moderateProfile(actor, moderationOpts!).account.filter,
        )
        .filter(actor => {
          const viewer = actor.viewer
          if (viewer) {
            if (
              viewer.following ||
              viewer.muted ||
              viewer.mutedByList ||
              viewer.blockedBy ||
              viewer.blocking
            ) {
              return false
            }
          }
          if (actor.did === currentAccount?.did) {
            return false
          }
          return true
        })

      return res.data
    },
    initialPageParam: undefined,
    getNextPageParam: lastPage => lastPage.cursor,
  })
}

export function useSuggestedFollowsByActorQuery({did}: {did: string}) {
  const {agent} = useSession()

  return useQuery<AppBskyGraphGetSuggestedFollowsByActor.OutputSchema, Error>({
    queryKey: suggestedFollowsByActorQuery(did),
    queryFn: async () => {
      const res = await agent.app.bsky.graph.getSuggestedFollowsByActor({
        actor: did,
      })
      return res.data
    },
  })
}

// TODO: Delete and replace usages with the one above.
export function useGetSuggestedFollowersByActor() {
  const {agent} = useSession()

  return useMutation({
    mutationFn: async (actor: string) => {
      const res = await agent.app.bsky.graph.getSuggestedFollowsByActor({
        actor: actor,
      })

      return res.data
    },
  })
}