Iterate over IDs and load Sones correctly.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / ajax / GetStatusAjaxPage.java
1 /*
2  * Sone - GetStatusAjaxPage.java - Copyright © 2010–2013 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 static com.fasterxml.jackson.databind.node.JsonNodeFactory.instance;
21
22 import java.text.DateFormat;
23 import java.text.SimpleDateFormat;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.HashSet;
29 import java.util.List;
30 import java.util.Set;
31
32 import net.pterodactylus.sone.data.Post;
33 import net.pterodactylus.sone.data.PostReply;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.notify.ListNotificationFilters;
36 import net.pterodactylus.sone.template.SoneAccessor;
37 import net.pterodactylus.sone.utils.Optionals;
38 import net.pterodactylus.sone.web.WebInterface;
39 import net.pterodactylus.sone.web.page.FreenetRequest;
40 import net.pterodactylus.util.notify.Notification;
41
42 import com.fasterxml.jackson.databind.JsonNode;
43 import com.fasterxml.jackson.databind.node.ArrayNode;
44 import com.fasterxml.jackson.databind.node.ObjectNode;
45 import com.google.common.base.Optional;
46 import com.google.common.base.Predicate;
47 import com.google.common.collect.Collections2;
48 import com.google.common.collect.FluentIterable;
49
50 /**
51  * The “get status” AJAX handler returns all information that is necessary to
52  * update the web interface in real-time.
53  *
54  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55  */
56 public class GetStatusAjaxPage extends JsonPage {
57
58         /** Date formatter. */
59         private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
60
61         /**
62          * Creates a new “get status” AJAX handler.
63          *
64          * @param webInterface
65          *            The Sone web interface
66          */
67         public GetStatusAjaxPage(WebInterface webInterface) {
68                 super("getStatus.ajax", webInterface);
69         }
70
71         /**
72          * {@inheritDoc}
73          */
74         @Override
75         protected JsonReturnObject createJsonObject(FreenetRequest request) {
76                 final Optional<Sone> currentSone = getCurrentSone(request.getToadletContext(), false);
77                 /* load Sones. always return the status of the current Sone. */
78                 Set<Sone> sones = new HashSet<Sone>(currentSone.asSet());
79                 String loadSoneIds = request.getHttpRequest().getParam("soneIds");
80                 if (loadSoneIds.length() > 0) {
81                         String[] soneIds = loadSoneIds.split(",");
82                         FluentIterable.from(Arrays.asList(soneIds))
83                                         .transform(webInterface.getCore().soneLoader())
84                                         .filter(Optionals.isPresent())
85                                         .transform(Optionals.<Sone>get())
86                                         .copyInto(sones);
87                 }
88                 ArrayNode jsonSones = new ArrayNode(instance);
89                 for (Sone sone : sones) {
90                         jsonSones.add(createJsonSone(sone));
91                 }
92                 /* load notifications. */
93                 List<Notification> notifications = ListNotificationFilters.filterNotifications(webInterface.getNotifications().getNotifications(), currentSone.orNull());
94                 Collections.sort(notifications, Notification.CREATED_TIME_SORTER);
95                 /* load new posts. */
96                 Collection<Post> newPosts = webInterface.getNewPosts();
97                 if (currentSone.isPresent()) {
98                         newPosts = Collections2.filter(newPosts, new Predicate<Post>() {
99
100                                 @Override
101                                 public boolean apply(Post post) {
102                                         return ListNotificationFilters.isPostVisible(currentSone.get(), post);
103                                 }
104
105                         });
106                 }
107                 ArrayNode jsonPosts = new ArrayNode(instance);
108                 for (Post post : newPosts) {
109                         ObjectNode jsonPost = new ObjectNode(instance);
110                         jsonPost.put("id", post.getId());
111                         jsonPost.put("sone", post.getSone().getId());
112                         jsonPost.put("recipient", post.getRecipientId().orNull());
113                         jsonPost.put("time", post.getTime());
114                         jsonPosts.add(jsonPost);
115                 }
116                 /* load new replies. */
117                 Collection<PostReply> newReplies = webInterface.getNewReplies();
118                 if (currentSone.isPresent()) {
119                         newReplies = Collections2.filter(newReplies, new Predicate<PostReply>() {
120
121                                 @Override
122                                 public boolean apply(PostReply reply) {
123                                         return ListNotificationFilters.isReplyVisible(currentSone.get(), reply);
124                                 }
125
126                         });
127                 }
128                 /* remove replies to unknown posts. */
129                 newReplies = Collections2.filter(newReplies, PostReply.HAS_POST_FILTER);
130                 ArrayNode jsonReplies = new ArrayNode(instance);
131                 for (PostReply reply : newReplies) {
132                         ObjectNode jsonReply = new ObjectNode(instance);
133                         jsonReply.put("id", reply.getId());
134                         jsonReply.put("sone", reply.getSone().getId());
135                         jsonReply.put("post", reply.getPostId());
136                         jsonReply.put("postSone", reply.getPost().get().getSone().getId());
137                         jsonReplies.add(jsonReply);
138                 }
139                 return createSuccessJsonObject().put("loggedIn", currentSone.isPresent()).put("options", createJsonOptions(currentSone)).put("sones", jsonSones).put("notificationHash", notifications.hashCode()).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
140         }
141
142         /**
143          * {@inheritDoc}
144          */
145         @Override
146         protected boolean needsFormPassword() {
147                 return false;
148         }
149
150         /**
151          * {@inheritDoc}
152          */
153         @Override
154         protected boolean requiresLogin() {
155                 return false;
156         }
157
158         //
159         // PRIVATE METHODS
160         //
161
162         /**
163          * Creates a JSON object from the given Sone.
164          *
165          * @param sone
166          *            The Sone to convert to a JSON object
167          * @return The JSON representation of the given Sone
168          */
169         private JsonNode createJsonSone(Sone sone) {
170                 ObjectNode jsonSone = new ObjectNode(instance);
171                 jsonSone.put("id", sone.getId());
172                 jsonSone.put("name", SoneAccessor.getNiceName(sone));
173                 jsonSone.put("local", sone.getInsertUri() != null);
174                 jsonSone.put("status", sone.getStatus().name());
175                 jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone));
176                 jsonSone.put("locked", webInterface.getCore().isLocked(sone));
177                 jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0);
178                 synchronized (dateFormat) {
179                         jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime())));
180                 }
181                 jsonSone.put("lastUpdatedText", GetTimesAjaxPage.getTime(webInterface, sone.getTime()).getText());
182                 return jsonSone;
183         }
184
185         /**
186          * Creates a JSON object that contains all options that are currently in
187          * effect for the given Sone (or overall, if the given Sone is {@code null}
188          * ).
189          *
190          * @param currentSone
191          *            The current Sone (may be {@code null})
192          * @return The current options
193          */
194         private static JsonNode createJsonOptions(Optional<Sone> currentSone) {
195                 ObjectNode options = new ObjectNode(instance);
196                 if (currentSone.isPresent()) {
197                         options.put("ShowNotification/NewSones", currentSone.get().getOptions().isShowNewSoneNotifications());
198                         options.put("ShowNotification/NewPosts", currentSone.get().getOptions().isShowNewPostNotifications());
199                         options.put("ShowNotification/NewReplies", currentSone.get().getOptions().isShowNewReplyNotifications());
200                 }
201                 return options;
202         }
203
204 }