forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {Platform} from 'react-native'
2import {type AppBskyAgeassuranceBegin, AtpAgent} from '@atproto/api'
3import {useMutation} from '@tanstack/react-query'
4
5import {wait} from '#/lib/async/wait'
6import {
7 DEV_ENV_APPVIEW,
8 PUBLIC_APPVIEW,
9 PUBLIC_APPVIEW_DID,
10} from '#/lib/constants'
11import {isNetworkError} from '#/lib/hooks/useCleanError'
12import {useAgent} from '#/state/session'
13import {usePatchAgeAssuranceServerState} from '#/ageAssurance'
14import {logger} from '#/ageAssurance/logger'
15import {useAnalytics} from '#/analytics'
16import {BLUESKY_PROXY_DID} from '#/env'
17import {useGeolocation} from '#/geolocation'
18
19const IS_DEV_ENV = BLUESKY_PROXY_DID !== PUBLIC_APPVIEW_DID
20const APPVIEW = IS_DEV_ENV ? DEV_ENV_APPVIEW : PUBLIC_APPVIEW
21
22export function useBeginAgeAssurance() {
23 const ax = useAnalytics()
24 const agent = useAgent()
25 const geolocation = useGeolocation()
26 const patchAgeAssuranceStateResponse = usePatchAgeAssuranceServerState()
27
28 return useMutation({
29 async mutationFn(
30 props: Omit<
31 AppBskyAgeassuranceBegin.InputSchema,
32 'countryCode' | 'regionCode'
33 >,
34 ) {
35 const countryCode = geolocation?.countryCode?.toUpperCase()
36 const regionCode = geolocation?.regionCode?.toUpperCase()
37 if (!countryCode) {
38 throw new Error(`Geolocation not available, cannot init age assurance.`)
39 }
40
41 const {
42 data: {token},
43 } = await agent.com.atproto.server.getServiceAuth({
44 aud: BLUESKY_PROXY_DID,
45 lxm: `app.bsky.ageassurance.begin`,
46 })
47
48 const appView = new AtpAgent({service: APPVIEW})
49 appView.sessionManager.session = {...agent.session!}
50 appView.sessionManager.session.accessJwt = token
51 appView.sessionManager.session.refreshJwt = ''
52
53 ax.metric('ageAssurance:api:begin', {
54 platform: Platform.OS,
55 countryCode,
56 regionCode,
57 })
58
59 /*
60 * 2s wait is good actually. Email sending takes a hot sec and this helps
61 * ensure the email is ready for the user once they open their inbox.
62 */
63 const {data} = await wait(
64 2e3,
65 appView.app.bsky.ageassurance.begin({
66 ...props,
67 countryCode,
68 regionCode,
69 }),
70 )
71
72 // Just keeps this in sync, not necessarily used right now
73 patchAgeAssuranceStateResponse(data)
74 },
75 onError(e) {
76 if (!isNetworkError(e)) {
77 logger.error(`useBeginAgeAssurance failed`, {
78 safeMessage: e,
79 })
80 }
81 },
82 })
83}