Statistics
| Branch: | Tag: | Revision:

root / src / gr / grnet / pithos / web / client / Pithos.java @ f0ff407d

History | View | Annotate | Download (52.2 kB)

1
/*
2
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or
5
 * without modification, are permitted provided that the following
6
 * conditions are met:
7
 *
8
 *   1. Redistributions of source code must retain the above
9
 *      copyright notice, this list of conditions and the following
10
 *      disclaimer.
11
 *
12
 *   2. Redistributions in binary form must reproduce the above
13
 *      copyright notice, this list of conditions and the following
14
 *      disclaimer in the documentation and/or other materials
15
 *      provided with the distribution.
16
 *
17
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
 * POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * The views and conclusions contained in the software and
31
 * documentation are those of the authors and should not be
32
 * interpreted as representing official policies, either expressed
33
 * or implied, of GRNET S.A.
34
 */
35
package gr.grnet.pithos.web.client;
36

    
37
import com.google.gwt.core.client.EntryPoint;
38
import com.google.gwt.core.client.GWT;
39
import com.google.gwt.core.client.JsArrayString;
40
import com.google.gwt.core.client.Scheduler;
41
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
42
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
43
import com.google.gwt.event.dom.client.ClickEvent;
44
import com.google.gwt.event.dom.client.ClickHandler;
45
import com.google.gwt.event.logical.shared.ResizeEvent;
46
import com.google.gwt.event.logical.shared.ResizeHandler;
47
import com.google.gwt.http.client.Response;
48
import com.google.gwt.http.client.URL;
49
import com.google.gwt.i18n.client.DateTimeFormat;
50
import com.google.gwt.i18n.client.Dictionary;
51
import com.google.gwt.i18n.client.TimeZone;
52
import com.google.gwt.resources.client.ClientBundle;
53
import com.google.gwt.resources.client.CssResource;
54
import com.google.gwt.resources.client.ImageResource;
55
import com.google.gwt.resources.client.ImageResource.ImageOptions;
56
import com.google.gwt.user.client.*;
57
import com.google.gwt.user.client.ui.*;
58
import com.google.gwt.view.client.SelectionChangeEvent;
59
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
60
import com.google.gwt.view.client.SingleSelectionModel;
61
import gr.grnet.pithos.web.client.catalog.UpdateUserCatalogs;
62
import gr.grnet.pithos.web.client.catalog.UserCatalogs;
63
import gr.grnet.pithos.web.client.commands.UploadFileCommand;
64
import gr.grnet.pithos.web.client.foldertree.*;
65
import gr.grnet.pithos.web.client.grouptree.Group;
66
import gr.grnet.pithos.web.client.grouptree.GroupTreeView;
67
import gr.grnet.pithos.web.client.grouptree.GroupTreeViewModel;
68
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView;
69
import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeViewModel;
70
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeView;
71
import gr.grnet.pithos.web.client.othersharedtree.OtherSharedTreeViewModel;
72
import gr.grnet.pithos.web.client.rest.*;
73
import org.apache.http.HttpStatus;
74

    
75
import java.util.*;
76

    
77
/**
78
 * Entry point classes define <code>onModuleLoad()</code>.
79
 */
80
public class Pithos implements EntryPoint, ResizeHandler {
81

    
82
    public static final String HOME_CONTAINER = "pithos";
83

    
84
    public static final String TRASH_CONTAINER = "trash";
85

    
86
    public static final Configuration config = GWT.create(Configuration.class);
87

    
88
    public interface Style extends CssResource {
89
        String commandAnchor();
90

    
91
        String statistics();
92

    
93
        @ClassName("gwt-HTML")
94
        String html();
95

    
96
        String uploadAlert();
97

    
98
        String uploadAlertLink();
99

    
100
        String uploadAlertProgress();
101

    
102
        String uploadAlertPercent();
103

    
104
        String uploadAlertClose();
105
    }
106

    
107
    public interface Resources extends ClientBundle {
108
        @Source("Pithos.css")
109
        Style pithosCss();
110

    
111
        @Source("gr/grnet/pithos/resources/close-popup.png")
112
        ImageResource closePopup();
113
    }
114

    
115
    public static Resources resources = GWT.create(Resources.class);
116

    
117
    /**
118
     * Instantiate an application-level image bundle. This object will provide
119
     * programmatic access to all the images needed by widgets.
120
     */
121
    static Images images = (Images) GWT.create(Images.class);
122

    
123
    public String getUserID() {
124
        return userID;
125
    }
126

    
127
    public UserCatalogs getUserCatalogs() {
128
        return userCatalogs;
129
    }
130

    
131
    public String getCurrentUserDisplayNameOrID() {
132
        final String displayName = userCatalogs.getDisplayName(getUserID());
133
        return displayName == null ? getUserID() : displayName;
134
    }
135

    
136
    public boolean hasUserDisplayNameForID(String userID) {
137
        return userCatalogs.getDisplayName(userID) != null;
138
    }
139

    
140
    public String getUserDisplayNameForID(String userID) {
141
        return userCatalogs.getDisplayName(userID);
142
    }
143

    
144
    public String getUserIDForDisplayName(String displayName) {
145
        return userCatalogs.getUserID(displayName);
146
    }
147

    
148
    public List<String> getUserDisplayNamesForIDs(List<String> userIDs) {
149
        if(userIDs == null) {
150
            userIDs = new ArrayList<String>();
151
        }
152
        final List<String> userDisplayNames = new ArrayList<String>();
153
        for(String userID : userIDs) {
154
            final String displayName = getUserDisplayNameForID(userID);
155
            userDisplayNames.add(displayName);
156
        }
157

    
158
        return userDisplayNames;
159
    }
160

    
161
    public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
162
        if(userIDs == null) {
163
            userIDs = new ArrayList<String>();
164
        }
165
        final List<String> filtered = new ArrayList<String>();
166
        for(String userID : userIDs) {
167
            if(!this.userCatalogs.hasID(userID)) {
168
                filtered.add(userID);
169
            }
170
        }
171
        return filtered;
172
    }
173

    
174
    public void setAccount(AccountResource acct) {
175
        account = acct;
176
    }
177

    
178
    public AccountResource getAccount() {
179
        return account;
180
    }
181

    
182
    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
183
        folderTreeView.updateFolder(f, showfiles, callback, openParent);
184
    }
185

    
186
    public void updateGroupNode(Group group) {
187
        groupTreeView.updateGroupNode(group);
188
    }
189

    
190
    public void updateMySharedRoot() {
191
        mysharedTreeView.updateRoot();
192
    }
193

    
194
    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
195
        mysharedTreeView.updateFolder(f, showfiles, callback);
196
    }
197

    
198
    public void updateSharedFolder(Folder f, boolean showfiles) {
199
        updateSharedFolder(f, showfiles, null);
200
    }
201

    
202
    public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
203
        otherSharedTreeView.updateFolder(f, showfiles, callback);
204
    }
205

    
206
    public MysharedTreeView getMySharedTreeView() {
207
        return mysharedTreeView;
208
    }
209

    
210
    /**
211
     * An aggregate image bundle that pulls together all the images for this
212
     * application into a single bundle.
213
     */
214
    public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
215

    
216
        @Source("gr/grnet/pithos/resources/document.png")
217
        ImageResource folders();
218

    
219
        @Source("gr/grnet/pithos/resources/advancedsettings.png")
220
        @ImageOptions(width = 32, height = 32)
221
        ImageResource tools();
222
    }
223

    
224
    private Throwable error;
225

    
226
    /**
227
     * The Application Clipboard implementation;
228
     */
229
    private Clipboard clipboard = new Clipboard();
230

    
231
    /**
232
     * The top panel that contains the menu bar.
233
     */
234
    private TopPanel topPanel;
235

    
236
    /**
237
     * The panel that contains the various system messages.
238
     */
239
    private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
240

    
241
    /**
242
     * The bottom panel that contains the status bar.
243
     */
244
    StatusPanel statusPanel = null;
245

    
246
    /**
247
     * The file list widget.
248
     */
249
    private FileList fileList;
250

    
251
    /**
252
     * The tab panel that occupies the right side of the screen.
253
     */
254
    private VerticalPanel inner = new VerticalPanel();
255

    
256

    
257
    /**
258
     * The split panel that will contain the left and right panels.
259
     */
260
    private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
261

    
262
    /**
263
     * The currently selected item in the application, for use by the Edit menu
264
     * commands. Potential types are Folder, File, User and Group.
265
     */
266
    private Object currentSelection;
267

    
268
    public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
269

    
270
    /**
271
     * The ID that uniquely identifies the user in Pithos+.
272
     * Currently this is a UUID. It used to be the user's email.
273
     */
274
    private String userID = null;
275

    
276
    /**
277
     * Hold mappings from user UUIDs to emails and vice-versa.
278
     */
279
    private UserCatalogs userCatalogs = new UserCatalogs();
280

    
281
    /**
282
     * The authentication token of the current user.
283
     */
284
    private String userToken;
285

    
286
    VerticalPanel trees;
287

    
288
    SingleSelectionModel<Folder> folderTreeSelectionModel;
289
    FolderTreeViewModel folderTreeViewModel;
290
    FolderTreeView folderTreeView;
291

    
292
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
293
    MysharedTreeViewModel mysharedTreeViewModel;
294
    MysharedTreeView mysharedTreeView = null;
295

    
296
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
297
    OtherSharedTreeViewModel otherSharedTreeViewModel;
298
    OtherSharedTreeView otherSharedTreeView = null;
299

    
300
    GroupTreeViewModel groupTreeViewModel;
301
    GroupTreeView groupTreeView;
302

    
303
    TreeView selectedTree;
304
    protected AccountResource account;
305

    
306
    Folder trash;
307

    
308
    List<Composite> treeViews = new ArrayList<Composite>();
309

    
310
    @SuppressWarnings("rawtypes")
311
    List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
312

    
313
    public Button upload;
314

    
315
    private HTML numOfFiles;
316

    
317
    private Toolbar toolbar;
318

    
319
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
320

    
321
    UploadAlert uploadAlert;
322

    
323
    Date lastModified;
324

    
325
    @Override
326
    public void onModuleLoad() {
327
        if(parseUserCredentials()) {
328
            initialize();
329
        }
330
    }
331

    
332
    static native void __ConsoleLog(String message) /*-{
333
      try {
334
        console.log(message);
335
      } catch (e) {
336
      }
337
    }-*/;
338

    
339
    public static void LOG(String ...args) {
340
        final StringBuilder sb = new StringBuilder();
341
        for(String arg : args) {
342
            sb.append(arg);
343
        }
344
        if(sb.length() > 0) {
345
            __ConsoleLog(sb.toString());
346
        }
347
    }
348

    
349
    private void initialize() {
350
        lastModified = new Date(); //Initialize if-modified-since value with now.
351
        resources.pithosCss().ensureInjected();
352
        boolean bareContent = Window.Location.getParameter("noframe") != null;
353
        String contentWidth = bareContent ? "100%" : "75%";
354

    
355
        VerticalPanel outer = new VerticalPanel();
356
        outer.setWidth("100%");
357
        if(!bareContent) {
358
            outer.addStyleName("pithos-outer");
359
        }
360

    
361
        if(!bareContent) {
362
            topPanel = new TopPanel(this, Pithos.images);
363
            topPanel.setWidth("100%");
364
            outer.add(topPanel);
365
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
366
        }
367

    
368
        messagePanel.setVisible(false);
369
        outer.add(messagePanel);
370
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
371
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
372

    
373
        HorizontalPanel header = new HorizontalPanel();
374
        header.addStyleName("pithos-header");
375
        header.setWidth(contentWidth);
376
        if(bareContent) {
377
            header.addStyleName("pithos-header-noframe");
378
        }
379
        upload = new Button("Upload", new ClickHandler() {
380
            @Override
381
            public void onClick(ClickEvent event) {
382
                if(getSelection() != null) {
383
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
384
                }
385
            }
386
        });
387
        upload.addStyleName("pithos-uploadButton");
388
        header.add(upload);
389
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
390
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
391

    
392
        toolbar = new Toolbar(this);
393
        header.add(toolbar);
394
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
395
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
396

    
397
        HorizontalPanel folderStatistics = new HorizontalPanel();
398
        folderStatistics.addStyleName("pithos-folderStatistics");
399
        numOfFiles = new HTML();
400
        folderStatistics.add(numOfFiles);
401
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
402
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
403
        folderStatistics.add(numOfFilesLabel);
404
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
405
        header.add(folderStatistics);
406
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
407
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
408
        header.setCellWidth(folderStatistics, "40px");
409
        outer.add(header);
410
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
411
        // Inner contains the various lists
412
        inner.sinkEvents(Event.ONCONTEXTMENU);
413
        inner.setWidth("100%");
414

    
415
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
416
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
417
            @Override
418
            public void onSelectionChange(SelectionChangeEvent event) {
419
                if(folderTreeSelectionModel.getSelectedObject() != null) {
420
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
421
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
422
                    Folder f = folderTreeSelectionModel.getSelectedObject();
423
                    updateFolder(f, true, new Command() {
424

    
425
                        @Override
426
                        public void execute() {
427
                            updateStatistics();
428
                        }
429
                    }, true);
430
                    showRelevantToolbarButtons();
431
                }
432
                else {
433
                    if(getSelectedTree().equals(folderTreeView)) {
434
                        setSelectedTree(null);
435
                    }
436
                    if(getSelectedTree() == null) {
437
                        showRelevantToolbarButtons();
438
                    }
439
                }
440
            }
441
        });
442
        selectionModels.add(folderTreeSelectionModel);
443

    
444
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
445
        folderTreeView = new FolderTreeView(folderTreeViewModel);
446
        treeViews.add(folderTreeView);
447

    
448
        fileList = new FileList(this, images);
449
        inner.add(fileList);
450

    
451
        trees = new VerticalPanel();
452
        trees.setWidth("100%");
453

    
454
        // Add the left and right panels to the split panel.
455
        splitPanel.setLeftWidget(trees);
456
        FlowPanel right = new FlowPanel();
457
        right.getElement().setId("rightPanel");
458
        right.add(inner);
459
        splitPanel.setRightWidget(right);
460
        splitPanel.setSplitPosition("219px");
461
        splitPanel.setSize("100%", "100%");
462
        splitPanel.addStyleName("pithos-splitPanel");
463
        splitPanel.setWidth(contentWidth);
464
        outer.add(splitPanel);
465
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
466

    
467
        if(!bareContent) {
468
            statusPanel = new StatusPanel();
469
            statusPanel.setWidth("100%");
470
            outer.add(statusPanel);
471
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
472
        }
473
        else {
474
            splitPanel.addStyleName("pithos-splitPanel-noframe");
475
        }
476

    
477
        // Hook the window resize event, so that we can adjust the UI.
478
        Window.addResizeHandler(this);
479
        // Clear out the window's built-in margin, because we want to take
480
        // advantage of the entire client area.
481
        Window.setMargin("0px");
482
        // Finally, add the outer panel to the RootPanel, so that it will be
483
        // displayed.
484
        RootPanel.get().add(outer);
485
        // Call the window resized handler to get the initial sizes setup. Doing
486
        // this in a deferred command causes it to occur after all widgets'
487
        // sizes have been computed by the browser.
488
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
489

    
490
            @Override
491
            public boolean execute() {
492
                if(!isCloudbarReady()) {
493
                    return true;
494
                }
495
                onWindowResized(Window.getClientHeight());
496
                return false;
497
            }
498
        });
499

    
500
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
501
            @Override
502
            public void execute() {
503
                fetchAccount(new Command() {
504

    
505
                    @Override
506
                    public void execute() {
507
                        if(!account.hasHomeContainer()) {
508
                            createHomeContainer(account, this);
509
                        }
510
                        else if(!account.hasTrashContainer()) {
511
                            createTrashContainer(this);
512
                        }
513
                        else {
514
                            for(Folder f : account.getContainers()) {
515
                                if(f.getName().equals(Pithos.TRASH_CONTAINER)) {
516
                                    trash = f;
517
                                    break;
518
                                }
519
                            }
520
                            trees.add(folderTreeView);
521
                            folderTreeViewModel.initialize(account, new Command() {
522

    
523
                                @Override
524
                                public void execute() {
525
                                    createMySharedTree();
526
                                }
527
                            });
528

    
529
                            HorizontalPanel separator = new HorizontalPanel();
530
                            separator.addStyleName("pithos-statisticsSeparator");
531
                            separator.add(new HTML(""));
532
                            trees.add(separator);
533

    
534
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
535
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
536
                            treeViews.add(groupTreeView);
537
                            trees.add(groupTreeView);
538
                            folderTreeView.showStatistics(account);
539
                        }
540
                    }
541
                });
542
            }
543
        });
544
    }
545

    
546
    public void scheduleResfresh() {
547
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
548

    
549
            @Override
550
            public boolean execute() {
551
                final Folder f = getSelection();
552
                if(f == null) {
553
                    return true;
554
                }
555

    
556
                HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getApiPath(), f.getOwnerID(), "/" + f.getContainer()) {
557

    
558
                    @Override
559
                    public void onSuccess(Folder _result) {
560
                        lastModified = new Date();
561
                        if(getSelectedTree().equals(folderTreeView)) {
562
                            updateFolder(f, true, new Command() {
563

    
564
                                @Override
565
                                public void execute() {
566
                                    scheduleResfresh();
567
                                }
568

    
569
                            }, false);
570
                        }
571
                        else if(getSelectedTree().equals(mysharedTreeView)) {
572
                            updateSharedFolder(f, true, new Command() {
573

    
574
                                @Override
575
                                public void execute() {
576
                                    scheduleResfresh();
577
                                }
578
                            });
579
                        }
580
                        else {
581
                            scheduleResfresh();
582
                        }
583
                    }
584

    
585
                    @Override
586
                    public void onError(Throwable t) {
587
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
588
                            scheduleResfresh();
589
                        }
590
                        else if(retries >= MAX_RETRIES) {
591
                            GWT.log("Error heading folder", t);
592
                            setError(t);
593
                            if(t instanceof RestException) {
594
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
595
                            }
596
                            else {
597
                                displayError("System error heading folder: " + t.getMessage());
598
                            }
599
                        }
600
                        else {//retry
601
                            GWT.log("Retry " + retries);
602
                            Scheduler.get().scheduleDeferred(this);
603
                        }
604
                    }
605

    
606
                    @Override
607
                    protected void onUnauthorized(Response response) {
608
                        if(retries >= MAX_RETRIES) {
609
                            sessionExpired();
610
                        }
611
                        else //retry
612
                        {
613
                            Scheduler.get().scheduleDeferred(this);
614
                        }
615
                    }
616
                };
617
                head.setHeader("X-Auth-Token", getUserToken());
618
                head.setHeader("If-Modified-Since", DateTimeFormat.getFormat("EEE, dd MMM yyyy HH:mm:ss").format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
619
                Scheduler.get().scheduleDeferred(head);
620

    
621
                return false;
622
            }
623
        }, 3000);
624
    }
625

    
626
    public void applyPermissions(Folder f) {
627
        if(f != null) {
628
            if(f.isInTrash()) {
629
                upload.setEnabled(false);
630
                disableUploadArea();
631
            }
632
            else {
633
                Boolean[] perms = f.getPermissions().get(userID);
634
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
635
                    upload.setEnabled(true);
636
                    enableUploadArea();
637
                }
638
                else {
639
                    upload.setEnabled(false);
640
                    disableUploadArea();
641
                }
642
            }
643
        }
644
        else {
645
            upload.setEnabled(false);
646
            disableUploadArea();
647
        }
648
    }
649

    
650
    @SuppressWarnings({"rawtypes", "unchecked"})
651
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
652
        selectedTree = _selectedTree;
653

    
654
        for(SingleSelectionModel s : selectionModels) {
655
            if(!s.equals(model) && s.getSelectedObject() != null) {
656
                s.setSelected(s.getSelectedObject(), false);
657
            }
658
        }
659
    }
660

    
661
    public void showFiles(final Folder f) {
662
        Set<File> files = f.getFiles();
663
        showFiles(files);
664
    }
665

    
666
    public void showFiles(Set<File> files) {
667
        fileList.setFiles(new ArrayList<File>(files));
668
    }
669

    
670
    /**
671
     * Parse and store the user credentials to the appropriate fields.
672
     */
673
    private boolean parseUserCredentials() {
674
        Configuration conf = (Configuration) GWT.create(Configuration.class);
675
        Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
676
        String cookie = otherProperties.get("authCookie");
677
        String auth = Cookies.getCookie(cookie);
678
        if(auth == null) {
679
            authenticateUser();
680
            return false;
681
        }
682
        if(auth.startsWith("\"")) {
683
            auth = auth.substring(1);
684
        }
685
        if(auth.endsWith("\"")) {
686
            auth = auth.substring(0, auth.length() - 1);
687
        }
688
        String[] authSplit = auth.split("\\" + conf.cookieSeparator(), 2);
689
        if(authSplit.length != 2) {
690
            authenticateUser();
691
            return false;
692
        }
693
        userID = authSplit[0];
694
        userToken = authSplit[1];
695

    
696
        String gotoUrl = Window.Location.getParameter("goto");
697
        if(gotoUrl != null && gotoUrl.length() > 0) {
698
            Window.Location.assign(gotoUrl);
699
            return false;
700
        }
701
        return true;
702
    }
703

    
704
    /**
705
     * Redirect the user to the login page for authentication.
706
     */
707
    protected void authenticateUser() {
708
        Dictionary otherProperties = Dictionary.getDictionary("otherProperties");
709
        Window.Location.assign(otherProperties.get("loginUrl") + Window.Location.getHref());
710
    }
711

    
712
    public void fetchAccount(final Command callback) {
713
        String path = "?format=json";
714

    
715
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getApiPath(), userID, path) {
716
            @Override
717
            public void onSuccess(AccountResource _result) {
718
                account = _result;
719
                if(callback != null) {
720
                    callback.execute();
721
                }
722
                // Initialize the user catalog
723
                new UpdateUserCatalogs(Pithos.this, Pithos.this.getUserID()).scheduleDeferred();
724
            }
725

    
726
            @Override
727
            public void onError(Throwable t) {
728
                GWT.log("Error getting account", t);
729
                setError(t);
730
                if(t instanceof RestException) {
731
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
732
                }
733
                else {
734
                    displayError("System error fetching user data: " + t.getMessage());
735
                }
736
            }
737

    
738
            @Override
739
            protected void onUnauthorized(Response response) {
740
                sessionExpired();
741
            }
742
        };
743
        getAccount.setHeader("X-Auth-Token", userToken);
744
        Scheduler.get().scheduleDeferred(getAccount);
745
    }
746

    
747
    public void updateStatistics() {
748
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getApiPath(), userID, "", account) {
749

    
750
            @Override
751
            public void onSuccess(AccountResource _result) {
752
                folderTreeView.showStatistics(account);
753
            }
754

    
755
            @Override
756
            public void onError(Throwable t) {
757
                GWT.log("Error getting account", t);
758
                setError(t);
759
                if(t instanceof RestException) {
760
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
761
                }
762
                else {
763
                    displayError("System error fetching user data: " + t.getMessage());
764
                }
765
            }
766

    
767
            @Override
768
            protected void onUnauthorized(Response response) {
769
                sessionExpired();
770
            }
771
        };
772
        headAccount.setHeader("X-Auth-Token", userToken);
773
        Scheduler.get().scheduleDeferred(headAccount);
774
    }
775

    
776
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
777
        String path = "/" + Pithos.HOME_CONTAINER;
778
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
779
            @Override
780
            public void onSuccess(Resource result) {
781
                if(!_account.hasTrashContainer()) {
782
                    createTrashContainer(callback);
783
                }
784
                else {
785
                    fetchAccount(callback);
786
                }
787
            }
788

    
789
            @Override
790
            public void onError(Throwable t) {
791
                GWT.log("Error creating pithos", t);
792
                setError(t);
793
                if(t instanceof RestException) {
794
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
795
                }
796
                else {
797
                    displayError("System error Error creating pithos: " + t.getMessage());
798
                }
799
            }
800

    
801
            @Override
802
            protected void onUnauthorized(Response response) {
803
                sessionExpired();
804
            }
805
        };
806
        createPithos.setHeader("X-Auth-Token", getUserToken());
807
        Scheduler.get().scheduleDeferred(createPithos);
808
    }
809

    
810
    protected void createTrashContainer(final Command callback) {
811
        String path = "/" + Pithos.TRASH_CONTAINER;
812
        PutRequest createPithos = new PutRequest(getApiPath(), getUserID(), path) {
813
            @Override
814
            public void onSuccess(Resource result) {
815
                fetchAccount(callback);
816
            }
817

    
818
            @Override
819
            public void onError(Throwable t) {
820
                GWT.log("Error creating pithos", t);
821
                setError(t);
822
                if(t instanceof RestException) {
823
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
824
                }
825
                else {
826
                    displayError("System error Error creating pithos: " + t.getMessage());
827
                }
828
            }
829

    
830
            @Override
831
            protected void onUnauthorized(Response response) {
832
                sessionExpired();
833
            }
834
        };
835
        createPithos.setHeader("X-Auth-Token", getUserToken());
836
        Scheduler.get().scheduleDeferred(createPithos);
837
    }
838

    
839
    /**
840
     * Creates an HTML fragment that places an image & caption together, for use
841
     * in a group header.
842
     *
843
     * @param imageProto an image prototype for an image
844
     * @param caption    the group caption
845
     * @return the header HTML fragment
846
     */
847
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
848
        String captionHTML = "<table class='caption' cellpadding='0' "
849
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
850
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
851
            + caption + "</b></td></tr></table>";
852
        return captionHTML;
853
    }
854

    
855
    protected void onWindowResized(int height) {
856
        // Adjust the split panel to take up the available room in the window.
857
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
858
        if(newHeight < 1) {
859
            newHeight = 1;
860
        }
861
        splitPanel.setHeight("" + newHeight);
862
        inner.setHeight("" + newHeight);
863
    }
864

    
865
    native boolean isCloudbarReady()/*-{
866
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
867
        return true;
868
      return false;
869
    }-*/;
870

    
871
    @Override
872
    public void onResize(ResizeEvent event) {
873
        int height = event.getHeight();
874
        onWindowResized(height);
875
    }
876

    
877
    /**
878
     * Display an error message.
879
     *
880
     * @param msg the message to display
881
     */
882
    public void displayError(String msg) {
883
        messagePanel.displayError(msg);
884
        onWindowResized(Window.getClientHeight());
885
    }
886

    
887
    /**
888
     * Display a warning message.
889
     *
890
     * @param msg the message to display
891
     */
892
    public void displayWarning(String msg) {
893
        messagePanel.displayWarning(msg);
894
        onWindowResized(Window.getClientHeight());
895
    }
896

    
897
    /**
898
     * Display an informational message.
899
     *
900
     * @param msg the message to display
901
     */
902
    public void displayInformation(String msg) {
903
        messagePanel.displayInformation(msg);
904
        onWindowResized(Window.getClientHeight());
905
    }
906

    
907
    /**
908
     * Retrieve the fileList.
909
     *
910
     * @return the fileList
911
     */
912
    public FileList getFileList() {
913
        return fileList;
914
    }
915

    
916
    /**
917
     * Retrieve the topPanel.
918
     *
919
     * @return the topPanel
920
     */
921
    TopPanel getTopPanel() {
922
        return topPanel;
923
    }
924

    
925
    /**
926
     * Retrieve the clipboard.
927
     *
928
     * @return the clipboard
929
     */
930
    public Clipboard getClipboard() {
931
        return clipboard;
932
    }
933

    
934
    public StatusPanel getStatusPanel() {
935
        return statusPanel;
936
    }
937

    
938
    public String getUserToken() {
939
        return userToken;
940
    }
941

    
942
    public static native void preventIESelection() /*-{
943
      $doc.body.onselectstart = function () {
944
        return false;
945
      };
946
    }-*/;
947

    
948
    public static native void enableIESelection() /*-{
949
      if ($doc.body.onselectstart != null)
950
        $doc.body.onselectstart = null;
951
    }-*/;
952

    
953
    /**
954
     * @return the absolute path of the API root URL
955
     */
956
    public String getApiPath() {
957
        Configuration conf = (Configuration) GWT.create(Configuration.class);
958
        return conf.apiPath();
959
    }
960

    
961
    /**
962
     * History support for folder navigation
963
     * adds a new browser history entry
964
     *
965
     * @param key
966
     */
967
    public void updateHistory(String key) {
968
//                Replace any whitespace of the initial string to "+"
969
//                String result = key.replaceAll("\\s","+");
970
//                Add a new browser history entry.
971
//                History.newItem(result);
972
        History.newItem(key);
973
    }
974

    
975
    public void deleteFolder(final Folder folder, final Command callback) {
976
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
977
        pwp.center();
978
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
979
        DeleteRequest deleteFolder = new DeleteRequest(getApiPath(), folder.getOwnerID(), path) {
980

    
981
            @Override
982
            protected void onUnauthorized(Response response) {
983
                pwp.hide();
984
                sessionExpired();
985
            }
986

    
987
            @Override
988
            public void onSuccess(Resource result) {
989
                updateFolder(folder.getParent(), true, new Command() {
990

    
991
                    @Override
992
                    public void execute() {
993
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
994
                        updateStatistics();
995
                        if(callback != null) {
996
                            callback.execute();
997
                        }
998
                        pwp.hide();
999
                    }
1000
                }, true);
1001
            }
1002

    
1003
            @Override
1004
            public void onError(Throwable t) {
1005
                GWT.log("", t);
1006
                setError(t);
1007
                if(t instanceof RestException) {
1008
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1009
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1010
                    }
1011
                    else {
1012
                        onSuccess(null);
1013
                    }
1014
                }
1015
                else {
1016
                    displayError("System error unable to delete folder: " + t.getMessage());
1017
                }
1018
                pwp.hide();
1019
            }
1020
        };
1021
        deleteFolder.setHeader("X-Auth-Token", getUserToken());
1022
        Scheduler.get().scheduleDeferred(deleteFolder);
1023
    }
1024

    
1025
    public FolderTreeView getFolderTreeView() {
1026
        return folderTreeView;
1027
    }
1028

    
1029
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1030
        if(iter.hasNext()) {
1031
            File file = iter.next();
1032
            String path = targetUri + "/" + file.getName();
1033
            PutRequest copyFile = new PutRequest(getApiPath(), targetUsername, path) {
1034
                @Override
1035
                public void onSuccess(Resource result) {
1036
                    copyFiles(iter, targetUsername, targetUri, callback);
1037
                }
1038

    
1039
                @Override
1040
                public void onError(Throwable t) {
1041
                    GWT.log("", t);
1042
                    setError(t);
1043
                    if(t instanceof RestException) {
1044
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1045
                    }
1046
                    else {
1047
                        displayError("System error unable to copy file: " + t.getMessage());
1048
                    }
1049
                }
1050

    
1051
                @Override
1052
                protected void onUnauthorized(Response response) {
1053
                    sessionExpired();
1054
                }
1055
            };
1056
            copyFile.setHeader("X-Auth-Token", getUserToken());
1057
            copyFile.setHeader("X-Copy-From", URL.encodePathSegment(file.getUri()));
1058
            if(!file.getOwnerID().equals(targetUsername)) {
1059
                copyFile.setHeader("X-Source-Account", URL.encodePathSegment(file.getOwnerID()));
1060
            }
1061
            copyFile.setHeader("Content-Type", file.getContentType());
1062
            Scheduler.get().scheduleDeferred(copyFile);
1063
        }
1064
        else if(callback != null) {
1065
            callback.execute();
1066
        }
1067
    }
1068

    
1069
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1070
        String path = targetUri + "?delimiter=/";
1071
        PutRequest copyFolder = new PutRequest(getApiPath(), targetUsername, path) {
1072
            @Override
1073
            public void onSuccess(Resource result) {
1074
                if(callback != null) {
1075
                    callback.execute();
1076
                }
1077
            }
1078

    
1079
            @Override
1080
            public void onError(Throwable t) {
1081
                GWT.log("", t);
1082
                setError(t);
1083
                if(t instanceof RestException) {
1084
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1085
                }
1086
                else {
1087
                    displayError("System error copying folder: " + t.getMessage());
1088
                }
1089
            }
1090

    
1091
            @Override
1092
            protected void onUnauthorized(Response response) {
1093
                sessionExpired();
1094
            }
1095
        };
1096
        copyFolder.setHeader("X-Auth-Token", getUserToken());
1097
        copyFolder.setHeader("Accept", "*/*");
1098
        copyFolder.setHeader("Content-Length", "0");
1099
        copyFolder.setHeader("Content-Type", "application/directory");
1100
        if(!f.getOwnerID().equals(targetUsername)) {
1101
            copyFolder.setHeader("X-Source-Account", f.getOwnerID());
1102
        }
1103
        if(move) {
1104
            copyFolder.setHeader("X-Move-From", URL.encodePathSegment(f.getUri()));
1105
        }
1106
        else {
1107
            copyFolder.setHeader("X-Copy-From", URL.encodePathSegment(f.getUri()));
1108
        }
1109
        Scheduler.get().scheduleDeferred(copyFolder);
1110
    }
1111

    
1112
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1113
        selectionModels.add(model);
1114
    }
1115

    
1116
    public OtherSharedTreeView getOtherSharedTreeView() {
1117
        return otherSharedTreeView;
1118
    }
1119

    
1120
    public void updateTrash(boolean showFiles, Command callback) {
1121
        updateFolder(trash, showFiles, callback, true);
1122
    }
1123

    
1124
    public void updateGroupsNode() {
1125
        groupTreeView.updateGroupNode(null);
1126
    }
1127

    
1128
    public Group addGroup(String groupname) {
1129
        Group newGroup = new Group(groupname);
1130
        account.addGroup(newGroup);
1131
        groupTreeView.updateGroupNode(null);
1132
        return newGroup;
1133
    }
1134

    
1135
    public void removeGroup(Group group) {
1136
        account.removeGroup(group);
1137
        updateGroupsNode();
1138
    }
1139

    
1140
    public TreeView getSelectedTree() {
1141
        return selectedTree;
1142
    }
1143

    
1144
    public void setSelectedTree(TreeView selected) {
1145
        selectedTree = selected;
1146
    }
1147

    
1148
    public Folder getSelection() {
1149
        if(selectedTree != null) {
1150
            return selectedTree.getSelection();
1151
        }
1152
        return null;
1153
    }
1154

    
1155
    public void showFolderStatistics(int folderFileCount) {
1156
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1157
    }
1158

    
1159
    public GroupTreeView getGroupTreeView() {
1160
        return groupTreeView;
1161
    }
1162

    
1163
    public void sessionExpired() {
1164
        new SessionExpiredDialog(this).center();
1165
    }
1166

    
1167
    public void updateRootFolder(Command callback) {
1168
        updateFolder(account.getPithos(), false, callback, true);
1169
    }
1170

    
1171
    void createMySharedTree() {
1172
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1173
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1174
            @Override
1175
            public void onSelectionChange(SelectionChangeEvent event) {
1176
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1177
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1178
                    upload.setEnabled(false);
1179
                    disableUploadArea();
1180
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1181
                    showRelevantToolbarButtons();
1182
                }
1183
                else {
1184
                    if(getSelectedTree().equals(mysharedTreeView)) {
1185
                        setSelectedTree(null);
1186
                    }
1187
                    if(getSelectedTree() == null) {
1188
                        showRelevantToolbarButtons();
1189
                    }
1190
                }
1191
            }
1192
        });
1193
        selectionModels.add(mysharedTreeSelectionModel);
1194
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1195
        mysharedTreeViewModel.initialize(new Command() {
1196

    
1197
            @Override
1198
            public void execute() {
1199
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1200
                trees.insert(mysharedTreeView, 2);
1201
                treeViews.add(mysharedTreeView);
1202
                createOtherSharedTree();
1203
            }
1204
        });
1205
    }
1206

    
1207
    void createOtherSharedTree() {
1208
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1209
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1210
            @Override
1211
            public void onSelectionChange(SelectionChangeEvent event) {
1212
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1213
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1214
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1215
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1216
                    showRelevantToolbarButtons();
1217
                }
1218
                else {
1219
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1220
                        setSelectedTree(null);
1221
                    }
1222
                    if(getSelectedTree() == null) {
1223
                        showRelevantToolbarButtons();
1224
                    }
1225
                }
1226
            }
1227
        });
1228
        selectionModels.add(otherSharedTreeSelectionModel);
1229
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1230
        otherSharedTreeViewModel.initialize(new Command() {
1231

    
1232
            @Override
1233
            public void execute() {
1234
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel);
1235
                trees.insert(otherSharedTreeView, 1);
1236
                treeViews.add(otherSharedTreeView);
1237
                scheduleResfresh();
1238
            }
1239
        });
1240
    }
1241

    
1242
    public native void log1(String message)/*-{
1243
      $wnd.console.log(message);
1244
    }-*/;
1245

    
1246
    public String getErrorData() {
1247
        if(error != null) {
1248
            return error.toString();
1249
        }
1250
        return "";
1251
    }
1252

    
1253
    public void setError(Throwable t) {
1254
        error = t;
1255
    }
1256

    
1257
    public void showRelevantToolbarButtons() {
1258
        toolbar.showRelevantButtons();
1259
    }
1260

    
1261
    public FileUploadDialog getFileUploadDialog() {
1262
        if(fileUploadDialog == null) {
1263
            fileUploadDialog = new FileUploadDialog(this);
1264
        }
1265
        return fileUploadDialog;
1266
    }
1267

    
1268
    public void hideUploadIndicator() {
1269
        upload.removeStyleName("pithos-uploadButton-loading");
1270
        upload.setTitle("");
1271
    }
1272

    
1273
    public void showUploadIndicator() {
1274
        upload.addStyleName("pithos-uploadButton-loading");
1275
        upload.setTitle("Upload in progress. Click for details.");
1276
    }
1277

    
1278
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1279
        if(folder == null) {
1280
            if(callback != null) {
1281
                callback.execute();
1282
            }
1283
        }
1284
        else {
1285
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getApiPath(), folder.getOwnerID(), folder.getUri(), folder) {
1286

    
1287
                @Override
1288
                public void onSuccess(Folder _result) {
1289
                    if(callback != null) {
1290
                        callback.execute();
1291
                    }
1292
                }
1293

    
1294
                @Override
1295
                public void onError(Throwable t) {
1296
                    if(t instanceof RestException) {
1297
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1298
                            final String path = folder.getUri();
1299
                            PutRequest newFolder = new PutRequest(getApiPath(), folder.getOwnerID(), path) {
1300
                                @Override
1301
                                public void onSuccess(Resource _result) {
1302
                                    scheduleFolderHeadCommand(folder, callback);
1303
                                }
1304

    
1305
                                @Override
1306
                                public void onError(Throwable _t) {
1307
                                    GWT.log("", _t);
1308
                                    setError(_t);
1309
                                    if(_t instanceof RestException) {
1310
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1311
                                    }
1312
                                    else {
1313
                                        displayError("System error creating folder: " + _t.getMessage());
1314
                                    }
1315
                                }
1316

    
1317
                                @Override
1318
                                protected void onUnauthorized(Response response) {
1319
                                    sessionExpired();
1320
                                }
1321
                            };
1322
                            newFolder.setHeader("X-Auth-Token", getUserToken());
1323
                            newFolder.setHeader("Content-Type", "application/folder");
1324
                            newFolder.setHeader("Accept", "*/*");
1325
                            newFolder.setHeader("Content-Length", "0");
1326
                            Scheduler.get().scheduleDeferred(newFolder);
1327
                        }
1328
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1329
                            onSuccess(folder);
1330
                        }
1331
                        else {
1332
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1333
                        }
1334
                    }
1335
                    else {
1336
                        displayError("System error heading folder: " + t.getMessage());
1337
                    }
1338

    
1339
                    GWT.log("Error heading folder", t);
1340
                    setError(t);
1341
                }
1342

    
1343
                @Override
1344
                protected void onUnauthorized(Response response) {
1345
                    sessionExpired();
1346
                }
1347
            };
1348
            headFolder.setHeader("X-Auth-Token", getUserToken());
1349
            Scheduler.get().scheduleDeferred(headFolder);
1350
        }
1351
    }
1352

    
1353
    public void scheduleFileHeadCommand(File f, final Command callback) {
1354
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getApiPath(), f.getOwnerID(), f.getUri(), f) {
1355

    
1356
            @Override
1357
            public void onSuccess(File _result) {
1358
                if(callback != null) {
1359
                    callback.execute();
1360
                }
1361
            }
1362

    
1363
            @Override
1364
            public void onError(Throwable t) {
1365
                GWT.log("Error heading file", t);
1366
                setError(t);
1367
                if(t instanceof RestException) {
1368
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1369
                }
1370
                else {
1371
                    displayError("System error heading file: " + t.getMessage());
1372
                }
1373
            }
1374

    
1375
            @Override
1376
            protected void onUnauthorized(Response response) {
1377
                sessionExpired();
1378
            }
1379
        };
1380
        headFile.setHeader("X-Auth-Token", getUserToken());
1381
        Scheduler.get().scheduleDeferred(headFile);
1382
    }
1383

    
1384
    public boolean isMySharedSelected() {
1385
        return getSelectedTree().equals(getMySharedTreeView());
1386
    }
1387

    
1388
    private Folder getUploadFolder() {
1389
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1390
            return getSelection();
1391
        }
1392
        return null;
1393
    }
1394

    
1395
    private void updateUploadFolder() {
1396
        updateUploadFolder(null);
1397
    }
1398

    
1399
    private void updateUploadFolder(final JsArrayString urls) {
1400
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1401
            Folder f = getSelection();
1402
            if(getSelectedTree().equals(getFolderTreeView())) {
1403
                updateFolder(f, true, new Command() {
1404

    
1405
                    @Override
1406
                    public void execute() {
1407
                        updateStatistics();
1408
                        if(urls != null) {
1409
                            selectUploadedFiles(urls);
1410
                        }
1411
                    }
1412
                }, false);
1413
            }
1414
            else {
1415
                updateOtherSharedFolder(f, true, null);
1416
            }
1417
        }
1418
    }
1419

    
1420
    public native void disableUploadArea() /*-{
1421
      var uploader = $wnd.$("#uploader").pluploadQueue();
1422
      var dropElm = $wnd.document.getElementById('rightPanel');
1423
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1424
    }-*/;
1425

    
1426
    public native void enableUploadArea() /*-{
1427
      var uploader = $wnd.$("#uploader").pluploadQueue();
1428
      var dropElm = $wnd.document.getElementById('rightPanel');
1429
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1430
      if (uploader.runtime == 'html5') {
1431
        uploader.settings.drop_element = 'rightPanel';
1432
        uploader.trigger('PostInit');
1433
      }
1434
    }-*/;
1435

    
1436
    public void showUploadAlert(int nOfFiles) {
1437
        if(uploadAlert == null) {
1438
            uploadAlert = new UploadAlert(this, nOfFiles);
1439
        }
1440
        if(!uploadAlert.isShowing()) {
1441
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1442

    
1443
                @Override
1444
                public void setPosition(int offsetWidth, int offsetHeight) {
1445
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1446
                }
1447
            });
1448
        }
1449
        uploadAlert.setNumOfFiles(nOfFiles);
1450
    }
1451

    
1452
    public void hideUploadAlert() {
1453
        if(uploadAlert != null && uploadAlert.isShowing()) {
1454
            uploadAlert.hide();
1455
        }
1456
    }
1457

    
1458
    public void selectUploadedFiles(JsArrayString urls) {
1459
        List<String> selectedUrls = new ArrayList<String>();
1460
        for(int i = 0; i < urls.length(); i++) {
1461
            selectedUrls.add(urls.get(i));
1462
        }
1463
        fileList.selectByUrl(selectedUrls);
1464
    }
1465

    
1466
    public void emptyContainer(final Folder container) {
1467
        String path = "/" + container.getName() + "?delimiter=/";
1468
        DeleteRequest delete = new DeleteRequest(getApiPath(), getUserID(), path) {
1469

    
1470
            @Override
1471
            protected void onUnauthorized(Response response) {
1472
                sessionExpired();
1473
            }
1474

    
1475
            @Override
1476
            public void onSuccess(Resource result) {
1477
                updateFolder(container, true, null, true);
1478
            }
1479

    
1480
            @Override
1481
            public void onError(Throwable t) {
1482
                GWT.log("Error deleting trash", t);
1483
                setError(t);
1484
                if(t instanceof RestException) {
1485
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1486
                }
1487
                else {
1488
                    displayError("System error deleting trash: " + t.getMessage());
1489
                }
1490
            }
1491
        };
1492
        delete.setHeader("X-Auth-Token", getUserToken());
1493
        Scheduler.get().scheduleDeferred(delete);
1494
    }
1495
}