Fakultas Ilmu Komputer UI

index.ts 1.61 KB
Newer Older
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
import { downloadFile, DocumentDirectoryPath } from 'react-native-fs';
import { Toast } from 'components/core';
import { PermissionsAndroid } from 'react-native';

const useDownloadFiles = (url: string) => {
  const fileName = url.split('/').pop();
  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;
    }

    const path = `${DocumentDirectoryPath}/${fileName}`;
    const response = await downloadFile({
      fromUrl: url,
      toFile: path,
    });
    return response.promise
      .then((res) => {
        if (res.statusCode === 200 && res.bytesWritten > 0) {
          Toast.show({
            type: 'success',
            text1: `${extension} berhasil diunduh.`,
            text2: `Silakan lihat file ${fileName} dalam penyimpanan HP Anda.`,
          });
          return {
            success: true,
            data: `file://${path}`,
          };
        } else {
          Toast.show({
            type: 'error',
            text1: `${extension} gagal diunduh.`,
            text2: 'Terjadi kesalahan pada sisi kami.',
          });
          return {
            success: false,
            error: res,
          };
        }
      })
      .catch(console.log);
  };

  return {
    fileName,
    extension,
    download,
    pdfViewUrl: `http://docs.google.com/gview?embedded=true&url=${url}`,
  };
};

export default useDownloadFiles;