about summary refs log tree commit diff
path: root/src/state/queries/list.ts
blob: ef05009d1743c362b207197587f0b1bdccc8ce6d (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {
  AtUri,
  AppBskyGraphGetList,
  AppBskyGraphList,
  AppBskyGraphDefs,
  BskyAgent,
} from '@atproto/api'
import {Image as RNImage} from 'react-native-image-crop-picker'
import {useQuery, useMutation, useQueryClient} from '@tanstack/react-query'
import chunk from 'lodash.chunk'
import {useSession, getAgent} from '../session'
import {invalidate as invalidateMyLists} from './my-lists'
import {RQKEY as PROFILE_LISTS_RQKEY} from './profile-lists'
import {uploadBlob} from '#/lib/api'
import {until} from '#/lib/async/until'
import {STALE} from '#/state/queries'

export const RQKEY = (uri: string) => ['list', uri]

export function useListQuery(uri?: string) {
  return useQuery<AppBskyGraphDefs.ListView, Error>({
    staleTime: STALE.MINUTES.ONE,
    queryKey: RQKEY(uri || ''),
    async queryFn() {
      if (!uri) {
        throw new Error('URI not provided')
      }
      const res = await getAgent().app.bsky.graph.getList({
        list: uri,
        limit: 1,
      })
      return res.data.list
    },
    enabled: !!uri,
  })
}

export interface ListCreateMutateParams {
  purpose: string
  name: string
  description: string
  avatar: RNImage | null | undefined
}
export function useListCreateMutation() {
  const {currentAccount} = useSession()
  const queryClient = useQueryClient()
  return useMutation<{uri: string; cid: string}, Error, ListCreateMutateParams>(
    {
      async mutationFn({purpose, name, description, avatar}) {
        if (!currentAccount) {
          throw new Error('Not logged in')
        }
        if (
          purpose !== 'app.bsky.graph.defs#curatelist' &&
          purpose !== 'app.bsky.graph.defs#modlist'
        ) {
          throw new Error('Invalid list purpose: must be curatelist or modlist')
        }
        const record: AppBskyGraphList.Record = {
          purpose,
          name,
          description,
          avatar: undefined,
          createdAt: new Date().toISOString(),
        }
        if (avatar) {
          const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime)
          record.avatar = blobRes.data.blob
        }
        const res = await getAgent().app.bsky.graph.list.create(
          {
            repo: currentAccount.did,
          },
          record,
        )

        // wait for the appview to update
        await whenAppViewReady(
          getAgent(),
          res.uri,
          (v: AppBskyGraphGetList.Response) => {
            return typeof v?.data?.list.uri === 'string'
          },
        )
        return res
      },
      onSuccess() {
        invalidateMyLists(queryClient)
        queryClient.invalidateQueries({
          queryKey: PROFILE_LISTS_RQKEY(currentAccount!.did),
        })
      },
    },
  )
}

export interface ListMetadataMutateParams {
  uri: string
  name: string
  description: string
  avatar: RNImage | null | undefined
}
export function useListMetadataMutation() {
  const {currentAccount} = useSession()
  const queryClient = useQueryClient()
  return useMutation<
    {uri: string; cid: string},
    Error,
    ListMetadataMutateParams
  >({
    async mutationFn({uri, name, description, avatar}) {
      const {hostname, rkey} = new AtUri(uri)
      if (!currentAccount) {
        throw new Error('Not logged in')
      }
      if (currentAccount.did !== hostname) {
        throw new Error('You do not own this list')
      }

      // get the current record
      const {value: record} = await getAgent().app.bsky.graph.list.get({
        repo: currentAccount.did,
        rkey,
      })

      // update the fields
      record.name = name
      record.description = description
      if (avatar) {
        const blobRes = await uploadBlob(getAgent(), avatar.path, avatar.mime)
        record.avatar = blobRes.data.blob
      } else if (avatar === null) {
        record.avatar = undefined
      }
      const res = (
        await getAgent().com.atproto.repo.putRecord({
          repo: currentAccount.did,
          collection: 'app.bsky.graph.list',
          rkey,
          record,
        })
      ).data

      // wait for the appview to update
      await whenAppViewReady(
        getAgent(),
        res.uri,
        (v: AppBskyGraphGetList.Response) => {
          const list = v.data.list
          return (
            list.name === record.name && list.description === record.description
          )
        },
      )
      return res
    },
    onSuccess(data, variables) {
      invalidateMyLists(queryClient)
      queryClient.invalidateQueries({
        queryKey: PROFILE_LISTS_RQKEY(currentAccount!.did),
      })
      queryClient.invalidateQueries({
        queryKey: RQKEY(variables.uri),
      })
    },
  })
}

export function useListDeleteMutation() {
  const {currentAccount} = useSession()
  const queryClient = useQueryClient()
  return useMutation<void, Error, {uri: string}>({
    mutationFn: async ({uri}) => {
      if (!currentAccount) {
        return
      }
      // fetch all the listitem records that belong to this list
      let cursor
      let listitemRecordUris: string[] = []
      for (let i = 0; i < 100; i++) {
        const res = await getAgent().app.bsky.graph.listitem.list({
          repo: currentAccount.did,
          cursor,
          limit: 100,
        })
        listitemRecordUris = listitemRecordUris.concat(
          res.records
            .filter(record => record.value.list === uri)
            .map(record => record.uri),
        )
        cursor = res.cursor
        if (!cursor) {
          break
        }
      }

      // batch delete the list and listitem records
      const createDel = (uri: string) => {
        const urip = new AtUri(uri)
        return {
          $type: 'com.atproto.repo.applyWrites#delete',
          collection: urip.collection,
          rkey: urip.rkey,
        }
      }
      const writes = listitemRecordUris
        .map(uri => createDel(uri))
        .concat([createDel(uri)])

      // apply in chunks
      for (const writesChunk of chunk(writes, 10)) {
        await getAgent().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
        },
      )
    },
    onSuccess() {
      invalidateMyLists(queryClient)
      queryClient.invalidateQueries({
        queryKey: PROFILE_LISTS_RQKEY(currentAccount!.did),
      })
      // TODO!! /* dont await */ this.rootStore.preferences.removeSavedFeed(this.uri)
    },
  })
}

export function useListMuteMutation() {
  const queryClient = useQueryClient()
  return useMutation<void, Error, {uri: string; mute: boolean}>({
    mutationFn: async ({uri, mute}) => {
      if (mute) {
        await getAgent().muteModList(uri)
      } else {
        await getAgent().unmuteModList(uri)
      }
    },
    onSuccess(data, variables) {
      queryClient.invalidateQueries({
        queryKey: RQKEY(variables.uri),
      })
    },
  })
}

export function useListBlockMutation() {
  const queryClient = useQueryClient()
  return useMutation<void, Error, {uri: string; block: boolean}>({
    mutationFn: async ({uri, block}) => {
      if (block) {
        await getAgent().blockModList(uri)
      } else {
        await getAgent().unblockModList(uri)
      }
    },
    onSuccess(data, variables) {
      queryClient.invalidateQueries({
        queryKey: RQKEY(variables.uri),
      })
    },
  })
}

async function whenAppViewReady(
  agent: BskyAgent,
  uri: string,
  fn: (res: AppBskyGraphGetList.Response) => boolean,
) {
  await until(
    5, // 5 tries
    1e3, // 1s delay between tries
    fn,
    () =>
      agent.app.bsky.graph.getList({
        list: uri,
        limit: 1,
      }),
  )
}