17782: Fixes 'array-callback-return' compile warnings.
[arvados-workbench2.git] / src / views-components / context-menu / actions / download-action.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import { ListItemIcon, ListItemText, ListItem } from '@material-ui/core';
7 import { DownloadIcon } from '../../../components/icon/icon';
8 import JSZip from 'jszip';
9 import FileSaver from 'file-saver';
10 import axios from 'axios';
11
12 export const DownloadAction = (props: { href?: any, download?: any, onClick?: () => void, kind?: string, currentCollectionUuid?: string; }) => {
13     const downloadProps = props.download ? { download: props.download } : {};
14
15     const createZip = (fileUrls: string[], download: string[]) => {
16         let id = 1;
17         const zip = new JSZip();
18         const filteredFileUrls = fileUrls
19             .filter((href: string) => {
20                 const letter = href.split('').pop();
21                 return letter !== '/';
22             });
23
24         filteredFileUrls.forEach((href: string) => {
25             axios.get(href).then(response => response).then(({ data }: any) => {
26                 const splittedByDot = href.split('.');
27                 if (splittedByDot[splittedByDot.length - 1] !== 'json') {
28                     if (filteredFileUrls.length === id) {
29                         zip.file(download[id - 1], data);
30                         zip.generateAsync({ type: 'blob' }).then((content) => {
31                             FileSaver.saveAs(content, `download-${props.currentCollectionUuid}.zip`);
32                         });
33                     } else {
34                         zip.file(download[id - 1], data);
35                         zip.generateAsync({ type: 'blob' });
36                     }
37                 } else {
38                     zip.file(download[id - 1], JSON.stringify(data));
39                     zip.generateAsync({ type: 'blob' });
40                 }
41                 id++;
42             });
43         });
44     };
45
46     return props.href || props.kind === 'files'
47         ? <a
48             style={{ textDecoration: 'none' }}
49             href={props.kind === 'files' ? undefined : `${props.href}&disposition=attachment`}
50             onClick={props.onClick}
51             {...downloadProps}>
52             <ListItem button onClick={() => props.kind === 'files' ? createZip(props.href, props.download) : undefined}>
53                 {props.kind !== 'files' ?
54                     <ListItemIcon>
55                         <DownloadIcon />
56                     </ListItemIcon> : <span />}
57                 <ListItemText>
58                     {props.kind === 'files' ? 'Download selected' : 'Download'}
59                 </ListItemText>
60             </ListItem>
61         </a>
62         : null;
63 };