about summary refs log tree commit diff
path: root/src/state/geolocation.tsx
blob: 4581996a095ea0087e4e362811e37ebdd6b4bd2c (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
import React from 'react'
import EventEmitter from 'eventemitter3'

import {networkRetry} from '#/lib/async/retry'
import {logger} from '#/logger'
import {type Device, device} from '#/storage'

const events = new EventEmitter()
const EVENT = 'geolocation-updated'
const emitGeolocationUpdate = (geolocation: Device['geolocation']) => {
  events.emit(EVENT, geolocation)
}
const onGeolocationUpdate = (
  listener: (geolocation: Device['geolocation']) => void,
) => {
  events.on(EVENT, listener)
  return () => {
    events.off(EVENT, listener)
  }
}

/**
 * Default geolocation value. IF undefined, we fail closed and apply all
 * additional mod authorities.
 */
export const DEFAULT_GEOLOCATION: Device['geolocation'] = {
  countryCode: undefined,
  isAgeRestrictedGeo: false,
}

async function getGeolocation(): Promise<Device['geolocation']> {
  const res = await fetch(`https://bsky.app/ipcc`)

  if (!res.ok) {
    throw new Error(`geolocation: lookup failed ${res.status}`)
  }

  const json = await res.json()

  if (json.countryCode) {
    return {
      countryCode: json.countryCode,
      isAgeRestrictedGeo: json.isAgeRestrictedGeo ?? false,
    }
  } else {
    return undefined
  }
}

/**
 * Local promise used within this file only.
 */
let geolocationResolution: Promise<{success: boolean}> | undefined

/**
 * Begin the process of resolving geolocation. This should be called once at
 * app start.
 *
 * THIS METHOD SHOULD NEVER THROW.
 *
 * This method is otherwise not used for any purpose. To ensure geolocation is
 * resolved, use {@link ensureGeolocationResolved}
 */
export function beginResolveGeolocation() {
  /**
   * In dev, IP server is unavailable, so we just set the default geolocation
   * and fail closed.
   */
  if (__DEV__) {
    geolocationResolution = new Promise(y => y({success: true}))
    if (!device.get(['geolocation'])) {
      device.set(['geolocation'], DEFAULT_GEOLOCATION)
    }
    return
  }

  geolocationResolution = new Promise(async resolve => {
    let success = true

    try {
      // Try once, fail fast
      const geolocation = await getGeolocation()
      if (geolocation) {
        device.set(['geolocation'], geolocation)
        emitGeolocationUpdate(geolocation)
        logger.debug(`geolocation: success`, {geolocation})
      } else {
        // endpoint should throw on all failures, this is insurance
        throw new Error(`geolocation: nothing returned from initial request`)
      }
    } catch (e: any) {
      success = false

      logger.debug(`geolocation: failed initial request`, {
        safeMessage: e.message,
      })

      // set to default
      device.set(['geolocation'], DEFAULT_GEOLOCATION)

      // retry 3 times, but don't await, proceed with default
      networkRetry(3, getGeolocation)
        .then(geolocation => {
          if (geolocation) {
            device.set(['geolocation'], geolocation)
            emitGeolocationUpdate(geolocation)
            logger.debug(`geolocation: success`, {geolocation})
            success = true
          } else {
            // endpoint should throw on all failures, this is insurance
            throw new Error(`geolocation: nothing returned from retries`)
          }
        })
        .catch((e: any) => {
          // complete fail closed
          logger.debug(`geolocation: failed retries`, {safeMessage: e.message})
        })
    } finally {
      resolve({success})
    }
  })
}

/**
 * Ensure that geolocation has been resolved, or at the very least attempted
 * once. Subsequent retries will not be captured by this `await`. Those will be
 * reported via {@link events}.
 */
export async function ensureGeolocationResolved() {
  if (!geolocationResolution) {
    throw new Error(`geolocation: beginResolveGeolocation not called yet`)
  }

  const cached = device.get(['geolocation'])
  if (cached) {
    logger.debug(`geolocation: using cache`, {cached})
  } else {
    logger.debug(`geolocation: no cache`)
    const {success} = await geolocationResolution
    if (success) {
      logger.debug(`geolocation: resolved`, {
        resolved: device.get(['geolocation']),
      })
    } else {
      logger.error(`geolocation: failed to resolve`)
    }
  }
}

type Context = {
  geolocation: Device['geolocation']
}

const context = React.createContext<Context>({
  geolocation: DEFAULT_GEOLOCATION,
})
context.displayName = 'GeolocationContext'

export function Provider({children}: {children: React.ReactNode}) {
  const [geolocation, setGeolocation] = React.useState(() => {
    const initial = device.get(['geolocation']) || DEFAULT_GEOLOCATION
    return initial
  })

  React.useEffect(() => {
    return onGeolocationUpdate(geolocation => {
      setGeolocation(geolocation!)
    })
  }, [])

  const ctx = React.useMemo(() => {
    return {
      geolocation,
    }
  }, [geolocation])

  return <context.Provider value={ctx}>{children}</context.Provider>
}

export function useGeolocation() {
  return React.useContext(context)
}