Fix regression with empty "Shared by me"
[pithos-web-client] / src / gr / grnet / pithos / web / client / mysharedtree / MysharedTreeViewModel.java
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
36 package gr.grnet.pithos.web.client.mysharedtree;
37
38 import gr.grnet.pithos.web.client.Const;
39 import gr.grnet.pithos.web.client.FolderContextMenu;
40 import gr.grnet.pithos.web.client.Pithos;
41 import gr.grnet.pithos.web.client.foldertree.AccountResource;
42 import gr.grnet.pithos.web.client.foldertree.File;
43 import gr.grnet.pithos.web.client.foldertree.Folder;
44 import gr.grnet.pithos.web.client.mysharedtree.MysharedTreeView.Templates;
45 import gr.grnet.pithos.web.client.rest.GetRequest;
46 import gr.grnet.pithos.web.client.rest.RestException;
47
48 import java.util.Iterator;
49
50 import com.google.gwt.cell.client.AbstractCell;
51 import com.google.gwt.cell.client.Cell;
52 import com.google.gwt.cell.client.ValueUpdater;
53 import com.google.gwt.core.client.GWT;
54 import com.google.gwt.core.client.Scheduler;
55 import com.google.gwt.event.dom.client.ContextMenuEvent;
56 import com.google.gwt.http.client.Response;
57 import com.google.gwt.http.client.URL;
58 import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
59 import com.google.gwt.user.client.Command;
60 import com.google.gwt.user.client.ui.AbstractImagePrototype;
61 import com.google.gwt.view.client.ListDataProvider;
62 import com.google.gwt.view.client.SingleSelectionModel;
63 import com.google.gwt.view.client.TreeViewModel;
64
65 public class MysharedTreeViewModel implements TreeViewModel {
66
67     protected Pithos app;
68
69     Folder dummy = new Folder("No files shared by me");
70     
71     private Cell<Folder> folderCell = new AbstractCell<Folder>(ContextMenuEvent.getType().getName()) {
72
73        @Override
74         public void render(Context context, Folder folder, SafeHtmlBuilder safeHtmlBuilder) {
75            if (!folder.equals(dummy)) {
76                    String html = AbstractImagePrototype.create(MysharedTreeView.images.folderYellow()).getHTML();
77                 safeHtmlBuilder.appendHtmlConstant(html).appendHtmlConstant("&nbsp;");
78            }
79             safeHtmlBuilder.append(Templates.INSTANCE.nameSpan(folder.getName()));
80         }
81
82        @Override
83        public void onBrowserEvent(Context context, com.google.gwt.dom.client.Element parent, final Folder folder, com.google.gwt.dom.client.NativeEvent event, ValueUpdater<Folder> valueUpdater) {
84            if (event.getType().equals(ContextMenuEvent.getType().getName())) {
85                 final int x = event.getClientX();
86                 final int y = event.getClientY();
87                MysharedTreeViewModel.this.selectionModel.setSelected(folder, true);
88                app.scheduleFolderHeadCommand(folder, new Command() {
89                                         
90                                         @Override
91                                         public void execute() {
92                                 FolderContextMenu menu = new FolderContextMenu(app, MysharedTreeView.images, app.getSelectedTree(), folder);
93                                 menu.setPopupPosition(x, y);
94                                 menu.show();
95                                         }
96                                 });
97            }
98        }
99     };
100
101     protected ListDataProvider<Folder> firstLevelDataProvider = new ListDataProvider<Folder>();
102  
103     protected SingleSelectionModel<Folder> selectionModel;
104
105     public MysharedTreeViewModel(Pithos _app, SingleSelectionModel<Folder> selectionModel) {
106         app = _app;
107         this.selectionModel = selectionModel;
108     }
109
110     @Override
111     public <T> NodeInfo<?> getNodeInfo(T value) {
112         if (value == null) {
113                 fetchSharedContainers(null);
114                 if (firstLevelDataProvider.getList().get(0).equals(dummy))
115                 return new DefaultNodeInfo<Folder>(firstLevelDataProvider, folderCell, null, null);
116             return new DefaultNodeInfo<Folder>(firstLevelDataProvider, folderCell, selectionModel, null);
117         }
118         return null;
119     }
120
121         private void fetchSharedContainers(final Command callback) {
122         app.LOG("MysharedTreeViewModel::fetchSharedContainers(), callback=", callback);
123         String path = "?format=json&shared=&public=";
124         GetRequest<AccountResource> getAccount = new GetRequest<AccountResource>(AccountResource.class, app.getApiPath(), app.getUserID(), path) {
125             @Override
126             public void onSuccess(final AccountResource _result) {
127                                 firstLevelDataProvider.getList().clear();
128                 for (Folder c : _result.getContainers()) {
129                         if (c.isHome())
130                                 firstLevelDataProvider.getList().add(0, c); //Pithos is always first
131                         else if (!c.isTrash())
132                                 firstLevelDataProvider.getList().add(c);
133                 }
134                 if (firstLevelDataProvider.getList().isEmpty())
135                         firstLevelDataProvider.getList().add(dummy);
136                                 if (callback != null) {
137                     app.LOG("MysharedTreeViewModel::fetchSharedContainers(), executing callback");
138                     callback.execute();
139                 }
140             }
141
142             @Override
143             public void onError(Throwable t) {
144                 GWT.log("Error getting account", t);
145                                 app.setError(t);
146                 if (t instanceof RestException)
147                     app.displayError("Error getting account: " + ((RestException) t).getHttpStatusText());
148                 else
149                     app.displayError("System error fetching user data: " + t.getMessage());
150             }
151
152                         @Override
153                         protected void onUnauthorized(Response response) {
154                                 app.sessionExpired();
155                         }
156         };
157         getAccount.setHeader(Const.X_AUTH_TOKEN, app.getUserToken());
158         Scheduler.get().scheduleDeferred(getAccount);
159         }
160
161         @Override
162     public boolean isLeaf(Object o) {
163                 if (o == null)
164                         return firstLevelDataProvider.getList().isEmpty();
165                 return true;
166     }
167
168     protected void fetchFolder(final Iterator<Folder> iter, final Command callback) {
169         app.LOG("MysharedTreeViewModel::fetchFolder(), iter=", iter.hasNext(), ", callback=", callback);
170         if (iter.hasNext()) {
171             final Folder f = iter.next();
172
173             String path = "/" + f.getContainer() + "?format=json&shared=&public=&delimiter=/&prefix=" + URL.encodeQueryString(f.getPrefix());
174             GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, app.getApiPath(), f.getOwnerID(), path, f) {
175                 @Override
176                 public void onSuccess(Folder _result) {
177                     fetchFolder(iter, callback);
178                 }
179
180                 @Override
181                 public void onError(Throwable t) {
182                     GWT.log("Error getting folder", t);
183                                         app.setError(t);
184                     if (t instanceof RestException)
185                         app.displayError("Error getting folder: " + ((RestException) t).getHttpStatusText());
186                     else
187                         app.displayError("System error fetching folder: " + t.getMessage());
188                 }
189
190                                 @Override
191                                 protected void onUnauthorized(Response response) {
192                                         app.sessionExpired();
193                                 }
194             };
195             getFolder.setHeader(Const.X_AUTH_TOKEN, app.getUserToken());
196             Scheduler.get().scheduleDeferred(getFolder);
197         }
198         else if(callback != null) {
199             callback.execute();
200         }
201     }
202
203     public Folder getSelection() {
204         return selectionModel.getSelectedObject();
205     }
206
207     public void updateFolder(Folder folder, boolean showfiles, Command callback) {
208         fetchFolder(folder, showfiles, callback);
209     }
210
211     public void fetchFolder(final Folder f, final boolean showfiles, final Command callback) {
212         app.LOG("MysharedTreeViewModel::fetchFolder(), folder=", f, ", showfiles=", showfiles, ", callback=", callback);
213         String path = "/" + f.getContainer() + "?format=json&shared=&public=" + URL.encodeQueryString(f.getPrefix());
214         GetRequest<Folder> getFolder = new GetRequest<Folder>(Folder.class, app.getApiPath(), f.getOwnerID(), path, f) {
215             @Override
216             public void onSuccess(final Folder _result) {
217                 for (File file : _result.getFiles()) {
218                         String name = file.getName();
219                                         if (name.lastIndexOf("/") != -1) {
220                                                 file.setName(name.substring(name.lastIndexOf("/") + 1, name.length()));
221                                         }
222                 }
223
224                 if (showfiles)
225                     app.showFiles(_result);
226                 if (callback != null)
227                         callback.execute();
228             }
229
230             @Override
231             public void onError(Throwable t) {
232                 GWT.log("Error getting folder", t);
233                                 app.setError(t);
234                 if (t instanceof RestException)
235                     app.displayError("Error getting folder: " + ((RestException) t).getHttpStatusText());
236                 else
237                     app.displayError("System error fetching folder: " + t.getMessage());
238             }
239
240                         @Override
241                         protected void onUnauthorized(Response response) {
242                                 app.sessionExpired();
243                         }
244         };
245         getFolder.setHeader("X-Auth-Token", app.getUserToken());
246         Scheduler.get().scheduleDeferred(getFolder);
247     }
248
249         public void initialize(Command callback) {
250                 fetchSharedContainers(callback);
251         }
252 }