RIFT-15726 - optimize download size -> lodash usage in UI
[osm/UI.git] / skyquake / plugins / composer / src / src / components / filemanager / FileManager.jsx
1 /*
2  *
3  *   Copyright 2016 RIFT.IO Inc
4  *
5  *   Licensed under the Apache License, Version 2.0 (the "License");
6  *   you may not use this file except in compliance with the License.
7  *   You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *   Unless required by applicable law or agreed to in writing, software
12  *   distributed under the License is distributed on an "AS IS" BASIS,
13  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *   See the License for the specific language governing permissions and
15  *   limitations under the License.
16  *
17  */
18
19
20 //https://raw.githubusercontent.com/RIFTIO/RIFT.ware/master/rift-shell
21 import _cloneDeep from 'lodash/cloneDeep'
22 import _findIndex from 'lodash/findIndex'
23 import React from 'react';
24 import ReactDOM from 'react-dom';
25 import TreeView from 'react-treeview';
26 import TextInput from 'widgets/form_controls/textInput.jsx';
27 import Button from '../Button';
28 import './FileMananger.scss';
29 import FileManagerActions from './FileManagerActions.js';
30 import imgSave from '../../../../node_modules/open-iconic/svg/data-transfer-upload.svg'
31 import {Panel, PanelWrapper} from 'widgets/panel/panel';
32 import SkyquakeComponent from 'widgets/skyquake_container/skyquakeComponent.jsx';
33 import LoadingIndicator from 'widgets/loading-indicator/loadingIndicator.jsx';
34
35 import DropZone from 'dropzone'
36 import Utils from '../../libraries/utils'
37 import FileManagerUploadDropZone from '../../libraries/FileManagerUploadDropZone';
38 let API_SERVER = require('utils/rw.js').getSearchParams(window.location).api_server;
39
40 const createDropZone = function (action, clickable, type, id, path, dropTarget) {
41     const dropZone = new FileManagerUploadDropZone(ReactDOM.findDOMNode(dropTarget), [clickable], action, type, id, path);
42     // dropZone.on('dragover', this.onDragOver);
43     // dropZone.on('dragend', this.onDragEnd);
44     // dropZone.on('addedfile', this.onFileAdded);
45     return dropZone;
46 };
47 //updateFileLocationInput
48 class FileManager extends React.Component {
49     constructor(props) {
50         super(props)
51     }
52     componentWillMount() {
53         // FileManagerActions.openFileManagerSockets()
54     }
55     componentWillUnmount() {
56         // FileManagerActions.closeFileManagerSockets();
57     }
58     generateFolder(data, nesting) {
59         let nestingLevel = nesting || 1;
60
61     }
62     deleteFile(name) {
63         return function(e) {
64             FileManagerActions.deletePackageFile(name);
65         }
66
67     }
68     updateFileLocationInput(name) {
69         return function(e) {
70             FileManagerActions.updateFileLocationInput({
71                 name: name,
72                 value: e.target.value
73             });
74         }
75     }
76     sendDownloadFileRequst = (url, path) => {
77         let self = this;
78         return function(e) {
79             if(!url || url == "") {
80                 return self.props.actions.showNotification.defer({type: 'error', msg: 'Value missing in download request'});;
81             }
82             let files = self.props.files.data;
83             let folder = path.split('/');
84             let splitUrl = url.split('/');
85             let fileName = splitUrl[splitUrl.length - 1];
86             folder.pop;
87             let fullPath = _cloneDeep(folder);
88             fullPath.push(fileName);
89             fullPath = fullPath.join('/');
90             folder = folder.join('/');
91             let fileIndex = _findIndex(files[folder], function(f) {
92                 return f.name == fullPath;
93             })
94             if (fileIndex == -1) {
95                 FileManagerActions.sendDownloadFileRequst({
96                     url: url,
97                     path: path
98                 });
99             } else {
100                 self.props.actions.showNotification('It seems you\'re attempting to upload a file with a duplicate file name');
101             }
102         }
103     }
104     render() {
105         let self = this;
106         let html = (
107             <div className="FileManager">
108                 <PanelWrapper style={{flexDirection: 'column'}}>
109                 <Panel className="addFileSection" style={{backgroundColor: 'transparent'}} no-corners>
110                     <div className="inputSection">
111                         <TextInput placeholder="some/path" value={this.props.newPathName} label="create a new directory" onChange={FileManagerActions.newPathNameUpdated} />
112                         <Button label="Create" onClick={FileManagerActions.createDirectory} />
113                     </div>
114                 </Panel>
115                 {self.props.files && self.props.files.id && buildList(self, self.props.files) }
116                 </PanelWrapper>
117             </div>
118         )
119         return html;
120     }
121
122 }
123
124 function buildList(self, data) {
125     let toReturn = [];
126     data.id.map(function(k,i) {
127         toReturn.push (contentFolder(self, data.data[k], k, i, self.props.filesState, self.updateFileLocationInput, self.sendDownloadFileRequst, self.deleteFile));
128     });
129     return toReturn.reverse();
130 }
131
132 function contentFolder(context, folder, path, key, inputState, updateFn, sendDownloadFileRequst, deleteFn) {
133     let type = context.props.type;
134     let id = context.props.item.id;
135     const onboardDropZone = createDropZone.bind(this, FileManagerUploadDropZone.ACTIONS.onboard, '.ComposerAppAddFile.' + path.replace(/\//g, '-'), type, id, path);
136     return (
137         <Panel title={path} key={key} itemClassName="nested" no-corners>
138         <div className="folder">
139             {
140                 folder.map(function(f, i) {
141                     if( !f.hasOwnProperty('contents') ){
142                         return contentFile(context, f, path, i, deleteFn);
143                     }
144                 })
145             }
146             <Panel className="addFileSection" no-corners>
147                 <ItemUpload type={type} id={id} path={path} key={key} dropZone={onboardDropZone} />
148                 <div style={{marginLeft: '0.5rem'}}>
149                     OR
150                 </div>
151                 <div className="inputSection">
152                     <TextInput placeholder="URL" className="" label="External URL" value={inputState[path]} onChange={updateFn(path)} />
153                     <Button className='ComposerAppSave' label="DOWNLOAD" onClick={sendDownloadFileRequst(inputState[path], path)}/>
154                 </div>
155             </Panel>
156
157             </div>
158         </Panel>
159     );
160 }
161 class ItemUpload extends React.Component {
162     constructor(props) {
163         super(props);
164     }
165     componentDidMount() {
166         if (this.props.dropZone) {
167             const dropTarget = this;
168             const dropZone = this.props.dropZone(dropTarget);
169         }
170     }
171     render() {
172         let {type, id, path, key, ...props} = this.props;
173         return (
174             <div className="inputSection">
175                 <label className="sqTextInput" style={{flexDirection: 'row', alignItems:'center'}}>
176                     <span>Upload File</span>
177                     <Button className={'ComposerAppAddFile ' + path.replace(/\//g, '-')} label="BROWSE"/>
178                 </label>
179             </div>
180         )
181     }
182 }
183 function contentFile(context, file, path, key, deleteFn) {
184     const name = stripPath(file.name, path);
185     const id = context.props.item.id;
186     const type = context.props.type;
187     const downloadHost = API_SERVER.match('localhost') || API_SERVER.match('127.0.0.1') ? `${window.location.protocol}//${window.location.hostname}` : API_SERVER;
188     //{`${window.location.protocol}//${API_SERVER}:4567/api/package${type}/${id}/${path}/${name}`}
189     return (
190         <div className="file" key={key}>
191             <div className="file-section">
192                 <div className="file-info">
193                     <div className="file-status" style={{display: (file.status && file.status.toLowerCase() != 'completed') ? 'inherit' : 'none', color: (file.status == 'FAILED' ? 'red' : 'inherit')}}>
194                         {file.status && (file.status == 'IN_PROGRESS' || file.status == 'DOWNLOADING'  )  ? <LoadingIndicator size={2} /> : file.status }
195                     </div>
196                     <div className="file-name">
197                         <a target="_blank" href={`${downloadHost}:4567/api/package/${type}/${id}/${path}/${name}`}>{name}</a>
198                     </div>
199                 </div>
200                 <div className="file-action" style={{display: (!file.status || (file && file.status.toLowerCase() != 'loading...')) ? 'inherit' : 'none', cursor: 'pointer'}} onClick={deleteFn(file.name)}>X</div>
201             </div>
202         </div>
203     )
204 }
205
206 function stripPath(name, path, returnPath) {
207     let stripSlash = (name.indexOf('/') > -1) ? '/' : '';
208     // return name.split(path + stripSlash)[1].replace('/', '');
209     let split = name.split(path + stripSlash)[returnPath ? 0 : 1];
210     return split ? split.replace('/', '') : name;
211 }
212
213
214
215 export default SkyquakeComponent(FileManager)
216 /**
217  * Sample Data
218  */
219 // let files = {
220 //   "name": ".",
221 //   "contents": [
222 //     {
223 //       "name": "pong_vnfd",
224 //       "contents": [
225 //         {
226 //           "name": "pong_vnfd/checksums.txt",
227 //           "last_modified_time": 1474458399.6218443,
228 //           "byte_size": 168
229 //         },
230 //         {
231 //           "name": "pong_vnfd/pong_vnfd.yaml",
232 //           "last_modified_time": 1474458399.6258445,
233 //           "byte_size": 3514
234 //         },
235 //         {
236 //           "name": "pong_vnfd/icons",
237 //           "contents": [
238 //             {
239 //               "name": "pong_vnfd/icons/rift_logo.png",
240 //               "last_modified_time": 1474458399.6218443,
241 //               "byte_size": 1658
242 //             }
243 //           ],
244 //           "last_modified_time": 1474458399.6218443,
245 //           "byte_size": 3
246 //         },
247 //         {
248 //           "name": "pong_vnfd/cloud_init",
249 //           "contents": [
250 //             {
251 //               "name": "pong_vnfd/cloud_init/pong_cloud_init.cfg",
252 //               "last_modified_time": 1474458399.6258445,
253 //               "byte_size": 227
254 //             }
255 //           ],
256 //           "last_modified_time": 1474458399.6258445,
257 //           "byte_size": 3
258 //         }
259 //       ],
260 //       "last_modified_time": 1474458399.6258445,
261 //       "byte_size": 6
262 //     }
263 //   ],
264 //   "last_modified_time": 1474458399.6218443,
265 //   "byte_size": 3
266 // };