Store notification page in AJAX status.
[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.text.DateFormat;
21 import java.text.SimpleDateFormat;
22 import java.util.Collections;
23 import java.util.Date;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Set;
27
28 import net.pterodactylus.sone.data.Post;
29 import net.pterodactylus.sone.data.PostReply;
30 import net.pterodactylus.sone.data.Sone;
31 import net.pterodactylus.sone.notify.ListNotificationFilters;
32 import net.pterodactylus.sone.template.SoneAccessor;
33 import net.pterodactylus.sone.web.WebInterface;
34 import net.pterodactylus.sone.web.page.FreenetRequest;
35 import net.pterodactylus.util.filter.Filter;
36 import net.pterodactylus.util.filter.Filters;
37 import net.pterodactylus.util.json.JsonArray;
38 import net.pterodactylus.util.json.JsonObject;
39 import net.pterodactylus.util.notify.Notification;
40 import net.pterodactylus.util.object.HashCode;
41
42 /**
43  * The “get status” AJAX handler returns all information that is necessary to
44  * update the web interface in real-time.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class GetStatusAjaxPage extends JsonPage {
49
50         /** Date formatter. */
51         private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
52
53         /**
54          * Creates a new “get status” AJAX handler.
55          *
56          * @param webInterface
57          *            The Sone web interface
58          */
59         public GetStatusAjaxPage(WebInterface webInterface) {
60                 super("getStatus.ajax", webInterface);
61         }
62
63         /**
64          * {@inheritDoc}
65          */
66         @Override
67         protected JsonObject createJsonObject(FreenetRequest request) {
68                 final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
69                 /* load Sones. */
70                 boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "false"));
71                 Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
72                 if (loadAllSones) {
73                         sones.addAll(webInterface.getCore().getSones());
74                 } else {
75                         String loadSoneIds = request.getHttpRequest().getParam("soneIds");
76                         if (loadSoneIds.length() > 0) {
77                                 String[] soneIds = loadSoneIds.split(",");
78                                 for (String soneId : soneIds) {
79                                         /* just add it, we skip null further down. */
80                                         sones.add(webInterface.getCore().getSone(soneId, false));
81                                 }
82                         }
83                 }
84                 JsonArray jsonSones = new JsonArray();
85                 for (Sone sone : sones) {
86                         if (sone == null) {
87                                 continue;
88                         }
89                         JsonObject jsonSone = createJsonSone(sone);
90                         jsonSones.add(jsonSone);
91                 }
92                 /* load notifications. */
93                 List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone);
94                 int notificationHash = HashCode.hashCode(notifications);
95                 Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
96                 JsonArray jsonNotificationInformations = new JsonArray();
97                 for (Notification notification : notifications) {
98                         jsonNotificationInformations.add(createJsonNotificationInformation(notification));
99                 }
100                 /* load new posts. */
101                 Set<Post> newPosts = webInterface.getNewPosts();
102                 if (currentSone != null) {
103                         newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
104
105                                 @Override
106                                 public boolean filterObject(Post post) {
107                                         return ListNotificationFilters.isPostVisible(currentSone, post);
108                                 }
109
110                         });
111                 }
112                 JsonArray jsonPosts = new JsonArray();
113                 for (Post post : newPosts) {
114                         JsonObject jsonPost = new JsonObject();
115                         jsonPost.put("id", post.getId());
116                         jsonPost.put("sone", post.getSone().getId());
117                         jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
118                         jsonPost.put("time", post.getTime());
119                         jsonPosts.add(jsonPost);
120                 }
121                 /* load new replies. */
122                 Set<PostReply> newReplies = webInterface.getNewReplies();
123                 if (currentSone != null) {
124                         newReplies = Filters.filteredSet(newReplies, new Filter<PostReply>() {
125
126                                 @Override
127                                 public boolean filterObject(PostReply reply) {
128                                         return ListNotificationFilters.isReplyVisible(currentSone, reply);
129                                 }
130
131                         });
132                 }
133                 /* remove replies to unknown posts. */
134                 newReplies = Filters.filteredSet(newReplies, new Filter<PostReply>() {
135
136                         @Override
137                         public boolean filterObject(PostReply reply) {
138                                 return (reply.getPost() != null) && (reply.getPost().getSone() != null);
139                         }
140                 });
141                 JsonArray jsonReplies = new JsonArray();
142                 for (PostReply reply : newReplies) {
143                         JsonObject jsonReply = new JsonObject();
144                         jsonReply.put("id", reply.getId());
145                         jsonReply.put("sone", reply.getSone().getId());
146                         jsonReply.put("post", reply.getPost().getId());
147                         jsonReply.put("postSone", reply.getPost().getSone().getId());
148                         jsonReplies.add(jsonReply);
149                 }
150                 return createSuccessJsonObject().put("loggedIn", currentSone != null).put("options", createJsonOptions(currentSone)).put("sones", jsonSones).put("notificationHash", notificationHash).put("notifications", jsonNotificationInformations).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
151         }
152
153         /**
154          * {@inheritDoc}
155          */
156         @Override
157         protected boolean needsFormPassword() {
158                 return false;
159         }
160
161         /**
162          * {@inheritDoc}
163          */
164         @Override
165         protected boolean requiresLogin() {
166                 return false;
167         }
168
169         //
170         // PRIVATE METHODS
171         //
172
173         /**
174          * Creates a JSON object from the given Sone.
175          *
176          * @param sone
177          *            The Sone to convert to a JSON object
178          * @return The JSON representation of the given Sone
179          */
180         private JsonObject createJsonSone(Sone sone) {
181                 JsonObject jsonSone = new JsonObject();
182                 jsonSone.put("id", sone.getId());
183                 jsonSone.put("name", SoneAccessor.getNiceName(sone));
184                 jsonSone.put("local", sone.getInsertUri() != null);
185                 jsonSone.put("status", webInterface.getCore().getSoneStatus(sone).name());
186                 jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone));
187                 jsonSone.put("locked", webInterface.getCore().isLocked(sone));
188                 jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0);
189                 synchronized (dateFormat) {
190                         jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime())));
191                 }
192                 jsonSone.put("lastUpdatedText", GetTimesAjaxPage.getTime(webInterface, sone.getTime()).getText());
193                 return jsonSone;
194         }
195
196         /**
197          * Creates a JSON object that only contains the ID and the last-updated time
198          * of the given notification.
199          *
200          * @see Notification#getId()
201          * @see Notification#getLastUpdatedTime()
202          * @param notification
203          *            The notification
204          * @return A JSON object containing the notification ID and last-updated
205          *         time
206          */
207         private JsonObject createJsonNotificationInformation(Notification notification) {
208                 JsonObject jsonNotification = new JsonObject();
209                 jsonNotification.put("id", notification.getId());
210                 jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime());
211                 return jsonNotification;
212         }
213
214         /**
215          * Creates a JSON object that contains all options that are currently in
216          * effect for the given Sone (or overall, if the given Sone is {@code null}
217          * ).
218          *
219          * @param currentSone
220          *            The current Sone (may be {@code null})
221          * @return The current options
222          */
223         private JsonObject createJsonOptions(Sone currentSone) {
224                 JsonObject options = new JsonObject();
225                 if (currentSone != null) {
226                         options.put("ShowNotification/NewSones", currentSone.getOptions().getBooleanOption("ShowNotification/NewSones").get());
227                         options.put("ShowNotification/NewPosts", currentSone.getOptions().getBooleanOption("ShowNotification/NewPosts").get());
228                         options.put("ShowNotification/NewReplies", currentSone.getOptions().getBooleanOption("ShowNotification/NewReplies").get());
229                 }
230                 return options;
231         }
232
233 }