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