Got file info from headers
[pithos] / web_client / src / gr / grnet / pithos / web / client / GSS.java
1 /*
2  * Copyright (c) 2011 Greek Research and Technology Network
3  */
4 package gr.grnet.pithos.web.client;
5
6 import com.google.gwt.core.client.Scheduler;
7 import com.google.gwt.core.client.Scheduler.ScheduledCommand;
8 import com.google.gwt.view.client.SelectionChangeEvent;
9 import com.google.gwt.view.client.SingleSelectionModel;
10 import gr.grnet.pithos.web.client.clipboard.Clipboard;
11 import gr.grnet.pithos.web.client.commands.GetUserCommand;
12 import gr.grnet.pithos.web.client.foldertree.AccountResource;
13 import gr.grnet.pithos.web.client.foldertree.File;
14 import gr.grnet.pithos.web.client.foldertree.Folder;
15 import gr.grnet.pithos.web.client.foldertree.FolderTreeView;
16 import gr.grnet.pithos.web.client.foldertree.FolderTreeViewModel;
17 import gr.grnet.pithos.web.client.rest.GetRequest;
18 import gr.grnet.pithos.web.client.rest.RestException;
19 import gr.grnet.pithos.web.client.rest.resource.FileResource;
20 import gr.grnet.pithos.web.client.rest.resource.OtherUserResource;
21 import gr.grnet.pithos.web.client.rest.resource.RestResource;
22 import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
23 import gr.grnet.pithos.web.client.rest.resource.SharedResource;
24 import gr.grnet.pithos.web.client.rest.resource.TrashResource;
25 import gr.grnet.pithos.web.client.rest.resource.UserResource;
26
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33
34 import com.google.gwt.core.client.EntryPoint;
35 import com.google.gwt.core.client.GWT;
36 import com.google.gwt.event.logical.shared.ResizeEvent;
37 import com.google.gwt.event.logical.shared.ResizeHandler;
38 import com.google.gwt.event.logical.shared.SelectionEvent;
39 import com.google.gwt.event.logical.shared.SelectionHandler;
40 import com.google.gwt.http.client.URL;
41 import com.google.gwt.i18n.client.DateTimeFormat;
42 import com.google.gwt.resources.client.ClientBundle;
43 import com.google.gwt.resources.client.ImageResource;
44 import com.google.gwt.user.client.Cookies;
45 import com.google.gwt.user.client.DOM;
46 import com.google.gwt.user.client.Event;
47 import com.google.gwt.user.client.History;
48 import com.google.gwt.user.client.Window;
49 import com.google.gwt.user.client.ui.AbstractImagePrototype;
50 import com.google.gwt.user.client.ui.DecoratedTabPanel;
51 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
52 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
53 import com.google.gwt.user.client.ui.RootPanel;
54 import com.google.gwt.user.client.ui.TabPanel;
55 import com.google.gwt.user.client.ui.VerticalPanel;
56 import java.util.Set;
57
58 /**
59  * Entry point classes define <code>onModuleLoad()</code>.
60  */
61 public class GSS implements EntryPoint, ResizeHandler {
62
63         /**
64          * A constant that denotes the completion of an IncrementalCommand.
65          */
66         public static final boolean DONE = false;
67
68         public static final int VISIBLE_FILE_COUNT = 25;
69
70         /**
71          * Instantiate an application-level image bundle. This object will provide
72          * programmatic access to all the images needed by widgets.
73          */
74         private static Images images = (Images) GWT.create(Images.class);
75
76     public String getUsername() {
77         return username;
78     }
79
80     public void setAccount(AccountResource acct) {
81         account = acct;
82     }
83
84     public AccountResource getAccount() {
85         return account;
86     }
87
88     /**
89          * An aggregate image bundle that pulls together all the images for this
90          * application into a single bundle.
91          */
92         public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, Search.Images, CellTreeView.Images {
93
94                 @Source("gr/grnet/pithos/resources/document.png")
95                 ImageResource folders();
96
97                 @Source("gr/grnet/pithos/resources/edit_group_22.png")
98                 ImageResource groups();
99
100                 @Source("gr/grnet/pithos/resources/search.png")
101                 ImageResource search();
102         }
103
104         /**
105          * The single GSS instance.
106          */
107         private static GSS singleton;
108
109         /**
110          * Gets the singleton GSS instance.
111          *
112          * @return the GSS object
113          */
114         public static GSS get() {
115                 if (GSS.singleton == null)
116                         GSS.singleton = new GSS();
117                 return GSS.singleton;
118         }
119
120         /**
121          * The Application Clipboard implementation;
122          */
123         private Clipboard clipboard = new Clipboard();
124
125         private UserResource currentUserResource;
126
127         /**
128          * The top panel that contains the menu bar.
129          */
130         private TopPanel topPanel;
131
132         /**
133          * The panel that contains the various system messages.
134          */
135         private MessagePanel messagePanel = new MessagePanel(GSS.images);
136
137         /**
138          * The bottom panel that contains the status bar.
139          */
140         private StatusPanel statusPanel = null;
141
142         /**
143          * The top right panel that displays the logged in user details
144          */
145         private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
146
147         /**
148          * The file list widget.
149          */
150         private FileList fileList;
151
152         /**
153          * The tab panel that occupies the right side of the screen.
154          */
155         private TabPanel inner = new DecoratedTabPanel(){
156                 
157                 public void onBrowserEvent(com.google.gwt.user.client.Event event) {
158                         if (DOM.eventGetType(event) == Event.ONCONTEXTMENU){
159                                 if(isFileListShowing()){
160                                         getFileList().showContextMenu(event);
161                                 }
162                         }
163                 };
164         };
165
166         /**
167          * The split panel that will contain the left and right panels.
168          */
169         private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
170
171         /**
172          * The widget that displays the tree of folders.
173          */
174         
175         private CellTreeView treeView = null;
176         /**
177          * The currently selected item in the application, for use by the Edit menu
178          * commands. Potential types are Folder, File, User and Group.
179          */
180         private Object currentSelection;
181
182
183         /**
184          * The WebDAV password of the current user
185          */
186         private String webDAVPassword;
187
188         public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
189
190     private String username = null;
191
192     /**
193      * The authentication token of the current user.
194      */
195     private String token;
196
197     private SingleSelectionModel<Folder> folderTreeSelectionModel;
198     private FolderTreeViewModel folderTreeViewModel;
199     private FolderTreeView folderTreeView;
200
201     private AccountResource account;
202
203         @Override
204         public void onModuleLoad() {
205                 // Initialize the singleton before calling the constructors of the
206                 // various widgets that might call GSS.get().
207                 singleton = this;
208                 if (parseUserCredentials())
209             initialize();
210         }
211
212     private void initialize() {
213         topPanel = new TopPanel(GSS.images);
214         topPanel.setWidth("100%");
215
216         messagePanel.setWidth("100%");
217         messagePanel.setVisible(false);
218
219
220         // Inner contains the various lists.
221         inner.sinkEvents(Event.ONCONTEXTMENU);
222         inner.setAnimationEnabled(true);
223         inner.getTabBar().addStyleName("pithos-MainTabBar");
224         inner.getDeckPanel().addStyleName("pithos-MainTabPanelBottom");
225
226         inner.setWidth("100%");
227
228         inner.addSelectionHandler(new SelectionHandler<Integer>() {
229
230             @Override
231             public void onSelection(SelectionEvent<Integer> event) {
232                 int tabIndex = event.getSelectedItem();
233                 switch (tabIndex) {
234                     case 0:
235                         fileList.updateCurrentlyShowingStats();
236                         break;
237                 }
238             }
239         });
240
241         folderTreeSelectionModel = new SingleSelectionModel<Folder>();
242         folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
243             @Override
244             public void onSelectionChange(SelectionChangeEvent event) {
245                 Folder f = folderTreeSelectionModel.getSelectedObject();
246                 showFiles(f);
247             }
248         });
249
250         folderTreeViewModel = new FolderTreeViewModel(folderTreeSelectionModel);
251         folderTreeView = new FolderTreeView(folderTreeViewModel);
252
253         fileList = new FileList(images, folderTreeView);
254         inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
255
256         // Add the left and right panels to the split panel.
257         splitPanel.setLeftWidget(folderTreeView);
258         splitPanel.setRightWidget(inner);
259         splitPanel.setSplitPosition("25%");
260         splitPanel.setSize("100%", "100%");
261         splitPanel.addStyleName("pithos-splitPanel");
262
263         // Create a dock panel that will contain the menu bar at the top,
264         // the shortcuts to the left, the status bar at the bottom and the
265         // right panel taking the rest.
266         VerticalPanel outer = new VerticalPanel();
267         outer.add(topPanel);
268         outer.add(messagePanel);
269         outer.add(splitPanel);
270         statusPanel = new StatusPanel(GSS.images);
271         outer.add(statusPanel);
272         outer.setWidth("100%");
273         outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
274
275         outer.setSpacing(4);
276
277         // Hook the window resize event, so that we can adjust the UI.
278         Window.addResizeHandler(this);
279         // Clear out the window's built-in margin, because we want to take
280         // advantage of the entire client area.
281         Window.setMargin("0px");
282         // Finally, add the outer panel to the RootPanel, so that it will be
283         // displayed.
284         RootPanel.get().add(outer);
285         // Call the window resized handler to get the initial sizes setup. Doing
286         // this in a deferred command causes it to occur after all widgets'
287         // sizes have been computed by the browser.
288         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
289
290             @Override
291             public void execute() {
292                 onWindowResized(Window.getClientHeight());
293             }
294         });
295
296         Scheduler.get().scheduleDeferred(new ScheduledCommand() {
297             @Override
298             public void execute() {
299                 fetchAccount();
300             }
301         });
302     }
303
304     private void showFiles(Folder f) {
305         inner.selectTab(0);
306         Set<File> files = f.getFiles();
307         Iterator<File> iter = files.iterator();
308         fetchFile(iter, files);
309     }
310
311     private void fetchFile(final Iterator<File> iter, final Set<File> files) {
312         if (iter.hasNext()) {
313             File file = iter.next();
314             String path = getApiPath() + username + "/" + file.getContainer() + "/" + file.getPath() + "?format=json";
315             GetRequest<File> getFile = new GetRequest<File>(File.class, path, file) {
316                 @Override
317                 public void onSuccess(File result) {
318                     fetchFile(iter, files);
319                 }
320
321                 @Override
322                 public void onError(Throwable t) {
323                     GWT.log("Error getting file", t);
324                     if (t instanceof RestException)
325                         GSS.get().displayError("Error getting file: " + ((RestException) t).getHttpStatusText());
326                     else
327                         GSS.get().displayError("System error fetching file: " + t.getMessage());
328                 }
329             };
330             getFile.setHeader("X-Auth-Token", "0000");
331             Scheduler.get().scheduleDeferred(getFile);
332         }
333         else
334             fileList.setFiles(new ArrayList<File>(files));
335     }
336
337     /**
338          * Parse and store the user credentials to the appropriate fields.
339          */
340         private boolean parseUserCredentials() {
341                 Configuration conf = (Configuration) GWT.create(Configuration.class);
342                 String cookie = conf.authCookie();
343                 String auth = Cookies.getCookie(cookie);
344                 if (auth == null) {
345                         authenticateUser();
346             return false;
347         }
348         else {
349             String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
350             if (authSplit.length != 2) {
351                 authenticateUser();
352                 return false;
353             }
354             else {
355                 username = authSplit[0];
356                 token = authSplit[1];
357                 return true;
358             }
359         }
360         }
361
362     /**
363          * Redirect the user to the login page for authentication.
364          */
365         protected void authenticateUser() {
366                 Configuration conf = (Configuration) GWT.create(Configuration.class);
367
368 //        Window.Location.assign(GWT.getModuleBaseURL() + conf.loginUrl() + "?next=" + Window.Location.getHref());
369         Cookies.setCookie(conf.authCookie(), "test" + conf.cookieSeparator() + "0000");
370         Window.Location.assign(GWT.getModuleBaseURL() + "GSS.html");
371         }
372
373     private void fetchAccount() {
374         String path = getApiPath() + username + "?format=json";
375
376         GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, path) {
377             @Override
378             public void onSuccess(AccountResource result) {
379                 account = result;
380                 statusPanel.displayStats(account);
381                 folderTreeViewModel.initialize(account);
382                 inner.selectTab(0);
383             }
384
385             @Override
386             public void onError(Throwable t) {
387                 GWT.log("Error getting account", t);
388                 if (t instanceof RestException)
389                     GSS.get().displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
390                 else
391                     GSS.get().displayError("System error fetching user data: " + t.getMessage());
392             }
393         };
394         getAccount.setHeader("X-Auth-Token", token);
395         Scheduler.get().scheduleDeferred(getAccount);
396     }
397
398         /**
399          * Clear the cookie and redirect the user to the logout page.
400          */
401         void logout() {
402                 Configuration conf = (Configuration) GWT.create(Configuration.class);
403                 String cookie = conf.authCookie();
404                 String domain = Window.Location.getHostName();
405                 String path = Window.Location.getPath();
406                 Cookies.setCookie(cookie, "", null, domain, path, false);
407         String baseUrl = GWT.getModuleBaseURL();
408         String homeUrl = baseUrl.substring(0, baseUrl.indexOf(path));
409                 Window.Location.assign(homeUrl + conf.logoutUrl());
410         }
411
412         /**
413          * Creates an HTML fragment that places an image & caption together, for use
414          * in a group header.
415          *
416          * @param imageProto an image prototype for an image
417          * @param caption the group caption
418          * @return the header HTML fragment
419          */
420         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
421                 String captionHTML = "<table class='caption' cellpadding='0' " 
422                 + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() 
423                 + "</td><td id =" + caption +" class='rcaption'><b style='white-space:nowrap'>&nbsp;" 
424                 + caption + "</b></td></tr></table>";
425                 return captionHTML;
426         }
427
428         private void onWindowResized(int height) {
429                 // Adjust the split panel to take up the available room in the window.
430                 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
431                 if (newHeight < 1)
432                         newHeight = 1;
433                 splitPanel.setHeight("" + newHeight);
434                 inner.setHeight("" + newHeight);
435         }
436
437         @Override
438         public void onResize(ResizeEvent event) {
439                 int height = event.getHeight();
440                 onWindowResized(height);
441         }
442
443         public boolean isFileListShowing() {
444                 int tab = inner.getTabBar().getSelectedTab();
445                 if (tab == 0)
446                         return true;
447                 return false;
448         }
449
450         public boolean isSearchResultsShowing() {
451                 int tab = inner.getTabBar().getSelectedTab();
452                 if (tab == 2)
453                         return true;
454                 return false;
455         }
456
457         /**
458          * Make the file list visible.
459          *
460          * @param update
461          */
462         public void showFileList(boolean update) {
463                 if(update){
464                         getTreeView().refreshCurrentNode(true);
465                 }
466                 else{
467                         RestResource currentFolder = getTreeView().getSelection();
468                         if(currentFolder!=null){
469                                 showFileList(currentFolder);
470                 }
471                 }
472
473         }
474         
475         public void showFileList(RestResource r) {
476                 showFileList(r,true);
477         }
478         
479         public void showFileList(RestResource r, boolean clearSelection) {
480                 RestResource currentFolder = r;
481                 if(currentFolder!=null){
482                         List<FileResource> files = null;
483                         if (currentFolder instanceof RestResourceWrapper) {
484                                 RestResourceWrapper folder = (RestResourceWrapper) currentFolder;
485                                 files = folder.getResource().getFiles();
486                         }
487                 }
488                 inner.selectTab(0);
489         }
490
491         /**
492          * Display the 'loading' indicator.
493          */
494         public void showLoadingIndicator(String message, String path) {
495                 if(path!=null){
496                         String[] split = path.split("/");
497                         message = message +" "+URL.decode(split[split.length-1]);
498                 }
499                 topPanel.getLoading().show(message);
500         }
501
502         /**
503          * Hide the 'loading' indicator.
504          */
505         public void hideLoadingIndicator() {
506                 topPanel.getLoading().hide();
507         }
508
509         /**
510          * A native JavaScript method to reach out to the browser's window and
511          * invoke its resizeTo() method.
512          *
513          * @param x the new width
514          * @param y the new height
515          */
516         public static native void resizeTo(int x, int y) /*-{
517                 $wnd.resizeTo(x,y);
518         }-*/;
519
520         /**
521          * A helper method that returns true if the user's list is currently visible
522          * and false if it is hidden.
523          *
524          * @return true if the user list is visible
525          */
526         public boolean isUserListVisible() {
527                 return inner.getTabBar().getSelectedTab() == 1;
528         }
529
530         /**
531          * Display an error message.
532          *
533          * @param msg the message to display
534          */
535         public void displayError(String msg) {
536                 messagePanel.displayError(msg);
537         }
538
539         /**
540          * Display a warning message.
541          *
542          * @param msg the message to display
543          */
544         public void displayWarning(String msg) {
545                 messagePanel.displayWarning(msg);
546         }
547
548         /**
549          * Display an informational message.
550          *
551          * @param msg the message to display
552          */
553         public void displayInformation(String msg) {
554                 messagePanel.displayInformation(msg);
555         }
556
557         /**
558          * Retrieve the folders.
559          *
560          * @return the folders
561          
562         public Folders getFolders() {
563                 return folders;
564         }*/
565
566         /**
567          * Retrieve the currentSelection.
568          *
569          * @return the currentSelection
570          */
571         public Object getCurrentSelection() {
572                 return currentSelection;
573         }
574
575         /**
576          * Modify the currentSelection.
577          *
578          * @param newCurrentSelection the currentSelection to set
579          */
580         public void setCurrentSelection(Object newCurrentSelection) {
581                 currentSelection = newCurrentSelection;
582         }
583
584         /**
585          * Retrieve the fileList.
586          *
587          * @return the fileList
588          */
589         public FileList getFileList() {
590                 return fileList;
591         }
592
593         /**
594          * Retrieve the topPanel.
595          *
596          * @return the topPanel
597          */
598         TopPanel getTopPanel() {
599                 return topPanel;
600         }
601
602         /**
603          * Retrieve the clipboard.
604          *
605          * @return the clipboard
606          */
607         public Clipboard getClipboard() {
608                 return clipboard;
609         }
610
611         public StatusPanel getStatusPanel() {
612                 return statusPanel;
613         }
614
615         /**
616          * Retrieve the userDetailsPanel.
617          *
618          * @return the userDetailsPanel
619          */
620         public UserDetailsPanel getUserDetailsPanel() {
621                 return userDetailsPanel;
622         }
623
624         
625
626         public String getToken() {
627                 return token;
628         }
629
630         public String getWebDAVPassword() {
631                 return webDAVPassword;
632         }
633
634         /**
635          * Retrieve the currentUserResource.
636          *
637          * @return the currentUserResource
638          */
639         public UserResource getCurrentUserResource() {
640                 return currentUserResource;
641         }
642
643         /**
644          * Modify the currentUserResource.
645          *
646          * @param newUser the new currentUserResource
647          */
648         public void setCurrentUserResource(UserResource newUser) {
649                 currentUserResource = newUser;
650         }
651
652         public static native void preventIESelection() /*-{
653                 $doc.body.onselectstart = function () { return false; };
654         }-*/;
655
656         public static native void enableIESelection() /*-{
657                 if ($doc.body.onselectstart != null)
658                 $doc.body.onselectstart = null;
659         }-*/;
660
661         /**
662          * @return the absolute path of the API root URL
663          */
664         public String getApiPath() {
665                 Configuration conf = (Configuration) GWT.create(Configuration.class);
666                 return conf.apiPath();
667         }
668
669         /**
670          * Convert server date to local time according to browser timezone
671          * and format it according to localized pattern.
672          * Time is always formatted to 24hr format.
673          * NB: This assumes that server runs in UTC timezone. Otherwise
674          * we would need to adjust for server time offset as well.
675          *
676          * @param date
677          * @return String
678          */
679         public static String formatLocalDateTime(Date date) {
680                 Date convertedDate = new Date(date.getTime() - date.getTimezoneOffset());
681                 final DateTimeFormat dateFormatter = DateTimeFormat.getShortDateFormat();
682                 final DateTimeFormat timeFormatter = DateTimeFormat.getFormat("HH:mm");
683                 String datePart = dateFormatter.format(convertedDate);
684                 String timePart = timeFormatter.format(convertedDate);
685                 return datePart + " " + timePart;
686         }
687         
688         /**
689          * History support for folder navigation
690          * adds a new browser history entry
691          *
692          * @param key
693          */
694         public void updateHistory(String key){
695 //              Replace any whitespace of the initial string to "+"
696 //              String result = key.replaceAll("\\s","+");
697 //              Add a new browser history entry.
698 //              History.newItem(result);
699                 History.newItem(key);
700         }
701
702         /**
703          * This method examines the token input and add a "/" at the end in case it's omitted.
704          * This happens only in Files/trash/, Files/shared/, Files/others.
705          *
706          * @param tokenInput
707          * @return the formated token with a "/" at the end or the same tokenInput parameter
708          */
709
710         private String handleSpecialFolderNames(String tokenInput){
711                 List<String> pathsToCheck = Arrays.asList("Files/trash", "Files/shared", "Files/others");
712                 if(pathsToCheck.contains(tokenInput))
713                         return tokenInput + "/";
714                 return tokenInput;
715
716         }
717
718         /**
719          * Reject illegal resource names, like '.' or '..' or slashes '/'.
720          */
721         static boolean isValidResourceName(String name) {
722                 if (".".equals(name) || "..".equals(name) || name.contains("/"))
723                         return false;
724                 return true;
725         }
726
727         public void putUserToMap(String _userName, String _userFullName){
728                 userFullNameMap.put(_userName, _userFullName);
729         }
730
731         public String findUserFullName(String _userName){
732                 return userFullNameMap.get(_userName);
733         }
734         public String getUserFullName(String _userName) {
735                 
736         if (GSS.get().findUserFullName(_userName) == null)
737                 //if there is no userFullName found then the map fills with the given _userName,
738                 //so userFullName = _userName
739                 GSS.get().putUserToMap(_userName, _userName);
740         else if(GSS.get().findUserFullName(_userName).indexOf('@') != -1){
741                 //if the userFullName = _userName the GetUserCommand updates the userFullName in the map
742                 GetUserCommand guc = new GetUserCommand(_userName);
743                 guc.execute();
744         }
745         return GSS.get().findUserFullName(_userName);
746         }
747         /**
748          * Retrieve the treeView.
749          *
750          * @return the treeView
751          */
752         public CellTreeView getTreeView() {
753                 return treeView;
754         }
755         
756         public void onResourceUpdate(RestResource resource,boolean clearSelection){
757                 if(resource instanceof RestResourceWrapper || resource instanceof OtherUserResource || resource instanceof TrashResource || resource instanceof SharedResource){
758                         if(getTreeView().getSelection()!=null&&getTreeView().getSelection().getUri().equals(resource.getUri()))
759                                 showFileList(resource,clearSelection);
760                 }
761                 
762         }
763 }