17526: Use codesnippet component on webdav dialog wget command for monospace
[arvados-workbench2.git] / src / views-components / webdav-s3-dialog / webdav-s3-dialog.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 { Dialog, DialogActions, Button, StyleRulesCallback, WithStyles, withStyles, CardHeader, Tab, Tabs } from '@material-ui/core';
7 import { withDialog } from "store/dialog/with-dialog";
8 import { COLLECTION_WEBDAV_S3_DIALOG_NAME, WebDavS3InfoDialogData } from 'store/collections/collection-info-actions';
9 import { WithDialogProps } from 'store/dialog/with-dialog';
10 import { compose } from 'redux';
11 import { DetailsAttribute } from "components/details-attribute/details-attribute";
12 import { DownloadIcon } from "components/icon/icon";
13 import { DefaultCodeSnippet } from "components/default-code-snippet/default-code-snippet";
14
15 export type CssRules = 'details' | 'downloadButton' | 'detailsAttrValWithCode';
16
17 const styles: StyleRulesCallback<CssRules> = theme => ({
18     details: {
19         marginLeft: theme.spacing.unit * 3,
20         marginRight: theme.spacing.unit * 3,
21     },
22     downloadButton: {
23         marginTop: theme.spacing.unit * 2,
24     },
25     detailsAttrValWithCode: {
26         display: "flex",
27         alignItems: "center",
28     }
29 });
30
31 interface TabPanelData {
32     children: React.ReactElement<any>[];
33     value: number;
34     index: number;
35 }
36
37 function TabPanel(props: TabPanelData) {
38     const { children, value, index } = props;
39
40     return (
41         <div
42             role="tabpanel"
43             hidden={value !== index}
44             id={`simple-tabpanel-${index}`}
45             aria-labelledby={`simple-tab-${index}`}
46         >
47             {value === index && children}
48         </div>
49     );
50 }
51
52 const isValidIpAddress = (ipAddress: string): Boolean => {
53     if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)) {
54         return true;
55     }
56
57     return false;
58 };
59
60 const mountainduckTemplate = ({
61     uuid,
62     username,
63     cyberDavStr,
64     collectionsUrl
65 }: any) => {
66
67     return `<?xml version="1.0" encoding="UTF-8"?>
68         <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
69         <plist version="1.0">
70         <dict>
71             <key>Protocol</key>
72             <string>davs</string>
73             <key>Provider</key>
74             <string>iterate GmbH</string>
75             <key>UUID</key>
76             <string>${uuid}</string>
77             <key>Hostname</key>
78             <string>${collectionsUrl.replace('https://', ``).replace('*', uuid).split(':')[0]}</string>
79             <key>Port</key>
80             <string>${(cyberDavStr.split(':')[2] || '443').split('/')[0]}</string>
81             <key>Username</key>
82             <string>${username}</string>${isValidIpAddress(collectionsUrl.replace('https://', ``).split(':')[0])?
83             `
84             <key>Path</key>
85             <string>/c=${uuid}</string>` : ''}
86             <key>Labels</key>
87             <array>
88             </array>
89         </dict>
90         </plist>`.split(/\r?\n/).join('\n');
91 };
92
93 const downloadMountainduckFileHandler = (filename: string, text: string) => {
94     const element = document.createElement('a');
95     element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
96     element.setAttribute('download', filename);
97
98     element.style.display = 'none';
99     document.body.appendChild(element);
100
101     element.click();
102
103     document.body.removeChild(element);
104 };
105
106 export const WebDavS3InfoDialog = compose(
107     withDialog(COLLECTION_WEBDAV_S3_DIALOG_NAME),
108     withStyles(styles),
109 )(
110     (props: WithDialogProps<WebDavS3InfoDialogData> & WithStyles<CssRules>) => {
111         if (!props.data.downloadUrl) { return null; }
112
113         let winDav;
114         let cyberDav;
115
116         if (props.data.collectionsUrl.indexOf("*") > -1) {
117             const withuuid = props.data.collectionsUrl.replace("*", props.data.uuid);
118             winDav = new URL(withuuid);
119             cyberDav = new URL(withuuid);
120         } else {
121             winDav = new URL(props.data.downloadUrl);
122             cyberDav = new URL(props.data.downloadUrl);
123             winDav.pathname = `/by_id/${props.data.uuid}`;
124             cyberDav.pathname = `/by_id/${props.data.uuid}`;
125         }
126
127         cyberDav.username = props.data.username;
128         const cyberDavStr = "dav" + cyberDav.toString().slice(4);
129
130         const s3endpoint = new URL(props.data.collectionsUrl.replace(/\/\*(--[^.]+)?\./, "/"));
131
132         const sp = props.data.token.split("/");
133         let tokenUuid;
134         let tokenSecret;
135         if (sp.length === 3 && sp[0] === "v2" && sp[1].slice(0, 5) === props.data.localCluster) {
136             tokenUuid = sp[1];
137             tokenSecret = sp[2];
138         } else {
139             tokenUuid = props.data.token.replace(/\//g, "_");
140             tokenSecret = tokenUuid;
141         }
142
143         const isCollection = (props.data.uuid.indexOf("-4zz18-") === 5);
144
145         let activeTab = props.data.activeTab;
146         if (!isCollection) {
147             activeTab = 2;
148         }
149
150         const wgetCommand = `wget --http-user=${props.data.username} --http-passwd=${props.data.token} --mirror --no-parent --no-host --cut-dirs=0 ${winDav.toString()}`;
151
152         return <Dialog
153             open={props.open}
154             maxWidth="md"
155             onClose={props.closeDialog}
156             style={{ alignSelf: 'stretch' }}>
157             <CardHeader
158                 title={`Open with 3rd party client`} />
159             <div className={props.classes.details} >
160                 <Tabs value={activeTab} onChange={props.data.setActiveTab}>
161                     {isCollection && <Tab value={0} key="cyberduck" label="WebDAV" />}
162                     {isCollection && <Tab value={1} key="windows" label="Windows or MacOS" />}
163                     <Tab value={2} key="s3" label="S3 bucket" />
164                     {isCollection && <Tab value={3} key="cli" label="wget / curl" />}
165                 </Tabs>
166
167                 <TabPanel index={1} value={activeTab}>
168                     <h2>Settings</h2>
169
170                     <DetailsAttribute
171                         label='Internet address'
172                         value={<a href={winDav.toString()} target="_blank" rel="noopener noreferrer">{winDav.toString()}</a>}
173                         copyValue={winDav.toString()} />
174
175                     <DetailsAttribute
176                         label='Username'
177                         value={props.data.username}
178                         copyValue={props.data.username} />
179
180                     <DetailsAttribute
181                         label='Password'
182                         value={props.data.token}
183                         copyValue={props.data.token} />
184
185                     <h3>Windows</h3>
186                     <ol>
187                         <li>Open File Explorer</li>
188                         <li>Click on "This PC", then go to Computer &rarr; Add a Network Location</li>
189                         <li>Click Next, then choose "Add a custom network location", then click Next</li>
190                         <li>Use the "internet address" and credentials listed under Settings, above</li>
191                     </ol>
192
193                     <h3>MacOS</h3>
194                     <ol>
195                         <li>Open Finder</li>
196                         <li>Click Go &rarr; Connect to server</li>
197                         <li>Use the "internet address" and credentials listed under Settings, above</li>
198                     </ol>
199                 </TabPanel>
200
201                 <TabPanel index={0} value={activeTab}>
202                     <DetailsAttribute
203                         label='Server'
204                         value={<a href={cyberDavStr} target="_blank" rel="noopener noreferrer">{cyberDavStr}</a>}
205                         copyValue={cyberDavStr} />
206
207                     <DetailsAttribute
208                         label='Username'
209                         value={props.data.username}
210                         copyValue={props.data.username} />
211
212                     <DetailsAttribute
213                         label='Password'
214                         value={props.data.token}
215                         copyValue={props.data.token} />
216
217                     <h3>Cyberduck/Mountain Duck</h3>
218
219                     <Button
220                         data-cy='download-button'
221                         className={props.classes.downloadButton}
222                         onClick={() => downloadMountainduckFileHandler(`${props.data.collectionName || props.data.uuid}.duck`, mountainduckTemplate({ ...props.data, cyberDavStr }))}
223                         variant='contained'
224                         color='primary'
225                         size='small'>
226                         <DownloadIcon />
227                         Download Cyber/Mountain Duck bookmark
228                     </Button>
229
230                     <h3>Gnome</h3>
231                     <ol>
232                         <li>Open Files</li>
233                         <li>Select +Other Locations</li>
234                         <li>Connect to Server &rarr; Enter server address</li>
235                     </ol>
236
237                 </TabPanel>
238
239                 <TabPanel index={2} value={activeTab}>
240                     <DetailsAttribute
241                         label='Endpoint'
242                         value={s3endpoint.host}
243                         copyValue={s3endpoint.host} />
244
245                     <DetailsAttribute
246                         label='Bucket'
247                         value={props.data.uuid}
248                         copyValue={props.data.uuid} />
249
250                     <DetailsAttribute
251                         label='Access Key'
252                         value={tokenUuid}
253                         copyValue={tokenUuid} />
254
255                     <DetailsAttribute
256                         label='Secret Key'
257                         value={tokenSecret}
258                         copyValue={tokenSecret} />
259
260                 </TabPanel>
261
262                 <TabPanel index={3} value={activeTab}>
263
264                     <DetailsAttribute
265                         label='Wget command'
266                         copyValue={wgetCommand}
267                         classValue={props.classes.detailsAttrValWithCode}>
268                         <DefaultCodeSnippet
269                             lines={[wgetCommand]} />
270                     </DetailsAttribute>
271
272                     <DetailsAttribute
273                         label='Username'
274                         value={props.data.username}
275                         copyValue={props.data.username} />
276
277                     <DetailsAttribute
278                         label='Password'
279                         value={props.data.token}
280                         copyValue={props.data.token} />
281
282                 </TabPanel>
283
284             </div>
285             <DialogActions>
286                 <Button
287                     variant='text'
288                     color='primary'
289                     onClick={props.closeDialog}>
290                     Close
291                 </Button>
292             </DialogActions>
293
294         </Dialog >;
295     }
296 );