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