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