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