about summary refs log tree commit diff
path: root/src/lib/media/save-image.ts
blob: 47955b15cc0778583f6927a975c711da60341b0d (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
import {useCallback} from 'react'
import * as MediaLibrary from 'expo-media-library'
import {t} from '@lingui/macro'

import {isNative} from '#/platform/detection'
import * as Toast from '#/view/com/util/Toast'
import {saveImageToMediaLibrary} from './manip'

/**
 * Same as `saveImageToMediaLibrary`, but also handles permissions and toasts
 */
export function useSaveImageToMediaLibrary() {
  const [permissionResponse, requestPermission, getPermission] =
    MediaLibrary.usePermissions({
      granularPermissions: ['photo'],
    })
  return useCallback(
    async (uri: string) => {
      if (!isNative) {
        throw new Error('useSaveImageToMediaLibrary is native only')
      }

      async function save() {
        try {
          await saveImageToMediaLibrary({uri})
          Toast.show(t`Image saved`)
        } catch (e: any) {
          Toast.show(t`Failed to save image: ${String(e)}`, 'xmark')
        }
      }

      const permission = permissionResponse ?? (await getPermission())

      if (permission.granted) {
        await save()
      } else {
        if (permission.canAskAgain) {
          // request again once
          const askAgain = await requestPermission()
          if (askAgain.granted) {
            await save()
          } else {
            // since we've been explicitly denied, show a toast.
            Toast.show(
              t`Images cannot be saved unless permission is granted to access your photo library.`,
              'xmark',
            )
          }
        } else {
          Toast.show(
            t`Permission to access your photo library was denied. Please enable it in your system settings.`,
            'xmark',
          )
        }
      }
    },
    [permissionResponse, requestPermission, getPermission],
  )
}