Fakultas Ilmu Komputer UI

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

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

25
26
27
28
29
30
31
32
33
34
35
36
37
38
    const dirs = RNFetchBlob.fs.dirs;
    RNFetchBlob.config({
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        mime: fileType,
        title: 'Downloading ' + title + '...',
        mediaScannable: true,
        path: dirs.DownloadDir + `/${fileName}`,
      },
    })
      .fetch('GET', url)
      .then((res) => res.path())
      .catch((err) => console.log(err));
39
40
41
42
43
44
45
46
47
48
49
  };

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

export default useDownloadFiles;