Change the way notifications are handled.
[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.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.Reply;
34 import net.pterodactylus.sone.data.Sone;
35 import net.pterodactylus.sone.notify.ListNotification;
36 import net.pterodactylus.sone.notify.ListNotificationFilters;
37 import net.pterodactylus.sone.template.SoneAccessor;
38 import net.pterodactylus.sone.web.WebInterface;
39 import net.pterodactylus.util.filter.Filter;
40 import net.pterodactylus.util.filter.Filters;
41 import net.pterodactylus.util.json.JsonArray;
42 import net.pterodactylus.util.json.JsonObject;
43 import net.pterodactylus.util.notify.Notification;
44 import net.pterodactylus.util.notify.TemplateNotification;
45 import net.pterodactylus.util.template.TemplateContext;
46
47 /**
48  * The “get status” AJAX handler returns all information that is necessary to
49  * update the web interface in real-time.
50  *
51  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52  */
53 public class GetStatusAjaxPage extends JsonPage {
54
55         /** Date formatter. */
56         private static final DateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy, HH:mm:ss");
57
58         /**
59          * Creates a new “get status” AJAX handler.
60          *
61          * @param webInterface
62          *            The Sone web interface
63          */
64         public GetStatusAjaxPage(WebInterface webInterface) {
65                 super("getStatus.ajax", webInterface);
66         }
67
68         /**
69          * {@inheritDoc}
70          */
71         @Override
72         protected JsonObject createJsonObject(Request request) {
73                 final Sone currentSone = getCurrentSone(request.getToadletContext(), false);
74                 /* load Sones. */
75                 boolean loadAllSones = Boolean.parseBoolean(request.getHttpRequest().getParam("loadAllSones", "true"));
76                 Set<Sone> sones = new HashSet<Sone>(Collections.singleton(getCurrentSone(request.getToadletContext(), false)));
77                 if (loadAllSones) {
78                         sones.addAll(webInterface.getCore().getSones());
79                 }
80                 JsonArray jsonSones = new JsonArray();
81                 for (Sone sone : sones) {
82                         if (sone == null) {
83                                 continue;
84                         }
85                         JsonObject jsonSone = createJsonSone(sone);
86                         jsonSones.add(jsonSone);
87                 }
88                 /* load notifications. */
89                 List<Notification> notifications = ListNotificationFilters.filterNotifications(new ArrayList<Notification>(webInterface.getNotifications().getNotifications()), currentSone);
90                 Collections.sort(notifications, Notification.LAST_UPDATED_TIME_SORTER);
91                 JsonArray jsonNotifications = new JsonArray();
92                 for (Notification notification : notifications) {
93                         jsonNotifications.add(createJsonNotification(notification));
94                 }
95                 /* load new posts. */
96                 Set<Post> newPosts = webInterface.getNewPosts();
97                 if (currentSone != null) {
98                         newPosts = Filters.filteredSet(newPosts, new Filter<Post>() {
99
100                                 @Override
101                                 public boolean filterObject(Post post) {
102                                         return currentSone.hasFriend(post.getSone().getId()) || currentSone.equals(post.getSone());
103                                 }
104
105                         });
106                 }
107                 JsonArray jsonPosts = new JsonArray();
108                 for (Post post : newPosts) {
109                         JsonObject jsonPost = new JsonObject();
110                         jsonPost.put("id", post.getId());
111                         jsonPost.put("sone", post.getSone().getId());
112                         jsonPost.put("recipient", (post.getRecipient() != null) ? post.getRecipient().getId() : null);
113                         jsonPost.put("time", post.getTime());
114                         jsonPosts.add(jsonPost);
115                 }
116                 /* load new replies. */
117                 Set<Reply> newReplies = webInterface.getNewReplies();
118                 if (currentSone != null) {
119                         newReplies = Filters.filteredSet(newReplies, new Filter<Reply>() {
120
121                                 @Override
122                                 public boolean filterObject(Reply reply) {
123                                         return currentSone.hasFriend(reply.getPost().getSone().getId()) || currentSone.equals(reply.getPost().getSone());
124                                 }
125
126                         });
127                 }
128                 JsonArray jsonReplies = new JsonArray();
129                 for (Reply reply : newReplies) {
130                         JsonObject jsonReply = new JsonObject();
131                         jsonReply.put("id", reply.getId());
132                         jsonReply.put("sone", reply.getSone().getId());
133                         jsonReply.put("post", reply.getPost().getId());
134                         jsonReply.put("postSone", reply.getPost().getSone().getId());
135                         jsonReplies.add(jsonReply);
136                 }
137                 return createSuccessJsonObject().put("sones", jsonSones).put("notifications", jsonNotifications).put("newPosts", jsonPosts).put("newReplies", jsonReplies);
138         }
139
140         /**
141          * {@inheritDoc}
142          */
143         @Override
144         protected boolean needsFormPassword() {
145                 return false;
146         }
147
148         /**
149          * {@inheritDoc}
150          */
151         @Override
152         protected boolean requiresLogin() {
153                 return false;
154         }
155
156         //
157         // PRIVATE METHODS
158         //
159
160         /**
161          * Creates a JSON object from the given Sone.
162          *
163          * @param sone
164          *            The Sone to convert to a JSON object
165          * @return The JSON representation of the given Sone
166          */
167         private JsonObject createJsonSone(Sone sone) {
168                 JsonObject jsonSone = new JsonObject();
169                 jsonSone.put("id", sone.getId());
170                 jsonSone.put("name", SoneAccessor.getNiceName(sone));
171                 jsonSone.put("local", sone.getInsertUri() != null);
172                 jsonSone.put("status", webInterface.getCore().getSoneStatus(sone).name());
173                 jsonSone.put("modified", webInterface.getCore().isModifiedSone(sone));
174                 jsonSone.put("locked", webInterface.getCore().isLocked(sone));
175                 jsonSone.put("lastUpdatedUnknown", sone.getTime() == 0);
176                 synchronized (dateFormat) {
177                         jsonSone.put("lastUpdated", dateFormat.format(new Date(sone.getTime())));
178                 }
179                 jsonSone.put("age", (System.currentTimeMillis() - sone.getTime()) / 1000);
180                 return jsonSone;
181         }
182
183         /**
184          * Creates a JSON object from the given notification.
185          *
186          * @param notification
187          *            The notification to create a JSON object
188          * @return The JSON object
189          */
190         private JsonObject createJsonNotification(Notification notification) {
191                 JsonObject jsonNotification = new JsonObject();
192                 jsonNotification.put("id", notification.getId());
193                 StringWriter notificationWriter = new StringWriter();
194                 try {
195                         if (notification instanceof TemplateNotification) {
196                                 TemplateContext templateContext = webInterface.getTemplateContextFactory().createTemplateContext().mergeContext(((TemplateNotification) notification).getTemplateContext());
197                                 templateContext.set("notification", notification);
198                                 ((TemplateNotification) notification).render(templateContext, notificationWriter);
199                         } else {
200                                 notification.render(notificationWriter);
201                         }
202                 } catch (IOException ioe1) {
203                         /* StringWriter never throws, ignore. */
204                 }
205                 jsonNotification.put("text", notificationWriter.toString());
206                 jsonNotification.put("createdTime", notification.getCreatedTime());
207                 jsonNotification.put("lastUpdatedTime", notification.getLastUpdatedTime());
208                 jsonNotification.put("dismissable", notification.isDismissable());
209                 return jsonNotification;
210         }
211
212 }