Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (59.6 kB)

1
/*
2
 * Copyright 2011-2013 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
    private static final boolean IsLOGEnabled = false;
82
    public static final boolean IsDetailedHTTPLOGEnabled = true;
83
    public static final boolean IsFullResponseBodyLOGEnabled = true;
84
    private static final boolean EnableScheduledRefresh = true; // Make false only for debugging purposes.
85

    
86
    public static final Set<String> HTTPHeadersToIgnoreInLOG = new HashSet<String>();
87
    static {
88
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_CONNECTION);
89
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_DATE);
90
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_KEEP_ALIVE);
91
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_SERVER);
92
        HTTPHeadersToIgnoreInLOG.add(Const.HTTP_HEADER_VARY);
93
        HTTPHeadersToIgnoreInLOG.add(Const.IF_MODIFIED_SINCE);
94
    }
95

    
96
    public static final Configuration config = GWT.create(Configuration.class);
97
    public static final String CONFIG_API_PATH = config.apiPath();
98
    static {
99
        LOG("CONFIG_API_PATH = ", CONFIG_API_PATH);
100
    }
101

    
102
    public static final Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
103
    public static String getFromOtherPropertiesOrDefault(String key, String def) {
104
        try {
105
            final String value = otherProperties.get(key);
106
            return value == null ? def : value;
107
        }
108
        catch(Exception e) {
109
            return def;
110
        }
111
    }
112

    
113
    public static String getFromOtherPropertiesOrNull(String key) {
114
        return getFromOtherPropertiesOrDefault(key, null);
115
    }
116

    
117
    private static final boolean SHOW_COPYRIGHT;
118
    static {
119
        final String valueStr = getFromOtherPropertiesOrDefault("SHOW_COPYRIGHT", "true").trim().toLowerCase();
120
        SHOW_COPYRIGHT = "true".equals(valueStr);
121
        LOG("SHOW_COPYRIGHT = '", valueStr, "' ==> ", SHOW_COPYRIGHT);
122
    }
123

    
124
    public static final String OTHERPROPS_STORAGE_API_URL = getFromOtherPropertiesOrNull("STORAGE_API_URL");
125
    public static final String OTHERPROPS_USER_CATALOGS_API_URL = getFromOtherPropertiesOrNull("USER_CATALOGS_API_URL");
126
    static {
127
        LOG("STORAGE_API_URL = ", OTHERPROPS_STORAGE_API_URL);
128
        LOG("USER_CATALOGS_API_URL = ", OTHERPROPS_USER_CATALOGS_API_URL);
129
    }
130

    
131
    public static final String STORAGE_API_URL;
132
    static {
133
        if(OTHERPROPS_STORAGE_API_URL != null) {
134
            STORAGE_API_URL = OTHERPROPS_STORAGE_API_URL;
135
        }
136
        else if(CONFIG_API_PATH != null) {
137
            STORAGE_API_URL = CONFIG_API_PATH;
138
        }
139
        else {
140
            throw new RuntimeException("Unknown STORAGE_API_URL");
141
        }
142

    
143
        LOG("Computed STORAGE_API_URL = ", STORAGE_API_URL);
144
    }
145

    
146
    public static final String STORAGE_VIEW_URL;
147
    static {
148
        final String viewURL = getFromOtherPropertiesOrNull("STORAGE_VIEW_URL");
149
        if(viewURL != null) {
150
            STORAGE_VIEW_URL = viewURL;
151
        }
152
        else {
153
            STORAGE_VIEW_URL = STORAGE_API_URL;
154
        }
155

    
156
        LOG("Computed STORAGE_VIEW_URL = ", STORAGE_VIEW_URL);
157
    }
158

    
159
    public static final String PUBLIC_LINK_VIEW_PREFIX = getFromOtherPropertiesOrDefault("PUBLIC_LINK_VIEW_PREFIX", "");
160

    
161
    public static final String USER_CATALOGS_API_URL;
162
    static {
163
        if(OTHERPROPS_USER_CATALOGS_API_URL != null) {
164
            USER_CATALOGS_API_URL = OTHERPROPS_USER_CATALOGS_API_URL;
165
        }
166
        else if(OTHERPROPS_STORAGE_API_URL != null) {
167
            throw new RuntimeException("STORAGE_API_URL is defined but USER_CATALOGS_API_URL is not");
168
        }
169
        else {
170
            // https://server.com/v1/ --> https://server.com
171
            String url = CONFIG_API_PATH;
172
            url = Helpers.stripTrailing(url, "/");
173
            url = Helpers.upToIncludingLastPart(url, "/");
174
            url = Helpers.stripTrailing(url, "/");
175
            url = url + "/user_catalogs";
176

    
177
            USER_CATALOGS_API_URL = url;
178

    
179
            LOG("Computed USER_CATALOGS_API_URL = ", USER_CATALOGS_API_URL);
180
        }
181
    }
182

    
183
    public interface Style extends CssResource {
184
        String commandAnchor();
185

    
186
        String statistics();
187

    
188
        @ClassName("gwt-HTML")
189
        String html();
190

    
191
        String uploadAlert();
192

    
193
        String uploadAlertLink();
194

    
195
        String uploadAlertProgress();
196

    
197
        String uploadAlertPercent();
198

    
199
        String uploadAlertClose();
200
    }
201

    
202
    public interface Resources extends ClientBundle {
203
        @Source("Pithos.css")
204
        Style pithosCss();
205

    
206
        @Source("gr/grnet/pithos/resources/close-popup.png")
207
        ImageResource closePopup();
208
    }
209

    
210
    public static Resources resources = GWT.create(Resources.class);
211

    
212
    /**
213
     * Instantiate an application-level image bundle. This object will provide
214
     * programmatic access to all the images needed by widgets.
215
     */
216
    static Images images = (Images) GWT.create(Images.class);
217

    
218
    public String getUserID() {
219
        return userID;
220
    }
221

    
222
    public UserCatalogs getUserCatalogs() {
223
        return userCatalogs;
224
    }
225

    
226
    public String getCurrentUserDisplayNameOrID() {
227
        final String displayName = userCatalogs.getDisplayName(getUserID());
228
        return displayName == null ? getUserID() : displayName;
229
    }
230

    
231
    public boolean hasDisplayNameForUserID(String userID) {
232
        return userCatalogs.getDisplayName(userID) != null;
233
    }
234

    
235
    public boolean hasIDForUserDisplayName(String userDisplayName) {
236
        return userCatalogs.getID(userDisplayName) != null;
237
    }
238

    
239
    public String getDisplayNameForUserID(String userID) {
240
        return userCatalogs.getDisplayName(userID);
241
    }
242

    
243
    public String getIDForUserDisplayName(String userDisplayName) {
244
        return userCatalogs.getID(userDisplayName);
245
    }
246

    
247
    public List<String> getDisplayNamesForUserIDs(List<String> userIDs) {
248
        if(userIDs == null) {
249
            userIDs = new ArrayList<String>();
250
        }
251
        final List<String> userDisplayNames = new ArrayList<String>();
252
        for(String userID : userIDs) {
253
            final String displayName = getDisplayNameForUserID(userID);
254
            userDisplayNames.add(displayName);
255
        }
256

    
257
        return userDisplayNames;
258
    }
259

    
260
    public List<String> filterUserIDsWithUnknownDisplayName(Collection<String> userIDs) {
261
        if(userIDs == null) {
262
            userIDs = new ArrayList<String>();
263
        }
264
        final List<String> filtered = new ArrayList<String>();
265
        for(String userID : userIDs) {
266
            if(!this.userCatalogs.hasID(userID)) {
267
                filtered.add(userID);
268
            }
269
        }
270
        return filtered;
271
    }
272

    
273
    public void setAccount(AccountResource acct) {
274
        account = acct;
275
    }
276

    
277
    public AccountResource getAccount() {
278
        return account;
279
    }
280

    
281
    public void updateFolder(Folder f, boolean showfiles, Command callback, final boolean openParent) {
282
        folderTreeView.updateFolder(f, showfiles, callback, openParent);
283
    }
284

    
285
    public void updateGroupNode(Group group) {
286
        groupTreeView.updateGroupNode(group);
287
    }
288

    
289
    public void updateMySharedRoot() {
290
        mysharedTreeView.updateRoot();
291
    }
292

    
293
    public void updateSharedFolder(Folder f, boolean showfiles, Command callback) {
294
        mysharedTreeView.updateFolder(f, showfiles, callback);
295
    }
296

    
297
    public void updateSharedFolder(Folder f, boolean showfiles) {
298
        updateSharedFolder(f, showfiles, null);
299
    }
300

    
301
    public void updateOtherSharedFolder(Folder f, boolean showfiles, Command callback) {
302
        otherSharedTreeView.updateFolder(f, showfiles, callback);
303
    }
304

    
305
    public MysharedTreeView getMySharedTreeView() {
306
        return mysharedTreeView;
307
    }
308

    
309
    /**
310
     * An aggregate image bundle that pulls together all the images for this
311
     * application into a single bundle.
312
     */
313
    public interface Images extends TopPanel.Images, FileList.Images, ToolsMenu.Images {
314

    
315
        @Source("gr/grnet/pithos/resources/document.png")
316
        ImageResource folders();
317

    
318
        @Source("gr/grnet/pithos/resources/advancedsettings.png")
319
        @ImageOptions(width = 32, height = 32)
320
        ImageResource tools();
321
    }
322

    
323
    private Throwable error;
324

    
325
    /**
326
     * The Application Clipboard implementation;
327
     */
328
    private Clipboard clipboard = new Clipboard();
329

    
330
    /**
331
     * The top panel that contains the menu bar.
332
     */
333
    private TopPanel topPanel;
334

    
335
    /**
336
     * The panel that contains the various system messages.
337
     */
338
    private MessagePanel messagePanel = new MessagePanel(this, Pithos.images);
339

    
340
    /**
341
     * The bottom panel that contains the status bar.
342
     */
343
    StatusPanel statusPanel = null;
344

    
345
    /**
346
     * The file list widget.
347
     */
348
    private FileList fileList;
349

    
350
    /**
351
     * The tab panel that occupies the right side of the screen.
352
     */
353
    private VerticalPanel inner = new VerticalPanel();
354

    
355

    
356
    /**
357
     * The split panel that will contain the left and right panels.
358
     */
359
    private HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
360

    
361
    /**
362
     * The currently selected item in the application, for use by the Edit menu
363
     * commands. Potential types are Folder, File, User and Group.
364
     */
365
    private Object currentSelection;
366

    
367
    public HashMap<String, String> userFullNameMap = new HashMap<String, String>();
368

    
369
    /**
370
     * The ID that uniquely identifies the user in Pithos+.
371
     * Currently this is a UUID. It used to be the user's email.
372
     */
373
    private String userID = null;
374

    
375
    /**
376
     * Holds mappings from user UUIDs to emails and vice-versa.
377
     */
378
    private UserCatalogs userCatalogs = new UserCatalogs();
379

    
380
    /**
381
     * The authentication token of the current user.
382
     */
383
    private String userToken;
384

    
385
    VerticalPanel trees;
386

    
387
    SingleSelectionModel<Folder> folderTreeSelectionModel;
388
    FolderTreeViewModel folderTreeViewModel;
389
    FolderTreeView folderTreeView;
390

    
391
    SingleSelectionModel<Folder> mysharedTreeSelectionModel;
392
    MysharedTreeViewModel mysharedTreeViewModel;
393
    MysharedTreeView mysharedTreeView = null;
394

    
395
    protected SingleSelectionModel<Folder> otherSharedTreeSelectionModel;
396
    OtherSharedTreeViewModel otherSharedTreeViewModel;
397
    OtherSharedTreeView otherSharedTreeView = null;
398

    
399
    GroupTreeViewModel groupTreeViewModel;
400
    GroupTreeView groupTreeView;
401

    
402
    TreeView selectedTree;
403
    protected AccountResource account;
404

    
405
    Folder trash;
406

    
407
    List<Composite> treeViews = new ArrayList<Composite>();
408

    
409
    @SuppressWarnings("rawtypes")
410
    List<SingleSelectionModel> selectionModels = new ArrayList<SingleSelectionModel>();
411

    
412
    public Button upload;
413

    
414
    private HTML numOfFiles;
415

    
416
    private Toolbar toolbar;
417

    
418
    private FileUploadDialog fileUploadDialog = new FileUploadDialog(this);
419

    
420
    UploadAlert uploadAlert;
421

    
422
    Date lastModified;
423

    
424
    @Override
425
    public void onModuleLoad() {
426
        if(parseUserCredentials()) {
427
            initialize();
428
        }
429
    }
430

    
431
    static native void __ConsoleLog(String message) /*-{
432
      try { console.log(message); } catch (e) {}
433
    }-*/;
434

    
435
    public static void LOGError(Throwable error, StringBuilder sb) {
436
        if(!isLOGEnabled()) { return; }
437

    
438
        sb.append("\nException: [" + error.toString().replace("\n", "\n  ") + "]");
439
        Throwable cause = error.getCause();
440
        if(cause != null) {
441
            sb.append("\nCauses:\n");
442
            while(cause != null) {
443
                sb.append("  ");
444
                sb.append("[" + cause.toString().replace("\n", "\n  ")  + "]");
445
                sb.append("\n");
446
                cause = cause.getCause();
447
            }
448
        }
449
        else {
450
            sb.append("\n");
451
        }
452

    
453
        StackTraceElement[] stackTrace = error.getStackTrace();
454
        sb.append("Stack trace (" + stackTrace.length + " elements):\n");
455
        for(int i = 0; i < stackTrace.length; i++) {
456
            StackTraceElement errorElem = stackTrace[i];
457
            sb.append("  [" + i + "] ");
458
            sb.append(errorElem.toString());
459
            sb.append("\n");
460
        }
461
    }
462

    
463
    public static void LOGError(Throwable error) {
464
        if(!isLOGEnabled()) { return; }
465

    
466
        final StringBuilder sb = new StringBuilder();
467
        LOGError(error, sb);
468
        if(sb.length() > 0) {
469
            __ConsoleLog(sb.toString());
470
        }
471
    }
472

    
473
    public static boolean isLOGEnabled() {
474
        return IsLOGEnabled;
475
    }
476

    
477
    public static void LOG(Object ...args) {
478
        if(!isLOGEnabled()) { return; }
479

    
480
        final StringBuilder sb = new StringBuilder();
481
        for(Object arg : args) {
482
            if(arg instanceof Throwable) {
483
                LOGError((Throwable) arg, sb);
484
            }
485
            else {
486
                sb.append(arg);
487
            }
488
        }
489

    
490
        if(sb.length() > 0) {
491
            __ConsoleLog(sb.toString());
492
        }
493
    }
494

    
495
    private void initialize() {
496
        userCatalogs.updateWithIDAndName("*", "All Pithos users");
497

    
498
        lastModified = new Date(); //Initialize if-modified-since value with now.
499
        resources.pithosCss().ensureInjected();
500
        boolean bareContent = Window.Location.getParameter("noframe") != null;
501
        String contentWidth = bareContent ? Const.PERCENT_100 : Const.PERCENT_75;
502

    
503
        VerticalPanel outer = new VerticalPanel();
504
        outer.setWidth(Const.PERCENT_100);
505
        if(!bareContent) {
506
            outer.addStyleName("pithos-outer");
507
        }
508

    
509
        if(!bareContent) {
510
            topPanel = new TopPanel(this, Pithos.images);
511
            topPanel.setWidth(Const.PERCENT_100);
512
            outer.add(topPanel);
513
            outer.setCellHorizontalAlignment(topPanel, HasHorizontalAlignment.ALIGN_CENTER);
514
        }
515

    
516
        messagePanel.setVisible(false);
517
        outer.add(messagePanel);
518
        outer.setCellHorizontalAlignment(messagePanel, HasHorizontalAlignment.ALIGN_CENTER);
519
        outer.setCellVerticalAlignment(messagePanel, HasVerticalAlignment.ALIGN_MIDDLE);
520

    
521
        HorizontalPanel header = new HorizontalPanel();
522
        header.addStyleName("pithos-header");
523
        header.setWidth(contentWidth);
524
        if(bareContent) {
525
            header.addStyleName("pithos-header-noframe");
526
        }
527
        upload = new Button("Upload", new ClickHandler() {
528
            @Override
529
            public void onClick(ClickEvent event) {
530
                if(getSelection() != null) {
531
                    new UploadFileCommand(Pithos.this, null, getSelection()).execute();
532
                }
533
            }
534
        });
535
        upload.addStyleName("pithos-uploadButton");
536
        header.add(upload);
537
        header.setCellHorizontalAlignment(upload, HasHorizontalAlignment.ALIGN_LEFT);
538
        header.setCellVerticalAlignment(upload, HasVerticalAlignment.ALIGN_MIDDLE);
539

    
540
        toolbar = new Toolbar(this);
541
        header.add(toolbar);
542
        header.setCellHorizontalAlignment(toolbar, HasHorizontalAlignment.ALIGN_CENTER);
543
        header.setCellVerticalAlignment(toolbar, HasVerticalAlignment.ALIGN_MIDDLE);
544

    
545
        HorizontalPanel folderStatistics = new HorizontalPanel();
546
        folderStatistics.addStyleName("pithos-folderStatistics");
547
        numOfFiles = new HTML();
548
        folderStatistics.add(numOfFiles);
549
        folderStatistics.setCellVerticalAlignment(numOfFiles, HasVerticalAlignment.ALIGN_MIDDLE);
550
        HTML numOfFilesLabel = new HTML("&nbsp;Files");
551
        folderStatistics.add(numOfFilesLabel);
552
        folderStatistics.setCellVerticalAlignment(numOfFilesLabel, HasVerticalAlignment.ALIGN_MIDDLE);
553
        header.add(folderStatistics);
554
        header.setCellHorizontalAlignment(folderStatistics, HasHorizontalAlignment.ALIGN_RIGHT);
555
        header.setCellVerticalAlignment(folderStatistics, HasVerticalAlignment.ALIGN_MIDDLE);
556
        header.setCellWidth(folderStatistics, "40px");
557
        outer.add(header);
558
        outer.setCellHorizontalAlignment(header, HasHorizontalAlignment.ALIGN_CENTER);
559
        // Inner contains the various lists
560
        inner.sinkEvents(Event.ONCONTEXTMENU);
561
        inner.setWidth(Const.PERCENT_100);
562

    
563
        folderTreeSelectionModel = new SingleSelectionModel<Folder>();
564
        folderTreeSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
565
            @Override
566
            public void onSelectionChange(SelectionChangeEvent event) {
567
                if(folderTreeSelectionModel.getSelectedObject() != null) {
568
                    deselectOthers(folderTreeView, folderTreeSelectionModel);
569
                    applyPermissions(folderTreeSelectionModel.getSelectedObject());
570
                    Folder f = folderTreeSelectionModel.getSelectedObject();
571
                    updateFolder(f, true, new Command() {
572

    
573
                        @Override
574
                        public void execute() {
575
                            updateStatistics();
576
                        }
577
                    }, true);
578
                    showRelevantToolbarButtons();
579
                }
580
                else {
581
                    if(getSelectedTree().equals(folderTreeView)) {
582
                        setSelectedTree(null);
583
                    }
584
                    if(getSelectedTree() == null) {
585
                        showRelevantToolbarButtons();
586
                    }
587
                }
588
            }
589
        });
590
        selectionModels.add(folderTreeSelectionModel);
591

    
592
        folderTreeViewModel = new FolderTreeViewModel(this, folderTreeSelectionModel);
593
        folderTreeView = new FolderTreeView(folderTreeViewModel);
594
        treeViews.add(folderTreeView);
595

    
596
        fileList = new FileList(this, images);
597
        inner.add(fileList);
598

    
599
        trees = new VerticalPanel();
600
        trees.setWidth(Const.PERCENT_100);
601

    
602
        // Add the left and right panels to the split panel.
603
        splitPanel.setLeftWidget(trees);
604
        FlowPanel right = new FlowPanel();
605
        right.getElement().setId("rightPanel");
606
        right.add(inner);
607
        splitPanel.setRightWidget(right);
608
        splitPanel.setSplitPosition("219px");
609
        splitPanel.setSize(Const.PERCENT_100, Const.PERCENT_100);
610
        splitPanel.addStyleName("pithos-splitPanel");
611
        splitPanel.setWidth(contentWidth);
612
        outer.add(splitPanel);
613
        outer.setCellHorizontalAlignment(splitPanel, HasHorizontalAlignment.ALIGN_CENTER);
614

    
615
        if(!bareContent) {
616
            statusPanel = new StatusPanel();
617
            statusPanel.setWidth(Const.PERCENT_100);
618
            outer.add(statusPanel);
619
            outer.setCellHorizontalAlignment(statusPanel, HasHorizontalAlignment.ALIGN_CENTER);
620
        }
621
        else {
622
            splitPanel.addStyleName("pithos-splitPanel-noframe");
623
        }
624

    
625
        // Hook the window resize event, so that we can adjust the UI.
626
        Window.addResizeHandler(this);
627
        // Clear out the window's built-in margin, because we want to take
628
        // advantage of the entire client area.
629
        Window.setMargin("0px");
630
        // Finally, add the outer panel to the RootPanel, so that it will be
631
        // displayed.
632
        RootPanel.get().add(outer);
633
        // Call the window resized handler to get the initial sizes setup. Doing
634
        // this in a deferred command causes it to occur after all widgets'
635
        // sizes have been computed by the browser.
636
        Scheduler.get().scheduleIncremental(new RepeatingCommand() {
637

    
638
            @Override
639
            public boolean execute() {
640
                if(!isCloudbarReady()) {
641
                    return true;
642
                }
643
                onWindowResized(Window.getClientHeight());
644
                return false;
645
            }
646
        });
647

    
648
        Scheduler.get().scheduleDeferred(new ScheduledCommand() {
649
            @Override
650
            public void execute() {
651
                LOG("Pithos::initialize() Calling Pithos::fetchAccount()");
652
                fetchAccount(new Command() {
653

    
654
                    @Override
655
                    public void execute() {
656
                        if(!account.hasHomeContainer()) {
657
                            createHomeContainer(account, this);
658
                        }
659
                        else if(!account.hasTrashContainer()) {
660
                            createTrashContainer(this);
661
                        }
662
                        else {
663
                            for(Folder f : account.getContainers()) {
664
                                if(f.getName().equals(Const.TRASH_CONTAINER)) {
665
                                    trash = f;
666
                                    break;
667
                                }
668
                            }
669
                            trees.add(folderTreeView);
670
                            folderTreeViewModel.initialize(account, new Command() {
671

    
672
                                @Override
673
                                public void execute() {
674
                                    createMySharedTree();
675
                                }
676
                            });
677

    
678
                            HorizontalPanel separator = new HorizontalPanel();
679
                            separator.addStyleName("pithos-statisticsSeparator");
680
                            separator.add(new HTML(""));
681
                            trees.add(separator);
682

    
683
                            groupTreeViewModel = new GroupTreeViewModel(Pithos.this);
684
                            groupTreeView = new GroupTreeView(groupTreeViewModel);
685
                            treeViews.add(groupTreeView);
686
                            trees.add(groupTreeView);
687
                            folderTreeView.showStatistics(account);
688
                        }
689
                    }
690
                });
691
            }
692
        });
693
    }
694

    
695
    public void scheduleRefresh() {
696
        if(!Pithos.EnableScheduledRefresh) { return; }
697

    
698
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
699

    
700
            @Override
701
            public boolean execute() {
702
                final Folder f = getSelection();
703
                if(f == null) {
704
                    return true;
705
                }
706

    
707
                HeadRequest<Folder> head = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), f.getOwnerID(), "/" + f.getContainer()) {
708

    
709
                    @Override
710
                    public void onSuccess(Folder _result) {
711
                        lastModified = new Date();
712
                        if(getSelectedTree().equals(folderTreeView)) {
713
                            updateFolder(f, true, new Command() {
714

    
715
                                @Override
716
                                public void execute() {
717
                                    scheduleRefresh();
718
                                }
719

    
720
                            }, false);
721
                        }
722
                        else if(getSelectedTree().equals(mysharedTreeView)) {
723
                            updateSharedFolder(f, true, new Command() {
724

    
725
                                @Override
726
                                public void execute() {
727
                                    scheduleRefresh();
728
                                }
729
                            });
730
                        }
731
                        else {
732
                            scheduleRefresh();
733
                        }
734
                    }
735

    
736
                    @Override
737
                    public void onError(Throwable t) {
738
                        if(t instanceof RestException && ((RestException) t).getHttpStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
739
                            scheduleRefresh();
740
                        }
741
                        else if(retries >= MAX_RETRIES) {
742
                            LOG("Error heading folder. ", t);
743
                            setError(t);
744
                            if(t instanceof RestException) {
745
                                displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
746
                            }
747
                            else {
748
                                displayError("System error heading folder: " + t.getMessage());
749
                            }
750
                        }
751
                        else {//retry
752
                            LOG("Retry ", retries);
753
                            Scheduler.get().scheduleDeferred(this);
754
                        }
755
                    }
756

    
757
                    @Override
758
                    protected void onUnauthorized(Response response) {
759
                        if(retries >= MAX_RETRIES) {
760
                            sessionExpired();
761
                        }
762
                        else //retry
763
                        {
764
                            Scheduler.get().scheduleDeferred(this);
765
                        }
766
                    }
767
                };
768
                head.setHeader(Const.X_AUTH_TOKEN, getUserToken());
769
                head.setHeader(Const.IF_MODIFIED_SINCE, DateTimeFormat.getFormat(Const.DATE_FORMAT_1).format(lastModified, TimeZone.createTimeZone(0)) + " GMT");
770
                Scheduler.get().scheduleDeferred(head);
771

    
772
                return false;
773
            }
774
        }, 3000);
775
    }
776

    
777
    public void applyPermissions(Folder f) {
778
        if(f != null) {
779
            if(f.isInTrash()) {
780
                upload.setEnabled(false);
781
                disableUploadArea();
782
            }
783
            else {
784
                Boolean[] perms = f.getPermissions().get(userID);
785
                if(f.getOwnerID().equals(userID) || (perms != null && perms[1] != null && perms[1])) {
786
                    upload.setEnabled(true);
787
                    enableUploadArea();
788
                }
789
                else {
790
                    upload.setEnabled(false);
791
                    disableUploadArea();
792
                }
793
            }
794
        }
795
        else {
796
            upload.setEnabled(false);
797
            disableUploadArea();
798
        }
799
    }
800

    
801
    @SuppressWarnings({"rawtypes", "unchecked"})
802
    public void deselectOthers(TreeView _selectedTree, SingleSelectionModel model) {
803
        selectedTree = _selectedTree;
804

    
805
        for(SingleSelectionModel s : selectionModels) {
806
            if(!s.equals(model) && s.getSelectedObject() != null) {
807
                s.setSelected(s.getSelectedObject(), false);
808
            }
809
        }
810
    }
811

    
812
    public void showFiles(final Folder f) {
813
        Set<File> files = f.getFiles();
814
        showFiles(files);
815
    }
816

    
817
    public void showFiles(Set<File> files) {
818
        fileList.setFiles(new ArrayList<File>(files));
819
    }
820

    
821
    /**
822
     * Parse and store the user credentials to the appropriate fields.
823
     */
824
    private boolean parseUserCredentials() {
825
        final String cookie = otherProperties.get(Const.AUTH_COOKIE);
826
        String auth = Cookies.getCookie(cookie);
827
        if(auth == null) {
828
            authenticateUser();
829
            return false;
830
        }
831
        if(auth.startsWith("\"")) {
832
            auth = auth.substring(1);
833
        }
834
        if(auth.endsWith("\"")) {
835
            auth = auth.substring(0, auth.length() - 1);
836
        }
837
        String[] authSplit = auth.split("\\" + config.cookieSeparator(), 2);
838
        if(authSplit.length != 2) {
839
            authenticateUser();
840
            return false;
841
        }
842
        this.userID = authSplit[0];
843
        this.userToken = authSplit[1];
844

    
845
        String gotoUrl = Window.Location.getParameter("goto");
846
        if(gotoUrl != null && gotoUrl.length() > 0) {
847
            Window.Location.assign(gotoUrl);
848
            return false;
849
        }
850
        return true;
851
    }
852

    
853
    /**
854
     * Redirect the user to the login page for authentication.
855
     */
856
    protected void authenticateUser() {
857
        Dictionary otherProperties = Dictionary.getDictionary(Const.OTHER_PROPERTIES);
858
        Window.Location.assign(otherProperties.get(Const.LOGIN_URL) + Window.Location.getHref());
859
    }
860

    
861
    public void fetchAccount(final Command callback) {
862
        String path = "?format=json";
863

    
864
        GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, path) {
865
            @Override
866
            public void onSuccess(AccountResource accountResource) {
867
                account = accountResource;
868
                if(callback != null) {
869
                    callback.execute();
870
                }
871

    
872
                final List<String> memberIDs = new ArrayList<String>();
873
                final List<Group> groups = account.getGroups();
874
                for(Group group : groups) {
875
                    memberIDs.addAll(group.getMemberIDs());
876
                }
877
                memberIDs.add(Pithos.this.getUserID());
878

    
879
                final List<String> theUnknown = Pithos.this.filterUserIDsWithUnknownDisplayName(memberIDs);
880
                // Initialize the user catalog
881
                new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();
882
                LOG("Called new UpdateUserCatalogs(Pithos.this, theUnknown).scheduleDeferred();");
883
            }
884

    
885
            @Override
886
            public void onError(Throwable t) {
887
                LOG("Error getting account", t);
888
                setError(t);
889
                if(t instanceof RestException) {
890
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
891
                }
892
                else {
893
                    displayError("System error fetching user data: " + t.getMessage());
894
                }
895
            }
896

    
897
            @Override
898
            protected void onUnauthorized(Response response) {
899
                sessionExpired();
900
            }
901
        };
902
        getAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
903
        Scheduler.get().scheduleDeferred(getAccount);
904
    }
905

    
906
    public void updateStatistics() {
907
        HeadRequest<AccountResource> headAccount = new HeadRequest<AccountResource>(AccountResource.class, getStorageAPIURL(), userID, "", account) {
908

    
909
            @Override
910
            public void onSuccess(AccountResource _result) {
911
                folderTreeView.showStatistics(account);
912
            }
913

    
914
            @Override
915
            public void onError(Throwable t) {
916
                LOG("Error getting account", t);
917
                setError(t);
918
                if(t instanceof RestException) {
919
                    displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
920
                }
921
                else {
922
                    displayError("System error fetching user data: " + t.getMessage());
923
                }
924
            }
925

    
926
            @Override
927
            protected void onUnauthorized(Response response) {
928
                sessionExpired();
929
            }
930
        };
931
        headAccount.setHeader(Const.X_AUTH_TOKEN, userToken);
932
        Scheduler.get().scheduleDeferred(headAccount);
933
    }
934

    
935
    protected void createHomeContainer(final AccountResource _account, final Command callback) {
936
        String path = "/" + Const.HOME_CONTAINER;
937
        PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
938
            @Override
939
            public void onSuccess(Resource result) {
940
                if(!_account.hasTrashContainer()) {
941
                    createTrashContainer(callback);
942
                }
943
                else {
944
                    fetchAccount(callback);
945
                }
946
            }
947

    
948
            @Override
949
            public void onError(Throwable t) {
950
                LOG("Error creating pithos", t);
951
                setError(t);
952
                if(t instanceof RestException) {
953
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
954
                }
955
                else {
956
                    displayError("System error Error creating pithos: " + t.getMessage());
957
                }
958
            }
959

    
960
            @Override
961
            protected void onUnauthorized(Response response) {
962
                sessionExpired();
963
            }
964
        };
965
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
966
        Scheduler.get().scheduleDeferred(createPithos);
967
    }
968

    
969
    protected void createTrashContainer(final Command callback) {
970
        String path = "/" + Const.TRASH_CONTAINER;
971
        PutRequest createPithos = new PutRequest(getStorageAPIURL(), getUserID(), path) {
972
            @Override
973
            public void onSuccess(Resource result) {
974
                fetchAccount(callback);
975
            }
976

    
977
            @Override
978
            public void onError(Throwable t) {
979
                LOG("Error creating pithos", t);
980
                setError(t);
981
                if(t instanceof RestException) {
982
                    displayError("Error creating pithos: " + ((RestException) t).getHttpStatusText());
983
                }
984
                else {
985
                    displayError("System error Error creating pithos: " + t.getMessage());
986
                }
987
            }
988

    
989
            @Override
990
            protected void onUnauthorized(Response response) {
991
                sessionExpired();
992
            }
993
        };
994
        createPithos.setHeader(Const.X_AUTH_TOKEN, getUserToken());
995
        Scheduler.get().scheduleDeferred(createPithos);
996
    }
997

    
998
    /**
999
     * Creates an HTML fragment that places an image & caption together, for use
1000
     * in a group header.
1001
     *
1002
     * @param imageProto an image prototype for an image
1003
     * @param caption    the group caption
1004
     * @return the header HTML fragment
1005
     */
1006
    private String createHeaderHTML(AbstractImagePrototype imageProto, String caption) {
1007
        String captionHTML = "<table class='caption' cellpadding='0' "
1008
            + "cellspacing='0'>" + "<tr><td class='lcaption'>" + imageProto.getHTML()
1009
            + "</td><td id =" + caption + " class='rcaption'><b style='white-space:nowrap'>&nbsp;"
1010
            + caption + "</b></td></tr></table>";
1011
        return captionHTML;
1012
    }
1013

    
1014
    protected void onWindowResized(int height) {
1015
        // Adjust the split panel to take up the available room in the window.
1016
        int newHeight = height - splitPanel.getAbsoluteTop() - 153;
1017
        if(newHeight < 1) {
1018
            newHeight = 1;
1019
        }
1020
        splitPanel.setHeight("" + newHeight);
1021
        inner.setHeight("" + newHeight);
1022
    }
1023

    
1024
    native boolean isCloudbarReady()/*-{
1025
      if ($wnd.$("div.cloudbar") && $wnd.$("div.cloudbar").height() > 0)
1026
        return true;
1027
      return false;
1028
    }-*/;
1029

    
1030
    @Override
1031
    public void onResize(ResizeEvent event) {
1032
        int height = event.getHeight();
1033
        onWindowResized(height);
1034
    }
1035

    
1036
    /**
1037
     * Display an error message.
1038
     *
1039
     * @param msg the message to display
1040
     */
1041
    public void displayError(String msg) {
1042
        messagePanel.displayError(msg);
1043
        onWindowResized(Window.getClientHeight());
1044
    }
1045

    
1046
    /**
1047
     * Display a warning message.
1048
     *
1049
     * @param msg the message to display
1050
     */
1051
    public void displayWarning(String msg) {
1052
        messagePanel.displayWarning(msg);
1053
        onWindowResized(Window.getClientHeight());
1054
    }
1055

    
1056
    /**
1057
     * Display an informational message.
1058
     *
1059
     * @param msg the message to display
1060
     */
1061
    public void displayInformation(String msg) {
1062
        messagePanel.displayInformation(msg);
1063
        onWindowResized(Window.getClientHeight());
1064
    }
1065

    
1066
    /**
1067
     * Retrieve the fileList.
1068
     *
1069
     * @return the fileList
1070
     */
1071
    public FileList getFileList() {
1072
        return fileList;
1073
    }
1074

    
1075
    /**
1076
     * Retrieve the topPanel.
1077
     *
1078
     * @return the topPanel
1079
     */
1080
    TopPanel getTopPanel() {
1081
        return topPanel;
1082
    }
1083

    
1084
    /**
1085
     * Retrieve the clipboard.
1086
     *
1087
     * @return the clipboard
1088
     */
1089
    public Clipboard getClipboard() {
1090
        return clipboard;
1091
    }
1092

    
1093
    public StatusPanel getStatusPanel() {
1094
        return statusPanel;
1095
    }
1096

    
1097
    public String getUserToken() {
1098
        return userToken;
1099
    }
1100

    
1101
    public static native void preventIESelection() /*-{
1102
      $doc.body.onselectstart = function () {
1103
        return false;
1104
      };
1105
    }-*/;
1106

    
1107
    public static native void enableIESelection() /*-{
1108
      if ($doc.body.onselectstart != null)
1109
        $doc.body.onselectstart = null;
1110
    }-*/;
1111

    
1112
    public static String getStorageAPIURL() {
1113
        return STORAGE_API_URL;
1114
    }
1115

    
1116
    public static String getStorageViewURL() {
1117
        return STORAGE_VIEW_URL;
1118
    }
1119

    
1120
    public static boolean isShowCopyrightMessage() {
1121
        return SHOW_COPYRIGHT;
1122
    }
1123

    
1124
    public static String getUserCatalogsURL() {
1125
        return USER_CATALOGS_API_URL;
1126
    }
1127

    
1128
    public static String getFileViewURL(File file) {
1129
        return Pithos.getStorageViewURL() + file.getOwnerID() + file.getUri();
1130
    }
1131

    
1132
    /**
1133
     * History support for folder navigation
1134
     * adds a new browser history entry
1135
     *
1136
     * @param key
1137
     */
1138
    public void updateHistory(String key) {
1139
//                Replace any whitespace of the initial string to "+"
1140
//                String result = key.replaceAll("\\s","+");
1141
//                Add a new browser history entry.
1142
//                History.newItem(result);
1143
        History.newItem(key);
1144
    }
1145

    
1146
    public void deleteFolder(final Folder folder, final Command callback) {
1147
        final PleaseWaitPopup pwp = new PleaseWaitPopup();
1148
        pwp.center();
1149
        String path = "/" + folder.getContainer() + "/" + folder.getPrefix() + "?delimiter=/" + "&t=" + System.currentTimeMillis();
1150
        DeleteRequest deleteFolder = new DeleteRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1151

    
1152
            @Override
1153
            protected void onUnauthorized(Response response) {
1154
                pwp.hide();
1155
                sessionExpired();
1156
            }
1157

    
1158
            @Override
1159
            public void onSuccess(Resource result) {
1160
                updateFolder(folder.getParent(), true, new Command() {
1161

    
1162
                    @Override
1163
                    public void execute() {
1164
                        folderTreeSelectionModel.setSelected(folder.getParent(), true);
1165
                        updateStatistics();
1166
                        if(callback != null) {
1167
                            callback.execute();
1168
                        }
1169
                        pwp.hide();
1170
                    }
1171
                }, true);
1172
            }
1173

    
1174
            @Override
1175
            public void onError(Throwable t) {
1176
                LOG(t);
1177
                setError(t);
1178
                if(t instanceof RestException) {
1179
                    if(((RestException) t).getHttpStatusCode() != Response.SC_NOT_FOUND) {
1180
                        displayError("Unable to delete folder: " + ((RestException) t).getHttpStatusText());
1181
                    }
1182
                    else {
1183
                        onSuccess(null);
1184
                    }
1185
                }
1186
                else {
1187
                    displayError("System error unable to delete folder: " + t.getMessage());
1188
                }
1189
                pwp.hide();
1190
            }
1191
        };
1192
        deleteFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1193
        Scheduler.get().scheduleDeferred(deleteFolder);
1194
    }
1195

    
1196
    public FolderTreeView getFolderTreeView() {
1197
        return folderTreeView;
1198
    }
1199

    
1200
    public void copyFiles(final Iterator<File> iter, final String targetUsername, final String targetUri, final Command callback) {
1201
        if(iter.hasNext()) {
1202
            File file = iter.next();
1203
            String path = targetUri + "/" + file.getName();
1204
            PutRequest copyFile = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1205
                @Override
1206
                public void onSuccess(Resource result) {
1207
                    copyFiles(iter, targetUsername, targetUri, callback);
1208
                }
1209

    
1210
                @Override
1211
                public void onError(Throwable t) {
1212
                    LOG(t);
1213
                    setError(t);
1214
                    if(t instanceof RestException) {
1215
                        displayError("Unable to copy file: " + ((RestException) t).getHttpStatusText());
1216
                    }
1217
                    else {
1218
                        displayError("System error unable to copy file: " + t.getMessage());
1219
                    }
1220
                }
1221

    
1222
                @Override
1223
                protected void onUnauthorized(Response response) {
1224
                    sessionExpired();
1225
                }
1226
            };
1227
            copyFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1228
            copyFile.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(file.getUri()));
1229
            if(!file.getOwnerID().equals(targetUsername)) {
1230
                copyFile.setHeader(Const.X_SOURCE_ACCOUNT, URL.encodePathSegment(file.getOwnerID()));
1231
            }
1232
            copyFile.setHeader(Const.CONTENT_TYPE, file.getContentType());
1233
            Scheduler.get().scheduleDeferred(copyFile);
1234
        }
1235
        else if(callback != null) {
1236
            callback.execute();
1237
        }
1238
    }
1239

    
1240
    public void copyFolder(final Folder f, final String targetUsername, final String targetUri, boolean move, final Command callback) {
1241
        String path = targetUri + "?delimiter=/";
1242
        PutRequest copyFolder = new PutRequest(getStorageAPIURL(), targetUsername, path) {
1243
            @Override
1244
            public void onSuccess(Resource result) {
1245
                if(callback != null) {
1246
                    callback.execute();
1247
                }
1248
            }
1249

    
1250
            @Override
1251
            public void onError(Throwable t) {
1252
                LOG(t);
1253
                setError(t);
1254
                if(t instanceof RestException) {
1255
                    displayError("Unable to copy folder: " + ((RestException) t).getHttpStatusText());
1256
                }
1257
                else {
1258
                    displayError("System error copying folder: " + t.getMessage());
1259
                }
1260
            }
1261

    
1262
            @Override
1263
            protected void onUnauthorized(Response response) {
1264
                sessionExpired();
1265
            }
1266
        };
1267
        copyFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1268
        copyFolder.setHeader(Const.ACCEPT, "*/*");
1269
        copyFolder.setHeader(Const.CONTENT_LENGTH, "0");
1270
        copyFolder.setHeader(Const.CONTENT_TYPE, "application/directory");
1271
        if(!f.getOwnerID().equals(targetUsername)) {
1272
            copyFolder.setHeader(Const.X_SOURCE_ACCOUNT, f.getOwnerID());
1273
        }
1274
        if(move) {
1275
            copyFolder.setHeader(Const.X_MOVE_FROM, URL.encodePathSegment(f.getUri()));
1276
        }
1277
        else {
1278
            copyFolder.setHeader(Const.X_COPY_FROM, URL.encodePathSegment(f.getUri()));
1279
        }
1280
        Scheduler.get().scheduleDeferred(copyFolder);
1281
    }
1282

    
1283
    public void addSelectionModel(@SuppressWarnings("rawtypes") SingleSelectionModel model) {
1284
        selectionModels.add(model);
1285
    }
1286

    
1287
    public OtherSharedTreeView getOtherSharedTreeView() {
1288
        return otherSharedTreeView;
1289
    }
1290

    
1291
    public void updateTrash(boolean showFiles, Command callback) {
1292
        updateFolder(trash, showFiles, callback, true);
1293
    }
1294

    
1295
    public void updateGroupsNode() {
1296
        groupTreeView.updateGroupNode(null);
1297
    }
1298

    
1299
    public Group addGroup(String groupname) {
1300
        Group newGroup = new Group(groupname);
1301
        account.addGroup(newGroup);
1302
        groupTreeView.updateGroupNode(null);
1303
        return newGroup;
1304
    }
1305

    
1306
    public void removeGroup(Group group) {
1307
        account.removeGroup(group);
1308
        updateGroupsNode();
1309
    }
1310

    
1311
    public TreeView getSelectedTree() {
1312
        return selectedTree;
1313
    }
1314

    
1315
    public void setSelectedTree(TreeView selected) {
1316
        selectedTree = selected;
1317
    }
1318

    
1319
    public Folder getSelection() {
1320
        if(selectedTree != null) {
1321
            return selectedTree.getSelection();
1322
        }
1323
        return null;
1324
    }
1325

    
1326
    public void showFolderStatistics(int folderFileCount) {
1327
        numOfFiles.setHTML(String.valueOf(folderFileCount));
1328
    }
1329

    
1330
    public GroupTreeView getGroupTreeView() {
1331
        return groupTreeView;
1332
    }
1333

    
1334
    public void sessionExpired() {
1335
        new SessionExpiredDialog(this).center();
1336
    }
1337

    
1338
    public void updateRootFolder(Command callback) {
1339
        updateFolder(account.getPithos(), false, callback, true);
1340
    }
1341

    
1342
    void createMySharedTree() {
1343
        LOG("Pithos::createMySharedTree()");
1344
        mysharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1345
        mysharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1346
            @Override
1347
            public void onSelectionChange(SelectionChangeEvent event) {
1348
                if(mysharedTreeSelectionModel.getSelectedObject() != null) {
1349
                    deselectOthers(mysharedTreeView, mysharedTreeSelectionModel);
1350
                    upload.setEnabled(false);
1351
                    disableUploadArea();
1352
                    updateSharedFolder(mysharedTreeSelectionModel.getSelectedObject(), true);
1353
                    showRelevantToolbarButtons();
1354
                }
1355
                else {
1356
                    if(getSelectedTree().equals(mysharedTreeView)) {
1357
                        setSelectedTree(null);
1358
                    }
1359
                    if(getSelectedTree() == null) {
1360
                        showRelevantToolbarButtons();
1361
                    }
1362
                }
1363
            }
1364
        });
1365
        selectionModels.add(mysharedTreeSelectionModel);
1366
        mysharedTreeViewModel = new MysharedTreeViewModel(Pithos.this, mysharedTreeSelectionModel);
1367
        mysharedTreeViewModel.initialize(new Command() {
1368

    
1369
            @Override
1370
            public void execute() {
1371
                mysharedTreeView = new MysharedTreeView(mysharedTreeViewModel);
1372
                trees.insert(mysharedTreeView, 2);
1373
                treeViews.add(mysharedTreeView);
1374
                createOtherSharedTree();
1375
            }
1376
        });
1377
    }
1378

    
1379
    void createOtherSharedTree() {
1380
        LOG("Pithos::createOtherSharedTree()");
1381
        otherSharedTreeSelectionModel = new SingleSelectionModel<Folder>();
1382
        otherSharedTreeSelectionModel.addSelectionChangeHandler(new Handler() {
1383
            @Override
1384
            public void onSelectionChange(SelectionChangeEvent event) {
1385
                if(otherSharedTreeSelectionModel.getSelectedObject() != null) {
1386
                    deselectOthers(otherSharedTreeView, otherSharedTreeSelectionModel);
1387
                    applyPermissions(otherSharedTreeSelectionModel.getSelectedObject());
1388
                    updateOtherSharedFolder(otherSharedTreeSelectionModel.getSelectedObject(), true, null);
1389
                    showRelevantToolbarButtons();
1390
                }
1391
                else {
1392
                    if(getSelectedTree().equals(otherSharedTreeView)) {
1393
                        setSelectedTree(null);
1394
                    }
1395
                    if(getSelectedTree() == null) {
1396
                        showRelevantToolbarButtons();
1397
                    }
1398
                }
1399
            }
1400
        });
1401
        selectionModels.add(otherSharedTreeSelectionModel);
1402
        otherSharedTreeViewModel = new OtherSharedTreeViewModel(Pithos.this, otherSharedTreeSelectionModel);
1403
        // #3784 We show it empty...
1404
        otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, true);
1405
        trees.insert(otherSharedTreeView, 1);
1406

    
1407
        LOG("Pithos::createOtherSharedTree(), initializing otherSharedTreeViewModel with a callback");
1408
        otherSharedTreeViewModel.initialize(new Command() {
1409
            @Override
1410
            public void execute() {
1411
                // #3784 ... then remove the empty stuff and add a new view with the populated model
1412
                trees.remove(otherSharedTreeView);
1413

    
1414
                otherSharedTreeView = new OtherSharedTreeView(otherSharedTreeViewModel, false);
1415
                trees.insert(otherSharedTreeView, 1);
1416
                treeViews.add(otherSharedTreeView);
1417
                scheduleRefresh();
1418
            }
1419
        });
1420
    }
1421

    
1422
    public String getErrorData() {
1423
        final StringBuilder sb = new StringBuilder();
1424
        final String NL = Const.NL;
1425
        Throwable t = this.error;
1426
        while(t != null) {
1427
            sb.append(t.toString());
1428
            sb.append(NL);
1429
            StackTraceElement[] traces = t.getStackTrace();
1430
            for(StackTraceElement trace : traces) {
1431
                sb.append("  [");
1432
                sb.append(trace.getClassName());
1433
                sb.append("::");
1434
                sb.append(trace.getMethodName());
1435
                sb.append("() at ");
1436
                sb.append(trace.getFileName());
1437
                sb.append(":");
1438
                sb.append(trace.getLineNumber());
1439
                sb.append("]");
1440
                sb.append(NL);
1441
            }
1442
            t = t.getCause();
1443
        }
1444

    
1445
        return sb.toString();
1446
    }
1447

    
1448
    public void setError(Throwable t) {
1449
        error = t;
1450
        LOG(t);
1451
    }
1452

    
1453
    public void showRelevantToolbarButtons() {
1454
        toolbar.showRelevantButtons();
1455
    }
1456

    
1457
    public FileUploadDialog getFileUploadDialog() {
1458
        if(fileUploadDialog == null) {
1459
            fileUploadDialog = new FileUploadDialog(this);
1460
        }
1461
        return fileUploadDialog;
1462
    }
1463

    
1464
    public void hideUploadIndicator() {
1465
        upload.removeStyleName("pithos-uploadButton-loading");
1466
        upload.setTitle("");
1467
    }
1468

    
1469
    public void showUploadIndicator() {
1470
        upload.addStyleName("pithos-uploadButton-loading");
1471
        upload.setTitle("Upload in progress. Click for details.");
1472
    }
1473

    
1474
    public void scheduleFolderHeadCommand(final Folder folder, final Command callback) {
1475
        if(folder == null) {
1476
            if(callback != null) {
1477
                callback.execute();
1478
            }
1479
        }
1480
        else {
1481
            HeadRequest<Folder> headFolder = new HeadRequest<Folder>(Folder.class, getStorageAPIURL(), folder.getOwnerID(), folder.getUri(), folder) {
1482

    
1483
                @Override
1484
                public void onSuccess(Folder _result) {
1485
                    if(callback != null) {
1486
                        callback.execute();
1487
                    }
1488
                }
1489

    
1490
                @Override
1491
                public void onError(Throwable t) {
1492
                    if(t instanceof RestException) {
1493
                        if(((RestException) t).getHttpStatusCode() == Response.SC_NOT_FOUND) {
1494
                            final String path = folder.getUri();
1495
                            PutRequest newFolder = new PutRequest(getStorageAPIURL(), folder.getOwnerID(), path) {
1496
                                @Override
1497
                                public void onSuccess(Resource _result) {
1498
                                    scheduleFolderHeadCommand(folder, callback);
1499
                                }
1500

    
1501
                                @Override
1502
                                public void onError(Throwable _t) {
1503
                                    setError(_t);
1504
                                    if(_t instanceof RestException) {
1505
                                        displayError("Unable to create folder: " + ((RestException) _t).getHttpStatusText());
1506
                                    }
1507
                                    else {
1508
                                        displayError("System error creating folder: " + _t.getMessage());
1509
                                    }
1510
                                }
1511

    
1512
                                @Override
1513
                                protected void onUnauthorized(Response response) {
1514
                                    sessionExpired();
1515
                                }
1516
                            };
1517
                            newFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1518
                            newFolder.setHeader(Const.CONTENT_TYPE, "application/folder");
1519
                            newFolder.setHeader(Const.ACCEPT, "*/*");
1520
                            newFolder.setHeader(Const.CONTENT_LENGTH, "0");
1521
                            Scheduler.get().scheduleDeferred(newFolder);
1522
                        }
1523
                        else if(((RestException) t).getHttpStatusCode() == Response.SC_FORBIDDEN) {
1524
                            onSuccess(folder);
1525
                        }
1526
                        else {
1527
                            displayError("Error heading folder: " + ((RestException) t).getHttpStatusText());
1528
                        }
1529
                    }
1530
                    else {
1531
                        displayError("System error heading folder: " + t.getMessage());
1532
                    }
1533

    
1534
                    LOG("Error heading folder", t);
1535
                    setError(t);
1536
                }
1537

    
1538
                @Override
1539
                protected void onUnauthorized(Response response) {
1540
                    sessionExpired();
1541
                }
1542
            };
1543
            headFolder.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1544
            Scheduler.get().scheduleDeferred(headFolder);
1545
        }
1546
    }
1547

    
1548
    public void scheduleFileHeadCommand(File f, final Command callback) {
1549
        HeadRequest<File> headFile = new HeadRequest<File>(File.class, getStorageAPIURL(), f.getOwnerID(), f.getUri(), f) {
1550

    
1551
            @Override
1552
            public void onSuccess(File _result) {
1553
                if(callback != null) {
1554
                    callback.execute();
1555
                }
1556
            }
1557

    
1558
            @Override
1559
            public void onError(Throwable t) {
1560
                LOG("Error heading file", t);
1561
                setError(t);
1562
                if(t instanceof RestException) {
1563
                    displayError("Error heading file: " + ((RestException) t).getHttpStatusText());
1564
                }
1565
                else {
1566
                    displayError("System error heading file: " + t.getMessage());
1567
                }
1568
            }
1569

    
1570
            @Override
1571
            protected void onUnauthorized(Response response) {
1572
                sessionExpired();
1573
            }
1574
        };
1575
        headFile.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1576
        Scheduler.get().scheduleDeferred(headFile);
1577
    }
1578

    
1579
    public boolean isMySharedSelected() {
1580
        return getSelectedTree().equals(getMySharedTreeView());
1581
    }
1582

    
1583
    private Folder getUploadFolder() {
1584
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1585
            return getSelection();
1586
        }
1587
        return null;
1588
    }
1589

    
1590
    private void updateUploadFolder() {
1591
        updateUploadFolder(null);
1592
    }
1593

    
1594
    private void updateUploadFolder(final JsArrayString urls) {
1595
        if(folderTreeView.equals(getSelectedTree()) || otherSharedTreeView.equals(getSelectedTree())) {
1596
            Folder f = getSelection();
1597
            if(getSelectedTree().equals(getFolderTreeView())) {
1598
                updateFolder(f, true, new Command() {
1599

    
1600
                    @Override
1601
                    public void execute() {
1602
                        updateStatistics();
1603
                        if(urls != null) {
1604
                            selectUploadedFiles(urls);
1605
                        }
1606
                    }
1607
                }, false);
1608
            }
1609
            else {
1610
                updateOtherSharedFolder(f, true, null);
1611
            }
1612
        }
1613
    }
1614

    
1615
    public native void disableUploadArea() /*-{
1616
      var uploader = $wnd.$("#uploader").pluploadQueue();
1617
      var dropElm = $wnd.document.getElementById('rightPanel');
1618
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1619
    }-*/;
1620

    
1621
    public native void enableUploadArea() /*-{
1622
      var uploader = $wnd.$("#uploader").pluploadQueue();
1623
      var dropElm = $wnd.document.getElementById('rightPanel');
1624
      $wnd.plupload.removeAllEvents(dropElm, uploader.id);
1625
      if (uploader.runtime == 'html5') {
1626
        uploader.settings.drop_element = 'rightPanel';
1627
        uploader.trigger('PostInit');
1628
      }
1629
    }-*/;
1630

    
1631
    public void showUploadAlert(int nOfFiles) {
1632
        if(uploadAlert == null) {
1633
            uploadAlert = new UploadAlert(this, nOfFiles);
1634
        }
1635
        if(!uploadAlert.isShowing()) {
1636
            uploadAlert.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
1637

    
1638
                @Override
1639
                public void setPosition(int offsetWidth, int offsetHeight) {
1640
                    uploadAlert.setPopupPosition((Window.getClientWidth() - offsetWidth) / 2, statusPanel.getAbsoluteTop() - offsetHeight);
1641
                }
1642
            });
1643
        }
1644
        uploadAlert.setNumOfFiles(nOfFiles);
1645
    }
1646

    
1647
    public void hideUploadAlert() {
1648
        if(uploadAlert != null && uploadAlert.isShowing()) {
1649
            uploadAlert.hide();
1650
        }
1651
    }
1652

    
1653
    public void selectUploadedFiles(JsArrayString urls) {
1654
        List<String> selectedUrls = new ArrayList<String>();
1655
        for(int i = 0; i < urls.length(); i++) {
1656
            selectedUrls.add(urls.get(i));
1657
        }
1658
        fileList.selectByUrl(selectedUrls);
1659
    }
1660

    
1661
    public void purgeContainer(final Folder container) {
1662
        String path = "/" + container.getName() + "?delimiter=/";
1663
        DeleteRequest delete = new DeleteRequest(getStorageAPIURL(), getUserID(), path) {
1664

    
1665
            @Override
1666
            protected void onUnauthorized(Response response) {
1667
                sessionExpired();
1668
            }
1669

    
1670
            @Override
1671
            public void onSuccess(Resource result) {
1672
                updateFolder(container, true, null, true);
1673
            }
1674

    
1675
            @Override
1676
            public void onError(Throwable t) {
1677
                LOG("Error deleting trash", t);
1678
                setError(t);
1679
                if(t instanceof RestException) {
1680
                    displayError("Error deleting trash: " + ((RestException) t).getHttpStatusText());
1681
                }
1682
                else {
1683
                    displayError("System error deleting trash: " + t.getMessage());
1684
                }
1685
            }
1686
        };
1687
        delete.setHeader(Const.X_AUTH_TOKEN, getUserToken());
1688
        Scheduler.get().scheduleDeferred(delete);
1689
    }
1690
}