Move create new WebDAV password URL from /users to plain / for user.
[pithos] / src / gr / ebs / gss / client / FileUploadDialog.java
1 /*\r
2  * Copyright 2007, 2008, 2009 Electronic Business Systems Ltd.\r
3  *\r
4  * This file is part of GSS.\r
5  *\r
6  * GSS is free software: you can redistribute it and/or modify\r
7  * it under the terms of the GNU General Public License as published by\r
8  * the Free Software Foundation, either version 3 of the License, or\r
9  * (at your option) any later version.\r
10  *\r
11  * GSS is distributed in the hope that it will be useful,\r
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14  * GNU General Public License for more details.\r
15  *\r
16  * You should have received a copy of the GNU General Public License\r
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.\r
18  */\r
19 package gr.ebs.gss.client;\r
20 \r
21 import gr.ebs.gss.client.rest.GetCommand;\r
22 import gr.ebs.gss.client.rest.PostCommand;\r
23 import gr.ebs.gss.client.rest.RestCommand;\r
24 import gr.ebs.gss.client.rest.RestException;\r
25 import gr.ebs.gss.client.rest.resource.FileResource;\r
26 import gr.ebs.gss.client.rest.resource.FolderResource;\r
27 import gr.ebs.gss.client.rest.resource.UploadStatusResource;\r
28 \r
29 import java.util.ArrayList;\r
30 import java.util.List;\r
31 \r
32 import com.google.gwt.core.client.GWT;\r
33 import com.google.gwt.http.client.URL;\r
34 import com.google.gwt.json.client.JSONObject;\r
35 import com.google.gwt.json.client.JSONString;\r
36 import com.google.gwt.user.client.DeferredCommand;\r
37 import com.google.gwt.user.client.Timer;\r
38 import com.google.gwt.user.client.ui.Button;\r
39 import com.google.gwt.user.client.ui.ClickListener;\r
40 import com.google.gwt.user.client.ui.DialogBox;\r
41 import com.google.gwt.user.client.ui.FileUpload;\r
42 import com.google.gwt.user.client.ui.FormHandler;\r
43 import com.google.gwt.user.client.ui.FormPanel;\r
44 import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;\r
45 import com.google.gwt.user.client.ui.FormSubmitEvent;\r
46 import com.google.gwt.user.client.ui.Grid;\r
47 import com.google.gwt.user.client.ui.HTML;\r
48 import com.google.gwt.user.client.ui.HasHorizontalAlignment;\r
49 import com.google.gwt.user.client.ui.Hidden;\r
50 import com.google.gwt.user.client.ui.HorizontalPanel;\r
51 import com.google.gwt.user.client.ui.KeyboardListener;\r
52 import com.google.gwt.user.client.ui.Label;\r
53 import com.google.gwt.user.client.ui.VerticalPanel;\r
54 import com.google.gwt.user.client.ui.Widget;\r
55 \r
56 /**\r
57  * The 'File upload' dialog box implementation.\r
58  */\r
59 public class FileUploadDialog extends DialogBox implements Updateable {\r
60 \r
61         protected int prgBarInterval = 1500;\r
62 \r
63         private ProgressBar progressBar;\r
64 \r
65         protected RepeatingTimer repeater = new RepeatingTimer(this, prgBarInterval);\r
66 \r
67         public static final boolean DONE = true;\r
68 \r
69         /**\r
70          * The Form element that performs the file upload.\r
71          */\r
72         private final FormPanel form = new FormPanel();\r
73 \r
74         private final FileUpload upload = new FileUpload();\r
75 \r
76         protected final Label filenameLabel = new Label("");\r
77 \r
78         protected List<FileResource> files;\r
79 \r
80         protected boolean cancelEvent = false;\r
81 \r
82         protected String fileNameToUse;\r
83 \r
84         protected FolderResource folder;\r
85 \r
86         /**\r
87          * The widget's constructor.\r
88          */\r
89         public FileUploadDialog() {\r
90                 // Set the dialog's caption.\r
91                 setText("File upload");\r
92                 setAnimationEnabled(true);\r
93                 // Since we're going to add a FileUpload widget, we'll need to set the\r
94                 // form to use the POST method, and multipart MIME encoding.\r
95                 form.setEncoding(FormPanel.ENCODING_MULTIPART);\r
96                 form.setMethod(FormPanel.METHOD_POST);\r
97 \r
98                 // Create a panel to hold all of the form widgets.\r
99                 VerticalPanel panel = new VerticalPanel();\r
100                 form.setWidget(panel);\r
101                 final HTML info = new HTML("You may select a file to upload. Install" +\r
102                                 " <a href='http://gears.google.com/' target='_blank'>Google " +\r
103                                 "Gears</a><br> for uploading multiple files simultaneously.");\r
104                 info.addStyleName("gss-uploadNote");\r
105                 panel.add(info);\r
106                 final Hidden date = new Hidden("Date", "");\r
107                 panel.add(date);\r
108                 final Hidden auth = new Hidden("Authorization", "");\r
109                 panel.add(auth);\r
110                 // Add an informative label with the folder name.\r
111                 Object selection = GSS.get().getFolders().getCurrent().getUserObject();\r
112                 folder = (FolderResource) selection;\r
113                 upload.setName("file");\r
114                 filenameLabel.setText("");\r
115                 filenameLabel.setVisible(false);\r
116                 filenameLabel.setStyleName("props-labels");\r
117                 HorizontalPanel fileUloadPanel = new HorizontalPanel();\r
118                 fileUloadPanel.add(filenameLabel);\r
119                 fileUloadPanel.add(upload);\r
120                 Grid generalTable = new Grid(2, 2);\r
121                 generalTable.setText(0, 0, "Folder");\r
122                 generalTable.setText(1, 0, "File");\r
123                 generalTable.setText(0, 1, folder.getName());\r
124                 generalTable.setWidget(1, 1, fileUloadPanel);\r
125                 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");\r
126                 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");\r
127                 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");\r
128                 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");\r
129                 generalTable.setCellSpacing(4);\r
130 \r
131                 panel.add(generalTable);\r
132 \r
133                 // Create a panel to hold the buttons.\r
134                 HorizontalPanel buttons = new HorizontalPanel();\r
135 \r
136                 // Create the 'upload' button, along with a listener that submits the\r
137                 // form.\r
138                 final Button submit = new Button("Upload", new ClickListener() {\r
139                         public void onClick(Widget sender) {\r
140                                 prepareAndSubmit();\r
141                         }\r
142                 });\r
143                 buttons.add(submit);\r
144                 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);\r
145                 // Create the 'Cancel' button, along with a listener that hides the\r
146                 // dialog when the button is clicked.\r
147                 final Button cancel = new Button("Cancel", new ClickListener() {\r
148 \r
149                         public void onClick(Widget sender) {\r
150                                 repeater.finish();\r
151                                 hide();\r
152                         }\r
153                 });\r
154                 buttons.add(cancel);\r
155                 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);\r
156                 buttons.setSpacing(8);\r
157                 buttons.addStyleName("gss-DialogBox");\r
158 \r
159                 // Add an event handler to the form.\r
160                 form.addFormHandler(new FormHandler() {\r
161 \r
162                         public void onSubmit(final FormSubmitEvent event) {\r
163                                 GSS app = GSS.get();\r
164                                 // This event is fired just before the form is submitted. We can\r
165                                 // take this opportunity to perform validation.\r
166                                 if (upload.getFilename().length() == 0) {\r
167                                         app.displayError("You must select a file!");\r
168                                         event.setCancelled(true);\r
169                                         hide();\r
170                                 } else {\r
171 \r
172                                         canContinue();\r
173                                         GWT.log("Cancel:" + cancelEvent, null);\r
174                                         if (cancelEvent) {\r
175                                                 cancelEvent = false;\r
176                                                 app.displayError("The specified file name already exists in this folder");\r
177                                                 event.setCancelled(true);\r
178                                                 hide();\r
179                                         } else {\r
180 \r
181                                                 fileNameToUse = getFilename(upload.getFilename());\r
182                                                 String apath;\r
183                                                 FileResource selectedFile = getFileForName(fileNameToUse);\r
184                                                 if (selectedFile == null ) {\r
185                                                         //we are going to create a file\r
186                                                         apath = folder.getUri();\r
187                                                         if (!apath.endsWith("/"))\r
188                                                                 apath = apath + "/";\r
189                                                         apath = apath + encodeComponent(fileNameToUse);\r
190                                                 } else\r
191                                                         apath = selectedFile.getUri();\r
192                                                 form.setAction(apath);\r
193                                                 String dateString = RestCommand.getDate();\r
194                                                 String resource = apath.substring(app.getApiPath().length() - 1, apath.length());\r
195                                                 String sig = RestCommand.calculateSig("POST", dateString, resource, RestCommand.base64decode(app.getToken()));\r
196                                                 date.setValue(dateString);\r
197                                                 auth.setValue(app.getCurrentUserResource().getUsername() + " " + sig);\r
198                                                 GWT.log("FolderPATH:" + folder.getUri(), null);\r
199                                                 submit.setEnabled(false);\r
200                                                 upload.setVisible(false);\r
201                                                 filenameLabel.setText(fileNameToUse);\r
202                                                 filenameLabel.setVisible(true);\r
203                                                 repeater.start();\r
204                                                 progressBar.setVisible(true);\r
205                                         }\r
206                                 }\r
207                         }\r
208 \r
209                         public void onSubmitComplete(final FormSubmitCompleteEvent event) {\r
210                                 // When the form submission is successfully completed, this\r
211                                 // event is fired. Assuming the service returned a response\r
212                                 // of type text/html, we can get the result text here (see\r
213                                 // the FormPanel documentation for further explanation).\r
214                                 String results = event.getResults();\r
215 \r
216                                 // Unfortunately the results are never empty, even in\r
217                                 // the absense of errors, so we have to check for '<pre></pre>'.\r
218                                 if (!results.equalsIgnoreCase("<pre></pre>")) {\r
219                                         GWT.log(results, null);\r
220                                         GSS.get().displayError(results);\r
221                                 }\r
222                                 progressBar.setProgress(100);\r
223                                 cancelUpload();\r
224                                 GSS.get().showFileList(true);\r
225                                 GSS.get().getStatusPanel().updateStats();\r
226                         }\r
227                 });\r
228 \r
229                 panel.add(buttons);\r
230                 progressBar = new ProgressBar(50, ProgressBar.SHOW_TIME_REMAINING);\r
231                 panel.add(progressBar);\r
232                 progressBar.setVisible(false);\r
233                 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);\r
234                 panel.setCellHorizontalAlignment(progressBar, HasHorizontalAlignment.ALIGN_CENTER);\r
235                 panel.addStyleName("gss-DialogBox");\r
236                 addStyleName("gss-DialogBox");\r
237                 setWidget(form);\r
238         }\r
239 \r
240         @Override\r
241         public boolean onKeyDownPreview(char key, int modifiers) {\r
242                 // Use the popup's key preview hooks to close the dialog when either\r
243                 // enter or escape is pressed.\r
244                 switch (key) {\r
245                         case KeyboardListener.KEY_ENTER:\r
246                                 prepareAndSubmit();\r
247                                 break;\r
248                         case KeyboardListener.KEY_ESCAPE:\r
249                                 cancelUpload();\r
250                                 break;\r
251                 }\r
252 \r
253                 return true;\r
254         }\r
255 \r
256         /**\r
257          * Cancels the file upload.\r
258          */\r
259         private void cancelUpload() {\r
260                 repeater.finish();\r
261                 hide();\r
262         }\r
263 \r
264         /**\r
265          * Make any last minute checks and start the upload.\r
266          */\r
267         public void prepareAndSubmit() {\r
268                 final String fname = getFilename(upload.getFilename());\r
269                 if (getFileForName(fname) == null) {\r
270                         //we are going to create a file, so we check to see if there is a trashed file with the same name\r
271                         FileResource same = null;\r
272                         for (FileResource fres : folder.getFiles())\r
273                                 if (fres.isDeleted() && fres.getName().equals(fname))\r
274                                         same = fres;\r
275                         if (same == null)\r
276                                 form.submit();\r
277                         else {\r
278                                 final FileResource sameFile = same;\r
279                                 GWT.log("Same deleted file", null);\r
280                                 ConfirmationDialog confirm = new ConfirmationDialog("A file with " +\r
281                                                 "the same name exists in the trash. If you continue,<br/>the trashed " +\r
282                                                 "file  '" + fname + "' will be renamed automatically for you.", "Continue") {\r
283 \r
284                                         @Override\r
285                                         public void cancel() {\r
286                                                 FileUploadDialog.this.hide();\r
287                                         }\r
288 \r
289                                         @Override\r
290                                         public void confirm() {\r
291                                                 updateTrashedFile(getBackupFilename(fname), sameFile);\r
292                                         }\r
293 \r
294                                 };\r
295                                 confirm.center();\r
296                         }\r
297                 }\r
298                 else {\r
299                         // We are going to update an existing file, so show a confirmation dialog.\r
300                         ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +\r
301                                         "you want to update " + fname + "?", "Update") {\r
302 \r
303                                 @Override\r
304                                 public void cancel() {\r
305                                         FileUploadDialog.this.hide();\r
306                                 }\r
307 \r
308                                 @Override\r
309                                 public void confirm() {\r
310                                         form.submit();\r
311                                 }\r
312 \r
313                         };\r
314                         confirm.center();\r
315                 }\r
316         }\r
317 \r
318         /**\r
319          * Returns the file name from a potential full path argument. Apparently IE\r
320          * insists on sending the full path name of a file when uploading, forcing\r
321          * us to trim the extra path info. Since this is only observed on Windows we\r
322          * get to check for a single path separator value.\r
323          *\r
324          * @param name the potentially full path name of a file\r
325          * @return the file name without extra path information\r
326          */\r
327         protected String getFilename(String name) {\r
328                 int pathSepIndex = name.lastIndexOf("\\");\r
329                 if (pathSepIndex == -1) {\r
330                         pathSepIndex = name.lastIndexOf("/");\r
331                         if (pathSepIndex == -1)\r
332                                 return name;\r
333                 }\r
334                 return name.substring(pathSepIndex + 1);\r
335         }\r
336 \r
337         /**\r
338          * Check whether the file name exists in selected folder.\r
339          *\r
340          * @return\r
341          */\r
342         private boolean canContinue() {\r
343                 if (files == null)\r
344                         return false;\r
345                 String fileName = getFilename(upload.getFilename());\r
346                 if (getFileForName(fileName) == null) {\r
347                         // For file creation, check to see if the file already exists.\r
348                         GWT.log("filename to upload:" + fileName, null);\r
349                         for (FileResource dto : files) {\r
350                                 GWT.log("Check:" + dto.getName() + "/" + fileName, null);\r
351                                 if (!dto.isDeleted() && dto.getName().equals(fileName)) {\r
352                                         cancelEvent = true;\r
353                                         return true;\r
354                                 }\r
355                         }\r
356                 }\r
357                 return true;\r
358         }\r
359 \r
360         class RepeatingTimer extends Timer {\r
361 \r
362                 private Updateable updateable;\r
363 \r
364                 private int interval = 1500;\r
365 \r
366                 private boolean running = true;\r
367 \r
368                 RepeatingTimer(Updateable _updateable, int _interval) {\r
369                         updateable = _updateable;\r
370                         interval = _interval;\r
371                 }\r
372 \r
373                 @Override\r
374                 public void run() {\r
375                         updateable.update();\r
376                 }\r
377 \r
378                 public void start() {\r
379                         running = true;\r
380 \r
381                         scheduleRepeating(interval);\r
382                 }\r
383 \r
384                 public void finish() {\r
385                         running = false;\r
386                         cancel();\r
387                 }\r
388 \r
389                 public int getInterval() {\r
390                         return interval;\r
391                 }\r
392 \r
393                 public void setInterval(int anInterval) {\r
394                         if (interval != anInterval) {\r
395                                 interval = anInterval;\r
396                                 if (running) {\r
397                                         finish();\r
398                                         start();\r
399                                 }\r
400                         }\r
401                 }\r
402         }\r
403 \r
404         /* (non-Javadoc)\r
405          * @see gr.ebs.gss.client.Updateable#update()\r
406          */\r
407         public void update() {\r
408                 String apath = folder.getUri();\r
409                 if (!apath.endsWith("/"))\r
410                         apath = apath + "/";\r
411                 apath = apath + encodeComponent(fileNameToUse) + "?progress=" + encodeComponent(fileNameToUse);\r
412                 GetCommand eg = new GetCommand<UploadStatusResource>(UploadStatusResource.class, apath, false) {\r
413 \r
414                         @Override\r
415                         public void onComplete() {\r
416                                 UploadStatusResource res = getResult();\r
417                                 progressBar.setProgress(res.percent());\r
418                         }\r
419 \r
420                         @Override\r
421                         public void onError(Throwable t) {\r
422                                 GWT.log("", t);\r
423                         }\r
424 \r
425                 };\r
426                 DeferredCommand.addCommand(eg);\r
427         }\r
428 \r
429         protected String getBackupFilename(String filename) {\r
430                 List<FileResource> filesInSameFolder = new ArrayList<FileResource>();\r
431                 for (FileResource deleted : folder.getFiles())\r
432                         if (deleted.isDeleted())\r
433                                 filesInSameFolder.add(deleted);\r
434                 int i = 1;\r
435                 for (FileResource same : filesInSameFolder)\r
436                         if (same.getName().startsWith(filename)) {\r
437                                 String toCheck = same.getName().substring(filename.length(), same.getName().length());\r
438                                 if (toCheck.startsWith(" ")) {\r
439                                         int test = -1;\r
440                                         try {\r
441                                                 test = Integer.valueOf(toCheck.replace(" ", ""));\r
442                                         } catch (NumberFormatException e) {\r
443                                                 // Do nothing since string is not a number.\r
444                                         }\r
445                                         if (test >= i)\r
446                                                 i = test + 1;\r
447                                 }\r
448                         }\r
449 \r
450                 return filename + " " + i;\r
451         }\r
452 \r
453         /**\r
454          * Rename the conflicting trashed file with the supplied new name.\r
455          */\r
456         private void updateTrashedFile(String newName, FileResource trashedFile) {\r
457                 JSONObject json = new JSONObject();\r
458                 json.put("name", new JSONString(newName));\r
459                 PostCommand cf = new PostCommand(trashedFile.getUri() + "?update=", json.toString(), 200) {\r
460 \r
461                         @Override\r
462                         public void onComplete() {\r
463                                 form.submit();\r
464                         }\r
465 \r
466                         @Override\r
467                         public void onError(Throwable t) {\r
468                                 GSS app = GSS.get();\r
469                                 GWT.log("", t);\r
470                                 if (t instanceof RestException) {\r
471                                         int statusCode = ((RestException) t).getHttpStatusCode();\r
472                                         if (statusCode == 405)\r
473                                                 app.displayError("You don't have the necessary permissions");\r
474                                         else if (statusCode == 404)\r
475                                                 app.displayError("User in permissions does not exist");\r
476                                         else if (statusCode == 409)\r
477                                                 app.displayError("A file with the same name already exists");\r
478                                         else if (statusCode == 413)\r
479                                                 app.displayError("Your quota has been exceeded");\r
480                                         else\r
481                                                 app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());\r
482                                 } else\r
483                                         app.displayError("System error modifying file:" + t.getMessage());\r
484                         }\r
485 \r
486                 };\r
487                 DeferredCommand.addCommand(cf);\r
488         }\r
489 \r
490         protected FileResource getFileForName(String name){\r
491                 for (FileResource f : folder.getFiles())\r
492                         if (!f.isDeleted() && f.getName().equals(name))\r
493                                 return f;\r
494                 return null;\r
495         }\r
496 \r
497 \r
498         /**\r
499          * Same as URL.encodeComponent, but also\r
500          * encode apostrophe since browsers aren't consistent about it\r
501          * (FF encodes, IE does not).\r
502          */\r
503         private String encodeComponent(String decodedURLComponent) {\r
504                 String retv = URL.encodeComponent(decodedURLComponent);\r
505                 retv = retv.replaceAll("'", "%27");\r
506                 return retv;\r
507         }\r
508 \r
509         /**\r
510          * Modify the files.\r
511          *\r
512          * @param newFiles the files to set\r
513          */\r
514         public void setFiles(List<FileResource> newFiles) {\r
515                 files = newFiles;\r
516         }\r
517 }\r