about summary refs log tree commit diff
path: root/src/lib/permissions.ts
blob: ab2c73ca6c7aa57442046614b9e68236d74ea321 (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
import {Alert} from 'react-native'
import {
  check,
  openSettings,
  Permission,
  PermissionStatus,
  PERMISSIONS,
  RESULTS,
} from 'react-native-permissions'

export const PHOTO_LIBRARY = PERMISSIONS.IOS.PHOTO_LIBRARY
export const CAMERA = PERMISSIONS.IOS.CAMERA

/**
 * Returns `true` if the user has granted permission or hasn't made
 * a decision yet. Returns `false` if unavailable or not granted.
 */
export async function hasAccess(perm: Permission): Promise<boolean> {
  const status = await check(perm)
  return isntANo(status)
}

export async function requestAccessIfNeeded(
  perm: Permission,
): Promise<boolean> {
  if (await hasAccess(perm)) {
    return true
  }
  let permDescription
  if (perm === PHOTO_LIBRARY) {
    permDescription = 'photo library'
  } else if (perm === CAMERA) {
    permDescription = 'camera'
  } else {
    return false
  }
  Alert.alert(
    'Permission needed',
    `Bluesky does not have permission to access your ${permDescription}.`,
    [
      {
        text: 'Cancel',
        style: 'cancel',
      },
      {text: 'Open Settings', onPress: () => openSettings()},
    ],
  )
  return false
}

export async function requestPhotoAccessIfNeeded() {
  return requestAccessIfNeeded(PHOTO_LIBRARY)
}

export async function requestCameraAccessIfNeeded() {
  return requestAccessIfNeeded(CAMERA)
}

function isntANo(status: PermissionStatus): boolean {
  return status !== RESULTS.UNAVAILABLE && status !== RESULTS.BLOCKED
}