Only clear the cookie when the user logs out. This way a user only needs to login...
[pithos] / src / gr / ebs / gss / client / GSS.java
1 /*
2  * Copyright 2007, 2008, 2009, 2010 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.clipboard.Clipboard;
22 import gr.ebs.gss.client.dnd.DnDFocusPanel;
23 import gr.ebs.gss.client.dnd.DnDSimpleFocusPanel;
24 import gr.ebs.gss.client.rest.GetCommand;
25 import gr.ebs.gss.client.rest.RestException;
26 import gr.ebs.gss.client.rest.resource.FileResource;
27 import gr.ebs.gss.client.rest.resource.FolderResource;
28 import gr.ebs.gss.client.rest.resource.TrashResource;
29 import gr.ebs.gss.client.rest.resource.UserResource;
30
31 import java.util.Iterator;
32 import java.util.List;
33
34 import com.allen_sauer.gwt.dnd.client.DragContext;
35 import com.allen_sauer.gwt.dnd.client.PickupDragController;
36 import com.allen_sauer.gwt.dnd.client.VetoDragException;
37 import com.google.gwt.core.client.EntryPoint;
38 import com.google.gwt.core.client.GWT;
39 import com.google.gwt.event.logical.shared.ResizeEvent;
40 import com.google.gwt.event.logical.shared.ResizeHandler;
41 import com.google.gwt.event.logical.shared.SelectionEvent;
42 import com.google.gwt.event.logical.shared.SelectionHandler;
43 import com.google.gwt.resources.client.ClientBundle;
44 import com.google.gwt.resources.client.ImageResource;
45 import com.google.gwt.user.client.Command;
46 import com.google.gwt.user.client.Cookies;
47 import com.google.gwt.user.client.DOM;
48 import com.google.gwt.user.client.DeferredCommand;
49 import com.google.gwt.user.client.History;
50 import com.google.gwt.user.client.Window;
51 import com.google.gwt.user.client.ui.AbsolutePanel;
52 import com.google.gwt.user.client.ui.AbstractImagePrototype;
53 import com.google.gwt.user.client.ui.DecoratedTabPanel;
54 import com.google.gwt.user.client.ui.DockPanel;
55 import com.google.gwt.user.client.ui.HTML;
56 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
57 import com.google.gwt.user.client.ui.HasVerticalAlignment;
58 import com.google.gwt.user.client.ui.HorizontalSplitPanel;
59 import com.google.gwt.user.client.ui.Label;
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.TreeItem;
63 import com.google.gwt.user.client.ui.VerticalPanel;
64 import com.google.gwt.user.client.ui.Widget;
65
66 /**
67  * Entry point classes define <code>onModuleLoad()</code>.
68  */
69 public class GSS implements EntryPoint, ResizeHandler {
70
71         /**
72          * A constant that denotes the completion of an IncrementalCommand.
73          */
74         public static final boolean DONE = false;
75
76         public static final int VISIBLE_FILE_COUNT = 100;
77
78         /**
79          * Instantiate an application-level image bundle. This object will provide
80          * programmatic access to all the images needed by widgets.
81          */
82         private static Images images = (Images) GWT.create(Images.class);
83
84         private GlassPanel glassPanel = new GlassPanel();
85
86         /**
87          * An aggregate image bundle that pulls together all the images for this
88          * application into a single bundle.
89          */
90         public interface Images extends ClientBundle, TopPanel.Images, StatusPanel.Images, FileMenu.Images, EditMenu.Images, SettingsMenu.Images, GroupMenu.Images, FilePropertiesDialog.Images, MessagePanel.Images, FileList.Images, SearchResults.Images, Search.Images, Groups.Images, Folders.Images {
91
92                 @Source("gr/ebs/gss/resources/document.png")
93                 ImageResource folders();
94
95                 @Source("gr/ebs/gss/resources/edit_group_22.png")
96                 ImageResource groups();
97
98                 @Source("gr/ebs/gss/resources/search.png")
99                 ImageResource search();
100         }
101
102         /**
103          * The single GSS instance.
104          */
105         private static GSS singleton;
106
107         /**
108          * Gets the singleton GSS instance.
109          *
110          * @return the GSS object
111          */
112         public static GSS get() {
113                 if (GSS.singleton == null)
114                         GSS.singleton = new GSS();
115                 return GSS.singleton;
116         }
117
118         /**
119          * The Application Clipboard implementation;
120          */
121         private Clipboard clipboard = new Clipboard();
122
123         private UserResource currentUserResource;
124
125         /**
126          * The top panel that contains the menu bar.
127          */
128         private TopPanel topPanel;
129
130         /**
131          * The panel that contains the various system messages.
132          */
133         private MessagePanel messagePanel = new MessagePanel(GSS.images);
134
135         /**
136          * The bottom panel that contains the status bar.
137          */
138         private StatusPanel statusPanel = new StatusPanel(GSS.images);
139
140         /**
141          * The top right panel that displays the logged in user details
142          */
143         private UserDetailsPanel userDetailsPanel = new UserDetailsPanel();
144
145         /**
146          * The file list widget.
147          */
148         private FileList fileList;
149
150         /**
151          * The group list widget.
152          */
153         private Groups groups = new Groups(images);
154
155         /**
156          * The search result widget.
157          */
158         private SearchResults searchResults;
159
160         /**
161          * The tab panel that occupies the right side of the screen.
162          */
163         private TabPanel inner = new DecoratedTabPanel();
164
165         /**
166          * The split panel that will contain the left and right panels.
167          */
168         private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
169
170         /**
171          * The horizontal panel that will contain the search and status panels.
172          */
173         private DockPanel searchStatus = new DockPanel();
174
175         /**
176          * The search widget.
177          */
178         private Search search;
179
180         /**
181          * The widget that displays the tree of folders.
182          */
183         private Folders folders = new Folders(images);
184
185         /**
186          * The currently selected item in the application, for use by the Edit menu
187          * commands. Potential types are Folder, File, User and Group.
188          */
189         private Object currentSelection;
190
191         /**
192          * The authentication token of the current user.
193          */
194         private String token;
195
196         /**
197          * The WebDAV password of the current user
198          */
199         private String webDAVPassword;
200
201         private PickupDragController dragController;
202
203         public void onModuleLoad() {
204                 // Initialize the singleton before calling the constructors of the
205                 // various widgets that might call GSS.get().
206                 singleton = this;
207                 RootPanel.get().add(glassPanel, 0, 0);
208                 parseUserCredentials();
209                 dragController = new PickupDragController(RootPanel.get(), false) {
210
211                         @Override
212                         public void previewDragStart() throws VetoDragException {
213                                 super.previewDragStart();
214                                 if (context.selectedWidgets.isEmpty())
215                                         throw new VetoDragException();
216
217                                 if (context.draggable != null)
218                                         if (context.draggable instanceof DnDFocusPanel) {
219                                                 DnDFocusPanel toDrop = (DnDFocusPanel) context.draggable;
220                                                 // prevent drag and drop for trashed files and for
221                                                 // unselected tree items
222                                                 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
223                                                         throw new VetoDragException();
224                                                 else if (toDrop.getItem() != null && !toDrop.getItem().equals(folders.getCurrent()))
225                                                         throw new VetoDragException();
226                                                 else if (toDrop.getItem() != null && !toDrop.getItem().isDraggable())
227                                                         throw new VetoDragException();
228
229                                         } else if (context.draggable instanceof DnDSimpleFocusPanel) {
230                                                 DnDSimpleFocusPanel toDrop = (DnDSimpleFocusPanel) context.draggable;
231                                                 // prevent drag and drop for trashed files and for
232                                                 // unselected tree items
233                                                 if (toDrop.getFiles() != null && folders.isTrashItem(folders.getCurrent()))
234                                                         throw new VetoDragException();
235                                         }
236                         }
237
238                         @Override
239                         protected Widget newDragProxy(DragContext aContext) {
240                                 AbsolutePanel container = new AbsolutePanel();
241                                 DOM.setStyleAttribute(container.getElement(), "overflow", "visible");
242                                 for (Iterator iterator = aContext.selectedWidgets.iterator(); iterator.hasNext();) {
243                                         HTML html = null;
244                                         Widget widget = (Widget) iterator.next();
245                                         if (widget instanceof DnDFocusPanel) {
246                                                 DnDFocusPanel book = (DnDFocusPanel) widget;
247                                                 html = book.cloneHTML();
248                                         } else if (widget instanceof DnDSimpleFocusPanel) {
249                                                 DnDSimpleFocusPanel book = (DnDSimpleFocusPanel) widget;
250                                                 html = book.cloneHTML();
251                                         }
252                                         if (html == null)
253                                                 container.add(new Label("Drag ME"));
254                                         else
255                                                 container.add(html);
256                                 }
257                                 return container;
258                         }
259                 };
260                 dragController.setBehaviorDragProxy(true);
261                 dragController.setBehaviorMultipleSelection(false);
262                 topPanel = new TopPanel(GSS.images);
263                 topPanel.setWidth("100%");
264
265                 messagePanel.setWidth("100%");
266                 messagePanel.setVisible(false);
267
268                 search = new Search(images);
269                 searchStatus.add(search, DockPanel.WEST);
270                 searchStatus.add(userDetailsPanel, DockPanel.EAST);
271                 searchStatus.setCellHorizontalAlignment(userDetailsPanel, HasHorizontalAlignment.ALIGN_RIGHT);
272                 searchStatus.setCellVerticalAlignment(search, HasVerticalAlignment.ALIGN_MIDDLE);
273                 searchStatus.setCellVerticalAlignment(userDetailsPanel, HasVerticalAlignment.ALIGN_MIDDLE);
274                 searchStatus.setWidth("100%");
275
276                 fileList = new FileList(images);
277
278                 searchResults = new SearchResults(images);
279
280                 // Inner contains the various lists.
281                 inner.setAnimationEnabled(true);
282                 inner.getTabBar().addStyleName("gss-MainTabBar");
283                 inner.getDeckPanel().addStyleName("gss-MainTabPanelBottom");
284                 inner.add(fileList, createHeaderHTML(AbstractImagePrototype.create(images.folders()), "Files"), true);
285
286                 inner.add(groups, createHeaderHTML(AbstractImagePrototype.create(images.groups()), "Groups"), true);
287                 inner.add(searchResults, createHeaderHTML(AbstractImagePrototype.create(images.search()), "Search Results"), true);
288                 inner.setWidth("100%");
289                 inner.selectTab(0);
290
291                 inner.addSelectionHandler(new SelectionHandler<Integer>() {
292
293                         @Override
294                         public void onSelection(SelectionEvent<Integer> event) {
295                                 int tabIndex = event.getSelectedItem();
296                                 switch (tabIndex) {
297                                         case 0:
298                                                 fileList.clearSelectedRows();
299                                                 fileList.updateCurrentlyShowingStats();
300                                                 History.newItem("Files");
301                                                 break;
302                                         case 1:
303                                                 groups.updateCurrentlyShowingStats();
304                                                 History.newItem("Groups");
305                                                 break;
306                                         case 2:
307                                                 searchResults.clearSelectedRows();
308                                                 searchResults.updateCurrentlyShowingStats();
309                                                 History.newItem("Search");
310                                                 break;
311                                 }
312                         }
313                 });
314
315                 // Add the left and right panels to the split panel.
316                 splitPanel.setLeftWidget(folders);
317                 splitPanel.setRightWidget(inner);
318                 splitPanel.setSplitPosition("25%");
319                 splitPanel.setSize("100%", "100%");
320                 splitPanel.addStyleName("gss-splitPanel");
321
322                 // Create a dock panel that will contain the menu bar at the top,
323                 // the shortcuts to the left, the status bar at the bottom and the
324                 // right panel taking the rest.
325                 VerticalPanel outer = new VerticalPanel();
326                 outer.add(topPanel);
327                 outer.add(searchStatus);
328                 outer.add(messagePanel);
329                 outer.add(splitPanel);
330                 outer.add(statusPanel);
331                 outer.setWidth("100%");
332                 outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
333
334                 outer.setSpacing(4);
335
336                 // Hook the window resize event, so that we can adjust the UI.
337                 Window.addResizeHandler(this);
338                 // Clear out the window's built-in margin, because we want to take
339                 // advantage of the entire client area.
340                 Window.setMargin("0px");
341                 // Finally, add the outer panel to the RootPanel, so that it will be
342                 // displayed.
343                 RootPanel.get().add(outer);
344                 // Call the window resized handler to get the initial sizes setup. Doing
345                 // this in a deferred command causes it to occur after all widgets'
346                 // sizes have been computed by the browser.
347                 DeferredCommand.addCommand(new Command() {
348
349                         public void execute() {
350                                 onWindowResized(Window.getClientHeight());
351                         }
352                 });
353         }
354
355         /**
356          * Fetches the User object for the specified username.
357          *
358          * @param username the username of the user
359          */
360         private void fetchUser(final String username) {
361                 String path = getApiPath() + username + "/";
362                 GetCommand<UserResource> getUserCommand = new GetCommand<UserResource>(UserResource.class, username, path, null) {
363
364                         @Override
365                         public void onComplete() {
366                                 currentUserResource = getResult();
367                                 final String announcement = currentUserResource.getAnnouncement();
368                                 if (announcement != null)
369                                         DeferredCommand.addCommand(new Command() {
370
371                                                 public void execute() {
372                                                         displayInformation(announcement);
373                                                 }
374                                         });
375                         }
376
377                         @Override
378                         public void onError(Throwable t) {
379                                 GWT.log("Fetching user error", t);
380                                 if (t instanceof RestException)
381                                         GSS.get().displayError("No user found:" + ((RestException) t).getHttpStatusText());
382                                 else
383                                         GSS.get().displayError("System error fetching user data:" + t.getMessage());
384                                 authenticateUser();
385                         }
386                 };
387                 DeferredCommand.addCommand(getUserCommand);
388         }
389
390         /**
391          * Parse and store the user credentials to the appropriate fields.
392          */
393         private void parseUserCredentials() {
394                 Configuration conf = (Configuration) GWT.create(Configuration.class);
395                 String cookie = conf.authCookie();
396                 String auth = Cookies.getCookie(cookie);
397                 if (auth == null) {
398                         authenticateUser();
399                         // Redundant, but silences warnings about possible auth NPE, below.
400                         return;
401                 }
402                 int sepIndex = auth.indexOf(conf.cookieSeparator());
403                 if (sepIndex == -1)
404                         authenticateUser();
405                 token = auth.substring(sepIndex + 1, auth.length());
406                 final String username = auth.substring(0, sepIndex);
407                 if (username == null)
408                         authenticateUser();
409
410                 refreshWebDAVPassword();
411
412                 DeferredCommand.addCommand(new Command() {
413
414                         public void execute() {
415                                 fetchUser(username);
416                         }
417                 });
418         }
419
420         /**
421          * Redirect the user to the login page for authentication.
422          */
423         protected void authenticateUser() {
424                 Configuration conf = (Configuration) GWT.create(Configuration.class);
425                 Window.Location.assign(conf.loginUrl() + "?next=" + GWT.getModuleBaseURL());
426         }
427
428         /**
429          * Clear the cookie and redirect the user to the logout page.
430          */
431         void logout() {
432                 Configuration conf = (Configuration) GWT.create(Configuration.class);
433                 String cookie = conf.authCookie();
434                 String domain = Window.Location.getHostName();
435                 String path = Window.Location.getPath();
436                 Cookies.setCookie(cookie, "", null, domain, path, false);
437                 Window.Location.assign(conf.logoutUrl());
438         }
439
440         /**
441          * Creates an HTML fragment that places an image & caption together, for use
442          * in a group header.
443          *
444          * @param imageProto an image prototype for an image
445          * @param caption the group caption
446          * @return the header HTML fragment
447          */
448         private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
449                 String captionHTML = "<table class='caption' cellpadding='0' " + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML() + "</td><td class='rcaption'><b style='white-space:nowrap'>&nbsp;" + caption + "</b></td></tr></table>";
450                 return captionHTML;
451         }
452
453         private void onWindowResized(int height) {
454                 // Adjust the split panel to take up the available room in the window.
455                 int newHeight = height - splitPanel.getAbsoluteTop() - 44;
456                 if (newHeight < 1)
457                         newHeight = 1;
458                 splitPanel.setHeight("" + newHeight);
459         }
460
461         @Override
462         public void onResize(ResizeEvent event) {
463                 int height = event.getHeight();
464                 onWindowResized(height);
465         }
466
467         public boolean isFileListShowing() {
468                 int tab = inner.getTabBar().getSelectedTab();
469                 if (tab == 0)
470                         return true;
471                 return false;
472         }
473
474         public boolean isSearchResultsShowing() {
475                 int tab = inner.getTabBar().getSelectedTab();
476                 if (tab == 2)
477                         return true;
478                 return false;
479         }
480
481         /**
482          * Make the user list visible.
483          */
484         public void showUserList() {
485                 inner.selectTab(1);
486         }
487
488         /**
489          * Make the file list visible.
490          */
491         public void showFileList() {
492                 fileList.updateFileCache(false, true /*clear selection*/);
493                 inner.selectTab(0);
494         }
495
496         /**
497          * Make the file list visible.
498          *
499          * @param update
500          */
501         public void showFileList(boolean update) {
502                 TreeItem currentFolder = getFolders().getCurrent();
503                 if (currentFolder != null) {
504                         List<FileResource> files = null;
505                         Object cachedObject = currentFolder.getUserObject();
506                         if (cachedObject instanceof FolderResource) {
507                                 FolderResource folder = (FolderResource) cachedObject;
508                                 files = folder.getFiles();
509                         } else if (cachedObject instanceof TrashResource) {
510                                 TrashResource folder = (TrashResource) cachedObject;
511                                 files = folder.getFiles();
512                         }
513                         if (files != null)
514                                 getFileList().setFiles(files);
515                 }
516                 fileList.updateFileCache(update, true /*clear selection*/);
517                 inner.selectTab(0);
518         }
519
520         /**
521          * Make the search results visible.
522          *
523          * @param query the search query string
524          */
525         public void showSearchResults(String query) {
526                 searchResults.updateFileCache(query);
527                 searchResults.updateCurrentlyShowingStats();
528                 inner.selectTab(2);
529         }
530
531         /**
532          * Display the 'loading' indicator.
533          */
534         public void showLoadingIndicator() {
535                 topPanel.getLoading().setVisible(true);
536         }
537
538         /**
539          * Hide the 'loading' indicator.
540          */
541         public void hideLoadingIndicator() {
542                 topPanel.getLoading().setVisible(false);
543         }
544
545         /**
546          * A native JavaScript method to reach out to the browser's window and
547          * invoke its resizeTo() method.
548          *
549          * @param x the new width
550          * @param y the new height
551          */
552         public static native void resizeTo(int x, int y) /*-{
553                 $wnd.resizeTo(x,y);
554         }-*/;
555
556         /**
557          * A helper method that returns true if the user's list is currently visible
558          * and false if it is hidden.
559          *
560          * @return true if the user list is visible
561          */
562         public boolean isUserListVisible() {
563                 return inner.getTabBar().getSelectedTab() == 1;
564         }
565
566         /**
567          * Display an error message.
568          *
569          * @param msg the message to display
570          */
571         public void displayError(String msg) {
572                 messagePanel.displayError(msg);
573         }
574
575         /**
576          * Display a warning message.
577          *
578          * @param msg the message to display
579          */
580         public void displayWarning(String msg) {
581                 messagePanel.displayWarning(msg);
582         }
583
584         /**
585          * Display an informational message.
586          *
587          * @param msg the message to display
588          */
589         public void displayInformation(String msg) {
590                 messagePanel.displayInformation(msg);
591         }
592
593         /**
594          * Retrieve the folders.
595          *
596          * @return the folders
597          */
598         public Folders getFolders() {
599                 return folders;
600         }
601
602         /**
603          * Retrieve the search.
604          *
605          * @return the search
606          */
607         Search getSearch() {
608                 return search;
609         }
610
611         /**
612          * Retrieve the currentSelection.
613          *
614          * @return the currentSelection
615          */
616         public Object getCurrentSelection() {
617                 return currentSelection;
618         }
619
620         /**
621          * Modify the currentSelection.
622          *
623          * @param newCurrentSelection the currentSelection to set
624          */
625         public void setCurrentSelection(Object newCurrentSelection) {
626                 currentSelection = newCurrentSelection;
627         }
628
629         /**
630          * Retrieve the groups.
631          *
632          * @return the groups
633          */
634         public Groups getGroups() {
635                 return groups;
636         }
637
638         /**
639          * Retrieve the fileList.
640          *
641          * @return the fileList
642          */
643         public FileList getFileList() {
644                 return fileList;
645         }
646
647         public SearchResults getSearchResults() {
648                 return searchResults;
649         }
650
651         /**
652          * Retrieve the topPanel.
653          *
654          * @return the topPanel
655          */
656         TopPanel getTopPanel() {
657                 return topPanel;
658         }
659
660         /**
661          * Retrieve the clipboard.
662          *
663          * @return the clipboard
664          */
665         public Clipboard getClipboard() {
666                 return clipboard;
667         }
668
669         public StatusPanel getStatusPanel() {
670                 return statusPanel;
671         }
672
673         /**
674          * Retrieve the userDetailsPanel.
675          *
676          * @return the userDetailsPanel
677          */
678         public UserDetailsPanel getUserDetailsPanel() {
679                 return userDetailsPanel;
680         }
681
682         /**
683          * Retrieve the dragController.
684          *
685          * @return the dragController
686          */
687         public PickupDragController getDragController() {
688                 return dragController;
689         }
690
691         public String getToken() {
692                 return token;
693         }
694
695         public String getWebDAVPassword() {
696                 return webDAVPassword;
697         }
698
699         public void removeGlassPanel() {
700                 glassPanel.removeFromParent();
701         }
702
703         /**
704          * Retrieve the currentUserResource.
705          *
706          * @return the currentUserResource
707          */
708         public UserResource getCurrentUserResource() {
709                 return currentUserResource;
710         }
711
712         /**
713          * Modify the currentUserResource.
714          *
715          * @param newUser the new currentUserResource
716          */
717         public void setCurrentUserResource(UserResource newUser) {
718                 currentUserResource = newUser;
719         }
720
721         public static native void preventIESelection() /*-{
722                 $doc.body.onselectstart = function () { return false; };
723         }-*/;
724
725         public static native void enableIESelection() /*-{
726                 if ($doc.body.onselectstart != null)
727                 $doc.body.onselectstart = null;
728         }-*/;
729
730         /**
731          * @return the absolute path of the API root URL
732          */
733         public String getApiPath() {
734                 Configuration conf = (Configuration) GWT.create(Configuration.class);
735                 return GWT.getModuleBaseURL() + conf.apiPath();
736         }
737
738         public void refreshWebDAVPassword() {
739                 Configuration conf = (Configuration) GWT.create(Configuration.class);
740                 String domain = Window.Location.getHostName();
741                 String path = Window.Location.getPath();
742                 String cookie = conf.webdavCookie();
743                 webDAVPassword = Cookies.getCookie(cookie);
744                 Cookies.setCookie(cookie, "", null, domain, path, false);
745         }
746
747 }