Fakultas Ilmu Komputer UI

index.ts 1.35 KB
Newer Older
1
import { PermissionsAndroid } from 'react-native';
2
3
import RNFetchBlob from 'rn-fetch-blob';
import { FileType } from './schema';
4
import Toast from 'react-native-toast-message';
5

6
7
8
9
10
11
const useDownloadFiles = (
  url = '',
  title = '',
  fileType: FileType,
  fileTitle?: string,
) => {
12
  const fileName = fileTitle ? fileTitle : url?.split('/').pop();
13
14
15
16
17
18
19
20
21
22
23
24
25
  const extension = fileName?.split('.').pop()?.toUpperCase() || '-';

  const askWritePermission = async () =>
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    );

  const download = async (): Promise<any> => {
    const granted = await askWritePermission();
    if (!granted) {
      return;
    }

26
27
28
29
30
31
    Toast.show({
      type: 'success',
      text1: `Mengunduh ${fileName}...`,
      text2: 'Notifikasi akan muncul setelah unduh selesai. Mohon menunggu.',
    });

32
33
34
35
36
37
    const dirs = RNFetchBlob.fs.dirs;
    RNFetchBlob.config({
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        mime: fileType,
38
        title: title || fileName,
39
40
41
42
43
44
45
        mediaScannable: true,
        path: dirs.DownloadDir + `/${fileName}`,
      },
    })
      .fetch('GET', url)
      .then((res) => res.path())
      .catch((err) => console.log(err));
46
47
48
49
50
51
52
53
54
55
  };

  return {
    fileName,
    extension,
    download,
  };
};

export default useDownloadFiles;