Merge branch 'release-0.6.1'
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / GetStatusAjaxPage.java
1 /*
2  * Sone - GetStatusAjaxPage.java - Copyright © 2010 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.web.ajax;
19
20 import java.io.IOException;
21 import java.io.StringWriter;
22 import java.text.DateFormat;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.Date;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Set;
30
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.Reply;
33 import net.pterodactylus.sone.data.Sone;
34 import net.pterodactylus.sone.notify.ListNotificationFilters;
35 import net.pterodactylus.sone.template.SoneAccessor;
36 import net.pterodactylus.sone.web.WebInterface;
37 import net.pterodactylus.util.filter.Filter;
38 import net.pterodactylus.util.filter.Filters;
39 import net.pterodactylus.util.json.JsonArray;
40 import net.pterodactylus.util.json.JsonObject;
41 import net.pterodactylus.util.notify.Notification;
42 import net.pterodactylus.util.notify.TemplateNotification;
43 import net.pterodactylus.util.template.TemplateContext;
44
45 /**
46  * The “get status” AJAX handler returns all information that is necessary to
47  * update the web interface in real-time.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class GetStatusAjaxPage extends JsonPage {
52
53         /** Date formatter. */
54         private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
55
56         /**
57          * Creates a new “get status” AJAX handler.
58          *
59          * @param webInterface
60          *            The Sone web interface
61          */
62         public GetStatusAjaxPage(WebInterface webInterface) {
63                 super("getStatus.ajax", webInterface);
64         }
65
66         /**
67          * {@inheritDoc}
68          */
69         @Override
70         protected JsonObject createJsonObject(Request request) {
71                 final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
72                 /* load Sones. */
73                 boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "true"));
74                 Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
75                 if (loadAllSones) {
76                         sones.addAll(webInterface.getCore().getSones());
77                 }
78                 JsonArray jsonSones = new JsonArray();
79                 for (Sone sone : sones) {
80                         if (sone == null) {
81                                 continue;
82                         }
83                         JsonObject jsonSone = createJsonSone(sone);
84                         jsonSones.add(jsonSone);
85                 }
86                 /* load notifications. */
87                 List<Notification> notifications = ListNotificationFilters.filterNotifications(new ArrayList<Notification>(webInterface.getNotifications().getNotifications()), currentSone);
88                 Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
89                 JsonArray jsonNotifications = new JsonArray();
90                 for (Notification notification : notifications) {
91                         jsonNotifications.add(createJsonNotification(notification));
92                 }
93                 /* load new posts. */
94                 Set<Post> newPosts = webInterface.getNewPosts();
95                 if (currentSone != null) {
96                         newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
97
98                                 @Override
99                                 public boolean filterObject(Post post) {
100                                         return currentSone.hasFriend(post.getSone().getId()) || currentSone.equals(post.getSone()) || currentSone.equals(post.getRecipient());
101                                 }
102
103                         });
104                 }
105                 JsonArray jsonPosts = new JsonArray();
106                 for (Post post : newPosts) {
107                         JsonObject jsonPost = new JsonObject();
108                         jsonPost.put("id", post.getId());
109                         jsonPost.put("sone", post.getSone().getId());
110                         jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
111                         jsonPost.put("time", post.getTime());
112                         jsonPosts.add(jsonPost);
113                 }
114                 /* load new replies. */
115                 Set<Reply> newReplies = webInterface.getNewReplies();
116                 if (currentSone != null) {
117                         newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() {
118
119                                 @Override
120                                 public boolean filterObject(Reply reply) {
121                                         return currentSone.hasFriend(reply.getPost().getSone().getId()) || currentSone.equals(reply.getPost().getSone()) || currentSone.equals(reply.getPost().getRecipient());
122                                 }
123
124                         });
125                 }
126                 JsonArray jsonReplies = new JsonArray();
127                 for (Reply reply : newReplies) {
128                         JsonObject jsonReply = new JsonObject();
129                         jsonReply.put("id", reply.getId());
130                         jsonReply.put("sone", reply.getSone().getId());
131                         jsonReply.put("post", reply.getPost().getId());
132                         jsonReply.put("postSone", reply.getPost().getSone().getId());
133                         jsonReplies.add(jsonReply);
134                 }
135                 return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotifications).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
136         }
137
138         /**
139          * {@inheritDoc}
140          */
141         @Override
142         protected boolean needsFormPassword() {
143                 return false;
144         }
145
146         /**
147          * {@inheritDoc}
148          */
149         @Override
150         protected boolean requiresLogin() {
151                 return false;
152         }
153
154         //
155         // PRIVATE METHODS
156         //
157
158         /**
159          * Creates a JSON object from the given Sone.
160          *
161          * @param sone
162          *            The Sone to convert to a JSON object
163          * @return The JSON representation of the given Sone
164          */
165         private JsonObject createJsonSone(Sone sone) {
166                 JsonObject jsonSone = new JsonObject();
167                 jsonSone.put("id", sone.getId());
168                 jsonSone.put("name", SoneAccessor.getNiceName(sone));
169                 jsonSone.put("local", sone.getInsertUri() != null);
170                 jsonSone.put("status", webInterface.getCore().getSoneStatus(sone).name());
171                 jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone));
172                 jsonSone.put("locked", webInterface.getCore().isLocked(sone));
173                 jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0);
174                 synchronized (dateFormat) {
175                         jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime())));
176                 }
177                 jsonSone.put("age", (System.currentTimeMillis() - sone.getTime()) / 1000);
178                 return jsonSone;
179         }
180
181         /**
182          * Creates a JSON object from the given notification.
183          *
184          * @param notification
185          *            The notification to create a JSON object
186          * @return The JSON object
187          */
188         private JsonObject createJsonNotification(Notification notification) {
189                 JsonObject jsonNotification = new JsonObject();
190                 jsonNotification.put("id", notification.getId());
191                 StringWriter notificationWriter = new StringWriter();
192                 try {
193                         if (notification instanceof TemplateNotification) {
194                                 TemplateContext templateContext = webInterface.getTemplateContextFactory().createTemplateContext().mergeContext(((TemplateNotification) notification).getTemplateContext());
195                                 templateContext.set("notification", notification);
196                                 ((TemplateNotification) notification).render(templateContext, notificationWriter);
197                         } else {
198                                 notification.render(notificationWriter);
199                         }
200                 } catch (IOException ioe1) {
201                         /* StringWriter never throws, ignore. */
202                 }
203                 jsonNotification.put("text", notificationWriter.toString());
204                 jsonNotification.put("createdTime", notification.getCreatedTime());
205                 jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime());
206                 jsonNotification.put("dismissable", notification.isDismissable());
207                 return jsonNotification;
208         }
209
210 }