Add collaboration feature
[sdc.git] / openecomp-ui / src / sdc-app / heatvalidation / UploadScreenActionHelper.js
1 /*!
2  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
13  * or implied. See the License for the specific language governing
14  * permissions and limitations under the License.
15  */
16 import RestAPIUtil from 'nfvo-utils/RestAPIUtil.js';
17 import i18n from 'nfvo-utils/i18n/i18n.js';
18 import isEqual from 'lodash/isEqual.js';
19 import cloneDeep from 'lodash/cloneDeep.js';
20 import {actionTypes as modalActionTypes} from 'nfvo-components/modal/GlobalModalConstants.js';
21 import {modalContentMapper} from 'sdc-app/common/modal/ModalContentMapper.js';
22 import {actionTypes as softwareProductsActionTypes} from '../onboarding/softwareProduct/SoftwareProductConstants.js';
23 import {actionTypes as HeatSetupActions} from '../onboarding/softwareProduct/attachments/setup/HeatSetupConstants.js';
24
25
26
27 const options = {
28         headers: {
29                 USER_ID: 'validationOnlyVspUser'
30         }
31 };
32
33
34 function getTimestampString() {
35         let date = new Date();
36         let z = n => n < 10 ? '0' + n : n;
37         return `${date.getFullYear()}-${z(date.getMonth())}-${z(date.getDate())}_${z(date.getHours())}-${z(date.getMinutes())}`;
38 }
39
40 function fetchVspIdAndVersion() {
41
42         let vspId = sessionStorage.getItem('validationAppVspId');
43         let versionId = sessionStorage.getItem('validationAppVersionId');
44         if (vspId) {
45                 return  Promise.resolve({value: vspId, versionId});
46         }else {
47                 return RestAPIUtil.fetch('/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/validation-vsp', options)
48                         .then(response => {
49                                 sessionStorage.setItem('validationAppVspId', response.itemId);
50                                 sessionStorage.setItem('validationAppVersionId', response.version.id);
51                                 return Promise.resolve({value: response.itemId, versionId: response.version.id});
52                         });
53         }
54
55 }
56
57
58 function showFileSaveDialog({blob, xhr, defaultFilename, addTimestamp}) {
59         let filename;
60         let contentDisposition = xhr.getResponseHeader('content-disposition');
61         let match = contentDisposition ? contentDisposition.match(/filename=(.*?)(;|$)/) : false;
62         if (match) {
63                 filename = match[1];
64         } else {
65                 filename = defaultFilename;
66         }
67
68         if (addTimestamp) {
69                 filename = filename.replace(/(^.*?)\.([^.]+$)/, `$1_${getTimestampString()}.$2`);
70         }
71
72         let link = document.createElement('a');
73         let url = URL.createObjectURL(blob);
74         link.href = url;
75         link.download = filename;
76         link.style.display = 'none';
77         document.body.appendChild(link);
78         link.click();
79         setTimeout(function(){
80                 document.body.removeChild(link);
81                 URL.revokeObjectURL(url);
82         }, 0);
83 }
84
85
86 function uploadFile(formData) {
87         return fetchVspIdAndVersion()
88                 .then(response => {
89                         return RestAPIUtil.post(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate`, formData, options);
90                 });
91 }
92
93 function loadSoftwareProductHeatCandidate(dispatch){
94         return fetchVspIdAndVersion()
95                 .then(response => {
96                         return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/manifest`, options)
97                                 .then(response => dispatch({
98                                         type: HeatSetupActions.MANIFEST_LOADED,
99                                         response
100                                 }));
101                 });
102 }
103
104 function updateHeatCandidate(dispatch, heatCandidate) {
105         return fetchVspIdAndVersion()
106                 .then(response => {
107                         return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/manifest`,
108                                 heatCandidate.heatData, options)
109                                 .then(null, error => {
110                                         dispatch({
111                                                 type: modalActionTypes.GLOBAL_MODAL_ERROR,
112                                                 data: {
113                                                         title: i18n('Save Failed'), 
114                                                         modalComponentName: modalContentMapper.SUMBIT_ERROR_RESPONSE,                                                   
115                                                         modalComponentProps: {
116                                                                 validationResponse: error.responseJSON
117                                                         },                                      
118                                                         cancelButtonText: i18n('Ok')
119                                                 }
120                                         });
121                                         return Promise.reject(error);
122                                 });
123                 });
124 }
125
126 function fetchSoftwareProduct() {
127         return fetchVspIdAndVersion()
128                 .then(response => {
129                         return RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}`, options);
130                 });
131 }
132
133 function downloadHeatFile() {
134         return fetchVspIdAndVersion()
135                 .then(response => {
136                         RestAPIUtil.fetch(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate`, {
137                                 ...options,
138                                 dataType: 'binary'
139                         })
140                                 .done((blob, statusText, xhr) => showFileSaveDialog({
141                                         blob,
142                                         xhr,
143                                         defaultFilename: 'HEAT_file.zip',
144                                         addTimestamp: true
145                                 }));
146                 });
147 }
148
149 function processAndValidateHeatCandidate(dispatch) {
150         return fetchVspIdAndVersion()
151                 .then(response => {
152                         return RestAPIUtil.put(`/sdc1/feProxy/onboarding-api/v1.0/vendor-software-products/${response.value}/versions/${response.versionId}/orchestration-template-candidate/process`, {}, options)
153                                 .then(response => {
154                                         if (response.status === 'Success') {
155                                                 fetchSoftwareProduct().then(response => {
156                                                         dispatch({
157                                                                 type: softwareProductsActionTypes.SOFTWARE_PRODUCT_LOADED,
158                                                                 response
159                                                         });
160                                                 });
161                                         }
162                                 });
163                 });
164 }
165
166 const UploadScreenActionHelper = {
167         uploadFile(dispatch, formData) {
168
169                 return Promise.resolve()
170                         .then(() => uploadFile(formData))
171                         .then(response => {
172                                 dispatch({
173                                         type: softwareProductsActionTypes.SOFTWARE_PRODUCT_LOADED,
174                                         response
175                                 });
176                                 dispatch({
177                                         type: HeatSetupActions.FILL_HEAT_SETUP_CACHE,
178                                         payload:{}
179                                 });
180                                 loadSoftwareProductHeatCandidate(dispatch);
181                         })
182                         .catch(error => {
183                                 dispatch({                                      
184                                         type: modalActionTypes.GLOBAL_MODAL_ERROR,
185                                         data: {
186                                                 title: i18n('File Upload Failed'),                                                                                                      
187                                                 msg: error.responseJSON.message,                                        
188                                                 cancelButtonText: i18n('Ok')
189                                         }
190                                 });
191                         });
192         },
193
194         processAndValidateHeat(dispatch, heatData, heatDataCache){
195                 return isEqual(heatData, heatDataCache) ? Promise.resolve() :
196                         updateHeatCandidate(dispatch, heatData)
197                                 .then(() => processAndValidateHeatCandidate(dispatch))
198                                 .then(() => dispatch({type: HeatSetupActions.FILL_HEAT_SETUP_CACHE, payload: cloneDeep(heatData)}));
199         },
200
201         downloadHeatFile(){
202                 return downloadHeatFile();
203         },
204 };
205
206 export default UploadScreenActionHelper;