3263ec99b8573c3e88cd7244d3aa1bcc5989ed5d
[pithos] / src / gr / ebs / gss / client / FileUploadGearsDialog.java
1 /*
2  * Copyright 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.client;
20
21 import gr.ebs.gss.client.rest.PostCommand;
22 import gr.ebs.gss.client.rest.RestCommand;
23 import gr.ebs.gss.client.rest.RestException;
24 import gr.ebs.gss.client.rest.resource.FileResource;
25 import gr.ebs.gss.client.rest.resource.FolderResource;
26 import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
27
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import com.google.gwt.core.client.GWT;
35 import com.google.gwt.event.dom.client.ClickEvent;
36 import com.google.gwt.event.dom.client.ClickHandler;
37 import com.google.gwt.gears.client.Factory;
38 import com.google.gwt.gears.client.desktop.Desktop;
39 import com.google.gwt.gears.client.desktop.File;
40 import com.google.gwt.gears.client.desktop.OpenFilesHandler;
41 import com.google.gwt.gears.client.httprequest.HttpRequest;
42 import com.google.gwt.gears.client.httprequest.ProgressEvent;
43 import com.google.gwt.gears.client.httprequest.ProgressHandler;
44 import com.google.gwt.gears.client.httprequest.RequestCallback;
45 import com.google.gwt.http.client.URL;
46 import com.google.gwt.json.client.JSONObject;
47 import com.google.gwt.json.client.JSONString;
48 import com.google.gwt.user.client.DeferredCommand;
49 import com.google.gwt.user.client.ui.Button;
50 import com.google.gwt.user.client.ui.FlexTable;
51 import com.google.gwt.user.client.ui.HTML;
52 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
53 import com.google.gwt.user.client.ui.HorizontalPanel;
54 import com.google.gwt.user.client.ui.VerticalPanel;
55
56 /**
57  * The 'File upload' dialog box implementation with Google Gears support.
58  */
59 public class FileUploadGearsDialog extends FileUploadDialog implements Updateable {
60
61         protected final Factory factory = Factory.getInstance();
62
63         /**
64          * The array of files to upload.
65          */
66         private File[] fileObjects;
67
68         /**
69          * A list of files to upload, created from files array. Used to signal
70          * finished state when empty.
71          */
72         protected List<File> selectedFiles = new ArrayList<File>();
73
74         /**
75          * The list of progress bars for individual files.
76          */
77         protected List<ProgressBar> progressBars = new ArrayList<ProgressBar>();
78
79         private Button browse;
80
81         private Button submit;
82
83         private FlexTable generalTable;
84
85         private Map<String, FileResource> toRename;
86
87         protected List<HttpRequest> requests = new ArrayList<HttpRequest>();
88         
89         private boolean canContinue = true;
90
91         /**
92          * The widget's constructor.
93          */
94         public FileUploadGearsDialog() {
95                 // Set the dialog's caption.
96                 setText("File upload");
97                 setAnimationEnabled(true);
98                 // Create a panel to hold all of the dialog widgets.
99                 VerticalPanel panel = new VerticalPanel();
100                 final HTML info = new HTML("You may select one or more files to upload.");
101                 info.addStyleName("gss-uploadNote");
102                 panel.add(info);
103                 // Add an informative label with the folder name.
104                 Object selection = GSS.get().getTreeView().getSelection();
105                 folder = ((RestResourceWrapper) selection).getResource();
106
107                 browse = new Button("Browse...");
108
109                 HorizontalPanel fileUploadPanel = new HorizontalPanel();
110                 fileUploadPanel.add(browse);
111
112                 generalTable = new FlexTable();
113                 generalTable.setText(0, 0, "Folder");
114                 generalTable.setText(1, 0, "File");
115                 generalTable.setText(0, 1, folder.getName());
116                 generalTable.setWidget(1, 1, fileUploadPanel);
117                 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
118                 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
119                 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
120                 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
121                 generalTable.setCellSpacing(4);
122
123                 panel.add(generalTable);
124
125                 // Create a panel to hold the buttons.
126                 HorizontalPanel buttons = new HorizontalPanel();
127
128                 submit = new Button("Upload");
129                 submit.addClickHandler(new ClickHandler() {
130                         @Override
131                         public void onClick(ClickEvent event) {
132                                 prepareAndSubmit();
133                         }
134                 });
135                 submit.setEnabled(false);
136                 buttons.add(submit);
137                 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
138                 // Create the 'Cancel' button, along with a listener that hides the
139                 // dialog when the button is clicked.
140                 Button cancel = new Button("Cancel", new ClickHandler() {
141                         @Override
142                         public void onClick(ClickEvent event) {
143                                 canContinue = false;                            
144                                 cancelUpload();                         
145                                 GSS.get().showFileList(true);
146                         }
147                 });
148                 buttons.add(cancel);
149                 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
150                 buttons.setSpacing(8);
151                 buttons.addStyleName("gss-DialogBox");
152
153                 browse.addClickHandler(new ClickHandler() {
154                         @Override
155                         public void onClick(ClickEvent event) {
156                                 Desktop desktop = factory.createDesktop();
157                                 desktop.openFiles(new OpenFilesHandler() {
158
159                                         @Override
160                                         public void onOpenFiles(OpenFilesEvent ofevent) {
161                                                 fileObjects = ofevent.getFiles();
162                                                 selectedFiles.addAll(Arrays.asList(fileObjects));
163                                                 for (int i = 0; i< selectedFiles.size(); i++) {
164                                                         generalTable.setText(i+1, 0, "File");
165                                                         generalTable.setText(i+1, 1, selectedFiles.get(i).getName());
166                                                         ProgressBar progress = new ProgressBar(20, 0);
167                                                         generalTable.setWidget(i+1, 2, progress);
168                                                         progressBars.add(progress);
169                                                         generalTable.getCellFormatter().setStyleName(i+1, 0, "props-labels");
170                                                         generalTable.getCellFormatter().setStyleName(i+1, 1, "props-values");
171                                                 }
172                                                 submit.setEnabled(true);
173                                         }
174                                 });
175                         }
176                 });
177
178                 panel.add(buttons);
179                 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
180                 panel.addStyleName("gss-DialogBox");
181                 addStyleName("gss-DialogBox");
182                 setWidget(panel);
183         }
184
185         /**
186          * Cancels the file upload.
187          */
188         private void cancelUpload() {
189                 for (HttpRequest request: requests)
190                         request.abort();
191                 hide();         
192         }
193
194         /**
195          * Check whether the specified file name exists in the selected folder.
196          */
197         private boolean canContinue(File file) {
198                 String fileName = getFilename(file.getName());
199                 if (getFileForName(fileName) == null)
200                         // For file creation, check to see if the file already exists.
201                         for (FileResource fileRes : files)
202                                 if (!fileRes.isDeleted() && fileRes.getName().equals(fileName))
203                                         return false;
204                 return true;
205         }
206
207         @Override
208         public void prepareAndSubmit() {
209                 GSS app = GSS.get();
210                 if (selectedFiles.size() == 0) {
211                         app.displayError("You must select a file!");
212                         hide();
213                         return;
214                 }
215                 for (File file: selectedFiles)
216                         if (!canContinue(file)) {
217                                 app.displayError("The file name " + file.getName() +
218                                                         " already exists in this folder");
219                                 hide();
220                                 return;
221                         }
222                 submit.setEnabled(false);
223                 browse.setVisible(false);
224                 List<String> toUpdate = new ArrayList<String>();
225                 toRename = new HashMap<String, FileResource>();
226                 for (File file: selectedFiles) {
227                         String fname = getFilename(file.getName());
228                         if (getFileForName(fname) == null) {
229                                 // We are going to create a file, so we check to see if there is a
230                                 // trashed file with the same name.
231                                 FileResource same = null;
232                                 for (FileResource fres : folder.getFiles())
233                                         if (fres.isDeleted() && fres.getName().equals(fname))
234                                                 same = fres;
235                                 // In that case add it to the list of files to rename.
236                                 if (same != null)
237                                         toRename.put(getBackupFilename(fname), same);
238                         } else
239                                 // If we are updating a file add it to the list of files to update.
240                                 toUpdate.add(fname);
241                 }
242
243                 if (!toUpdate.isEmpty()) {
244                         StringBuffer sb = new StringBuffer();
245                         for (String name: toUpdate)
246                                 sb.append(name).append("<br/>");
247                         // We are going to update existing files, so show a confirmation dialog.
248                         ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +
249                                         "you want to update the following files?<br/><i>" + sb +
250                                         "</i>", "Update") {
251
252                                 @Override
253                                 public void cancel() {
254                                         hide();
255                                 }
256
257                                 @Override
258                                 public void confirm() {
259                                         confirmRename();
260                                 }
261
262                         };
263                         confirm.center();
264                 } else
265                         confirmRename();
266         }
267
268         /**
269          * Confirm the renames of synonymous files already in the trash.
270          */
271         private void confirmRename() {
272                 if (!toRename.isEmpty()) {
273                         StringBuffer sb = new StringBuffer();
274                         for (FileResource file: toRename.values())
275                                 sb.append(file.getName()).append("<br/>");
276                         ConfirmationDialog confirm = new ConfirmationDialog("Files " +
277                                         "with the following names already exist in the trash. If" +
278                                         " you continue,<br/>the trashed files will be renamed " +
279                                         "automatically for you:<br/><i>" + sb + "</i>", "Continue") {
280
281                                 @Override
282                                 public void cancel() {
283                                         hide();
284                                 }
285
286                                 @Override
287                                 public void confirm() {
288                                         updateTrashedFiles();
289                                 }
290
291                         };
292                         confirm.center();
293                 } else
294                         uploadFiles();
295         }
296
297         /**
298          * Rename the conflicting trashed files with the supplied new names.
299          */
300         private void updateTrashedFiles() {
301                 for (final String name: toRename.keySet()) {
302                         JSONObject json = new JSONObject();
303                         json.put("name", new JSONString(name));
304                         PostCommand cf = new PostCommand(toRename.get(name).getUri() + "?update=", json.toString(), 200) {
305
306                                 @Override
307                                 public void onComplete() {
308                                         toRename.remove(name);
309                                         uploadFiles();
310                                 }
311
312                                 @Override
313                                 public void onError(Throwable t) {
314                                         GSS app = GSS.get();
315                                         GWT.log("", t);
316                                         if (t instanceof RestException) {
317                                                 int statusCode = ((RestException) t).getHttpStatusCode();
318                                                 if (statusCode == 405)
319                                                         app.displayError("You don't have the necessary permissions");
320                                                 else if (statusCode == 404)
321                                                         app.displayError("User in permissions does not exist");
322                                                 else if (statusCode == 409)
323                                                         app.displayError("A file with the same name already exists");
324                                                 else if (statusCode == 413)
325                                                         app.displayError("Your quota has been exceeded");
326                                                 else
327                                                         app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
328                                         } else
329                                                 app.displayError("System error modifying file:" + t.getMessage());
330                                 }
331
332                         };
333                         DeferredCommand.addCommand(cf);
334                 }
335         }
336
337         /**
338          * Checks if the renaming step for already trashed files is complete and
339          * starts file uploads.
340          */
341         private void uploadFiles() {            
342                 if (!toRename.isEmpty()) return;
343                 if (canContinue){                                               
344                         doSend(selectedFiles);
345                 }
346         }
347
348         /**
349          * Perform the HTTP request to upload the specified file.
350          */
351         protected void doSend(final List<File> filesRemaining) {
352                 final GSS app = GSS.get();
353                 HttpRequest request = factory.createHttpRequest();
354                 requests.add(request);
355                 String method = "PUT";
356
357                 String path;
358                 final String filename = getFilename(filesRemaining.get(0).getName());
359                 path = folder.getUri();
360                 if (!path.endsWith("/"))
361                         path = path + "/";
362                 path = path + encode(filename);
363
364                 String token = app.getToken();
365                 String resource = path.substring(app.getApiPath().length()-1, path.length());
366                 String date = RestCommand.getDate();
367                 String sig = RestCommand.calculateSig(method, date, resource, RestCommand.base64decode(token));
368                 request.open(method, path);
369                 request.setRequestHeader("X-GSS-Date", date);
370                 request.setRequestHeader("Authorization", app.getCurrentUserResource().getUsername() + " " + sig);
371                 request.setRequestHeader("Accept", "application/json; charset=utf-8");
372                 request.setCallback(new RequestCallback() {
373                         @Override
374                         public void onResponseReceived(HttpRequest req) {
375                                 int state = req.getReadyState();
376                                 if (state != 4) return;
377                                 switch(req.getStatus()) {
378                                         case 201: // Created falls through to updated.
379                                         case 204:
380                                                 filesRemaining.remove(0);
381                                                 if(filesRemaining.isEmpty()){                                                   
382                                                         finish();
383                                                         break;
384                                                 }                                               
385                                                 doSend(filesRemaining);                         
386                                                 break;
387                                         case 403:
388                                                 SessionExpiredDialog dlg = new SessionExpiredDialog();
389                                                 dlg.center();
390                                                 break;
391                                         case 405:
392                                                 app.displayError("You don't have permission to " +
393                                                                 "upload file " + filename);
394                                                 break;
395                                         case 409:
396                                                 app.displayError("A folder with the name " + filename +
397                                                                 " already exists at this level");
398                                                 break;
399                                         case 413:
400                                                 app.displayError("There is not enough free space " +
401                                                                 "available for uploading " + filename);
402                                                 break;
403                                         default:
404                                                 app.displayError("Error uploading file " + filename +
405                                                                         ": " + req.getStatus());
406                                 }
407                         }
408                 });
409                 request.getUpload().setProgressHandler(new ProgressHandler() {
410                         @Override
411                         public void onProgress(ProgressEvent event) {
412                                 double pcnt = (double) event.getLoaded() / event.getTotal();
413                                 progressBars.get(0).setProgress((int) Math.floor(pcnt * 100));
414                                 if(pcnt*100 == 100)
415                                         progressBars.remove(0);
416                         }
417                 });
418                 request.send(filesRemaining.get(0).getBlob());
419         }
420
421         /**
422          * Perform the final actions after the files are uploaded.
423          */
424         protected void finish() {
425                 hide();
426                 //GSS.get().showFileList(true);
427                 GSS.get().getTreeView().updateNode(folder);//showFileList(true);
428                 GSS.get().getStatusPanel().updateStats();
429         }
430
431         /**
432          * Same as URL.encode, but also encode apostrophe since browsers aren't
433          * consistent about it (FF encodes, IE does not).
434          */
435         protected String encode(String decodedURL) {
436                 String retv = decodedURL.replaceAll("@", "_"); // Replace bad character
437                 retv = URL.encodeComponent(retv);
438                 retv = retv.replaceAll("'", "%27");
439                 return retv;
440         }
441
442 }