about summary refs log tree commit diff
path: root/src/components/hooks/useStarterPackEntry.native.ts
blob: b6e4ab05b1c7f6092e2710865ccbd9deab8a60d2 (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
import React from 'react'

import {
  createStarterPackLinkFromAndroidReferrer,
  httpStarterPackUriToAtUri,
} from 'lib/strings/starter-pack'
import {isAndroid} from 'platform/detection'
import {useHasCheckedForStarterPack} from 'state/preferences/used-starter-packs'
import {useSetActiveStarterPack} from 'state/shell/starter-pack'
import {DevicePrefs, Referrer} from '../../../modules/expo-bluesky-swiss-army'

export function useStarterPackEntry() {
  const [ready, setReady] = React.useState(false)
  const setActiveStarterPack = useSetActiveStarterPack()
  const hasCheckedForStarterPack = useHasCheckedForStarterPack()

  React.useEffect(() => {
    if (ready) return

    // On Android, we cannot clear the referral link. It gets stored for 90 days and all we can do is query for it. So,
    // let's just ensure we never check again after the first time.
    if (hasCheckedForStarterPack) {
      setReady(true)
      return
    }

    // Safety for Android. Very unlike this could happen, but just in case. The response should be nearly immediate
    const timeout = setTimeout(() => {
      setReady(true)
    }, 500)

    ;(async () => {
      let uri: string | null | undefined

      if (isAndroid) {
        const res = await Referrer.getGooglePlayReferrerInfoAsync()

        if (res && res.installReferrer) {
          uri = createStarterPackLinkFromAndroidReferrer(res.installReferrer)
        }
      } else {
        const res = await DevicePrefs.getStringValueAsync(
          'starterPackUri',
          true,
        )

        if (res) {
          uri = httpStarterPackUriToAtUri(res)
          DevicePrefs.setStringValueAsync('starterPackUri', null, true)
        }
      }

      if (uri) {
        setActiveStarterPack({
          uri,
        })
      }

      setReady(true)
    })()

    return () => {
      clearTimeout(timeout)
    }
  }, [ready, setActiveStarterPack, hasCheckedForStarterPack])

  return ready
}