Add Sone insert events to core listener.
[Sone.git] / src / main / java / net / pterodactylus / sone / web / WebInterface.java
1 /*
2  * Sone - WebInterface.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;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.io.Reader;
24 import java.io.StringReader;
25 import java.io.UnsupportedEncodingException;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.UUID;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import net.pterodactylus.sone.core.Core;
39 import net.pterodactylus.sone.core.CoreListener;
40 import net.pterodactylus.sone.data.Post;
41 import net.pterodactylus.sone.data.Reply;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.freenet.L10nFilter;
44 import net.pterodactylus.sone.freenet.wot.Identity;
45 import net.pterodactylus.sone.freenet.wot.Trust;
46 import net.pterodactylus.sone.main.SonePlugin;
47 import net.pterodactylus.sone.notify.ListNotification;
48 import net.pterodactylus.sone.template.CollectionAccessor;
49 import net.pterodactylus.sone.template.CssClassNameFilter;
50 import net.pterodactylus.sone.template.HttpRequestAccessor;
51 import net.pterodactylus.sone.template.IdentityAccessor;
52 import net.pterodactylus.sone.template.JavascriptFilter;
53 import net.pterodactylus.sone.template.ParserFilter;
54 import net.pterodactylus.sone.template.PostAccessor;
55 import net.pterodactylus.sone.template.ReplyAccessor;
56 import net.pterodactylus.sone.template.ReplyGroupFilter;
57 import net.pterodactylus.sone.template.RequestChangeFilter;
58 import net.pterodactylus.sone.template.SoneAccessor;
59 import net.pterodactylus.sone.template.SubstringFilter;
60 import net.pterodactylus.sone.template.TrustAccessor;
61 import net.pterodactylus.sone.template.UnknownDateFilter;
62 import net.pterodactylus.sone.text.Part;
63 import net.pterodactylus.sone.text.SonePart;
64 import net.pterodactylus.sone.text.SoneTextParser;
65 import net.pterodactylus.sone.web.ajax.BookmarkAjaxPage;
66 import net.pterodactylus.sone.web.ajax.CreatePostAjaxPage;
67 import net.pterodactylus.sone.web.ajax.CreateReplyAjaxPage;
68 import net.pterodactylus.sone.web.ajax.DeletePostAjaxPage;
69 import net.pterodactylus.sone.web.ajax.DeleteProfileFieldAjaxPage;
70 import net.pterodactylus.sone.web.ajax.DeleteReplyAjaxPage;
71 import net.pterodactylus.sone.web.ajax.DismissNotificationAjaxPage;
72 import net.pterodactylus.sone.web.ajax.DistrustAjaxPage;
73 import net.pterodactylus.sone.web.ajax.EditProfileFieldAjaxPage;
74 import net.pterodactylus.sone.web.ajax.FollowSoneAjaxPage;
75 import net.pterodactylus.sone.web.ajax.GetLikesAjaxPage;
76 import net.pterodactylus.sone.web.ajax.GetNotificationAjaxPage;
77 import net.pterodactylus.sone.web.ajax.GetPostAjaxPage;
78 import net.pterodactylus.sone.web.ajax.GetReplyAjaxPage;
79 import net.pterodactylus.sone.web.ajax.GetStatusAjaxPage;
80 import net.pterodactylus.sone.web.ajax.GetTimesAjaxPage;
81 import net.pterodactylus.sone.web.ajax.GetTranslationPage;
82 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
83 import net.pterodactylus.sone.web.ajax.LockSoneAjaxPage;
84 import net.pterodactylus.sone.web.ajax.MarkAsKnownAjaxPage;
85 import net.pterodactylus.sone.web.ajax.MoveProfileFieldAjaxPage;
86 import net.pterodactylus.sone.web.ajax.TrustAjaxPage;
87 import net.pterodactylus.sone.web.ajax.UnbookmarkAjaxPage;
88 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
89 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
90 import net.pterodactylus.sone.web.ajax.UnlockSoneAjaxPage;
91 import net.pterodactylus.sone.web.ajax.UntrustAjaxPage;
92 import net.pterodactylus.sone.web.page.PageToadlet;
93 import net.pterodactylus.sone.web.page.PageToadletFactory;
94 import net.pterodactylus.sone.web.page.RedirectPage;
95 import net.pterodactylus.sone.web.page.StaticPage;
96 import net.pterodactylus.sone.web.page.TemplatePage;
97 import net.pterodactylus.util.cache.Cache;
98 import net.pterodactylus.util.cache.CacheException;
99 import net.pterodactylus.util.cache.CacheItem;
100 import net.pterodactylus.util.cache.DefaultCacheItem;
101 import net.pterodactylus.util.cache.MemoryCache;
102 import net.pterodactylus.util.cache.ValueRetriever;
103 import net.pterodactylus.util.collection.SetBuilder;
104 import net.pterodactylus.util.filter.Filters;
105 import net.pterodactylus.util.logging.Logging;
106 import net.pterodactylus.util.notify.Notification;
107 import net.pterodactylus.util.notify.NotificationManager;
108 import net.pterodactylus.util.notify.TemplateNotification;
109 import net.pterodactylus.util.template.CollectionSortFilter;
110 import net.pterodactylus.util.template.ContainsFilter;
111 import net.pterodactylus.util.template.DateFilter;
112 import net.pterodactylus.util.template.FormatFilter;
113 import net.pterodactylus.util.template.HtmlFilter;
114 import net.pterodactylus.util.template.MatchFilter;
115 import net.pterodactylus.util.template.Provider;
116 import net.pterodactylus.util.template.ReflectionAccessor;
117 import net.pterodactylus.util.template.ReplaceFilter;
118 import net.pterodactylus.util.template.StoreFilter;
119 import net.pterodactylus.util.template.Template;
120 import net.pterodactylus.util.template.TemplateContext;
121 import net.pterodactylus.util.template.TemplateContextFactory;
122 import net.pterodactylus.util.template.TemplateException;
123 import net.pterodactylus.util.template.TemplateParser;
124 import net.pterodactylus.util.template.XmlFilter;
125 import net.pterodactylus.util.thread.Ticker;
126 import net.pterodactylus.util.version.Version;
127 import freenet.clients.http.SessionManager;
128 import freenet.clients.http.SessionManager.Session;
129 import freenet.clients.http.ToadletContainer;
130 import freenet.clients.http.ToadletContext;
131 import freenet.l10n.BaseL10n;
132 import freenet.support.api.HTTPRequest;
133
134 /**
135  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
136  * references to l10n helpers.
137  *
138  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
139  */
140 public class WebInterface implements CoreListener {
141
142         /** The logger. */
143         private static final Logger logger = Logging.getLogger(WebInterface.class);
144
145         /** The notification manager. */
146         private final NotificationManager notificationManager = new NotificationManager();
147
148         /** The Sone plugin. */
149         private final SonePlugin sonePlugin;
150
151         /** The registered toadlets. */
152         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
153
154         /** The form password. */
155         private final String formPassword;
156
157         /** The template context factory. */
158         private final TemplateContextFactory templateContextFactory;
159
160         /** The Sone text parser. */
161         private final SoneTextParser soneTextParser;
162
163         /** The “new Sone” notification. */
164         private final ListNotification<Sone> newSoneNotification;
165
166         /** The “new post” notification. */
167         private final ListNotification<Post> newPostNotification;
168
169         /** The “new reply” notification. */
170         private final ListNotification<Reply> newReplyNotification;
171
172         /** The invisible “local post” notification. */
173         private final ListNotification<Post> localPostNotification;
174
175         /** The invisible “local reply” notification. */
176         private final ListNotification<Reply> localReplyNotification;
177
178         /** The “you have been mentioned” notification. */
179         private final ListNotification<Post> mentionNotification;
180
181         /** The “rescuing Sone” notification. */
182         private final ListNotification<Sone> rescuingSonesNotification;
183
184         /** The “Sone rescued” notification. */
185         private final ListNotification<Sone> sonesRescuedNotification;
186
187         /** Notifications for sone inserts. */
188         private final Map<Sone, TemplateNotification> soneInsertNotifications = new HashMap<Sone, TemplateNotification>();
189
190         /** Sone locked notification ticker objects. */
191         private final Map<Sone, Object> lockedSonesTickerObjects = Collections.synchronizedMap(new HashMap<Sone, Object>());
192
193         /** The “Sone locked” notification. */
194         private final ListNotification<Sone> lockedSonesNotification;
195
196         /** The “new version” notification. */
197         private final TemplateNotification newVersionNotification;
198
199         /**
200          * Creates a new web interface.
201          *
202          * @param sonePlugin
203          *            The Sone plugin
204          */
205         @SuppressWarnings("synthetic-access")
206         public WebInterface(SonePlugin sonePlugin) {
207                 this.sonePlugin = sonePlugin;
208                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
209                 soneTextParser = new SoneTextParser(getCore(), getCore());
210
211                 templateContextFactory = new TemplateContextFactory();
212                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
213                 templateContextFactory.addAccessor(Collection.class, new CollectionAccessor());
214                 templateContextFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
215                 templateContextFactory.addAccessor(Post.class, new PostAccessor(getCore()));
216                 templateContextFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
217                 templateContextFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
218                 templateContextFactory.addAccessor(Trust.class, new TrustAccessor());
219                 templateContextFactory.addAccessor(HTTPRequest.class, new HttpRequestAccessor());
220                 templateContextFactory.addFilter("date", new DateFilter());
221                 templateContextFactory.addFilter("html", new HtmlFilter());
222                 templateContextFactory.addFilter("replace", new ReplaceFilter());
223                 templateContextFactory.addFilter("store", new StoreFilter());
224                 templateContextFactory.addFilter("l10n", new L10nFilter(getL10n()));
225                 templateContextFactory.addFilter("substring", new SubstringFilter());
226                 templateContextFactory.addFilter("xml", new XmlFilter());
227                 templateContextFactory.addFilter("change", new RequestChangeFilter());
228                 templateContextFactory.addFilter("match", new MatchFilter());
229                 templateContextFactory.addFilter("css", new CssClassNameFilter());
230                 templateContextFactory.addFilter("js", new JavascriptFilter());
231                 templateContextFactory.addFilter("parse", new ParserFilter(getCore(), templateContextFactory, soneTextParser));
232                 templateContextFactory.addFilter("unknown", new UnknownDateFilter(getL10n(), "View.Sone.Text.UnknownDate"));
233                 templateContextFactory.addFilter("format", new FormatFilter());
234                 templateContextFactory.addFilter("sort", new CollectionSortFilter());
235                 templateContextFactory.addFilter("replyGroup", new ReplyGroupFilter());
236                 templateContextFactory.addFilter("in", new ContainsFilter());
237                 templateContextFactory.addProvider(Provider.TEMPLATE_CONTEXT_PROVIDER);
238                 templateContextFactory.addProvider(new ClassPathTemplateProvider());
239                 templateContextFactory.addTemplateObject("webInterface", this);
240                 templateContextFactory.addTemplateObject("formPassword", formPassword);
241
242                 /* create notifications. */
243                 Template newSoneNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newSoneNotification.html"));
244                 newSoneNotification = new ListNotification<Sone>("new-sone-notification", "sones", newSoneNotificationTemplate, false);
245
246                 Template newPostNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newPostNotification.html"));
247                 newPostNotification = new ListNotification<Post>("new-post-notification", "posts", newPostNotificationTemplate, false);
248
249                 Template localPostNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newPostNotification.html"));
250                 localPostNotification = new ListNotification<Post>("local-post-notification", "posts", localPostNotificationTemplate, false);
251
252                 Template newReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
253                 newReplyNotification = new ListNotification<Reply>("new-reply-notification", "replies", newReplyNotificationTemplate, false);
254
255                 Template localReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
256                 localReplyNotification = new ListNotification<Reply>("local-reply-notification", "replies", localReplyNotificationTemplate, false);
257
258                 Template mentionNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/mentionNotification.html"));
259                 mentionNotification = new ListNotification<Post>("mention-notification", "posts", mentionNotificationTemplate, false);
260
261                 Template rescuingSonesTemplate = TemplateParser.parse(createReader("/templates/notify/rescuingSonesNotification.html"));
262                 rescuingSonesNotification = new ListNotification<Sone>("sones-being-rescued-notification", "sones", rescuingSonesTemplate);
263
264                 Template sonesRescuedTemplate = TemplateParser.parse(createReader("/templates/notify/sonesRescuedNotification.html"));
265                 sonesRescuedNotification = new ListNotification<Sone>("sones-rescued-notification", "sones", sonesRescuedTemplate);
266
267                 Template lockedSonesTemplate = TemplateParser.parse(createReader("/templates/notify/lockedSonesNotification.html"));
268                 lockedSonesNotification = new ListNotification<Sone>("sones-locked-notification", "sones", lockedSonesTemplate);
269
270                 Template newVersionTemplate = TemplateParser.parse(createReader("/templates/notify/newVersionNotification.html"));
271                 newVersionNotification = new TemplateNotification("new-version-notification", newVersionTemplate);
272         }
273
274         //
275         // ACCESSORS
276         //
277
278         /**
279          * Returns the Sone core used by the Sone plugin.
280          *
281          * @return The Sone core
282          */
283         public Core getCore() {
284                 return sonePlugin.core();
285         }
286
287         /**
288          * Returns the template context factory of the web interface.
289          *
290          * @return The template context factory
291          */
292         public TemplateContextFactory getTemplateContextFactory() {
293                 return templateContextFactory;
294         }
295
296         /**
297          * Returns the current session, creating a new session if there is no
298          * current session.
299          *
300          * @param toadletContenxt
301          *            The toadlet context
302          * @return The current session, or {@code null} if there is no current
303          *         session
304          */
305         public Session getCurrentSession(ToadletContext toadletContenxt) {
306                 return getCurrentSession(toadletContenxt, true);
307         }
308
309         /**
310          * Returns the current session, creating a new session if there is no
311          * current session and {@code create} is {@code true}.
312          *
313          * @param toadletContenxt
314          *            The toadlet context
315          * @param create
316          *            {@code true} to create a new session if there is no current
317          *            session, {@code false} otherwise
318          * @return The current session, or {@code null} if there is no current
319          *         session
320          */
321         public Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
322                 Session session = getSessionManager().useSession(toadletContenxt);
323                 if (create && (session == null)) {
324                         session = getSessionManager().createSession(UUID.randomUUID().toString(), toadletContenxt);
325                 }
326                 return session;
327         }
328
329         /**
330          * Returns the currently logged in Sone.
331          *
332          * @param toadletContext
333          *            The toadlet context
334          * @return The currently logged in Sone, or {@code null} if no Sone is
335          *         currently logged in
336          */
337         public Sone getCurrentSone(ToadletContext toadletContext) {
338                 return getCurrentSone(toadletContext, true);
339         }
340
341         /**
342          * Returns the currently logged in Sone.
343          *
344          * @param toadletContext
345          *            The toadlet context
346          * @param create
347          *            {@code true} to create a new session if no session exists,
348          *            {@code false} to not create a new session
349          * @return The currently logged in Sone, or {@code null} if no Sone is
350          *         currently logged in
351          */
352         public Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
353                 Set<Sone> localSones = getCore().getLocalSones();
354                 if (localSones.size() == 1) {
355                         return localSones.iterator().next();
356                 }
357                 return getCurrentSone(getCurrentSession(toadletContext, create));
358         }
359
360         /**
361          * Returns the currently logged in Sone.
362          *
363          * @param session
364          *            The session
365          * @return The currently logged in Sone, or {@code null} if no Sone is
366          *         currently logged in
367          */
368         public Sone getCurrentSone(Session session) {
369                 if (session == null) {
370                         return null;
371                 }
372                 String soneId = (String) session.getAttribute("Sone.CurrentSone");
373                 if (soneId == null) {
374                         return null;
375                 }
376                 return getCore().getLocalSone(soneId, false);
377         }
378
379         /**
380          * Sets the currently logged in Sone.
381          *
382          * @param toadletContext
383          *            The toadlet context
384          * @param sone
385          *            The Sone to set as currently logged in
386          */
387         public void setCurrentSone(ToadletContext toadletContext, Sone sone) {
388                 Session session = getCurrentSession(toadletContext);
389                 if (sone == null) {
390                         session.removeAttribute("Sone.CurrentSone");
391                 } else {
392                         session.setAttribute("Sone.CurrentSone", sone.getId());
393                 }
394         }
395
396         /**
397          * Returns the notification manager.
398          *
399          * @return The notification manager
400          */
401         public NotificationManager getNotifications() {
402                 return notificationManager;
403         }
404
405         /**
406          * Returns the l10n helper of the node.
407          *
408          * @return The node’s l10n helper
409          */
410         public BaseL10n getL10n() {
411                 return sonePlugin.l10n().getBase();
412         }
413
414         /**
415          * Returns the session manager of the node.
416          *
417          * @return The node’s session manager
418          */
419         public SessionManager getSessionManager() {
420                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
421         }
422
423         /**
424          * Returns the node’s form password.
425          *
426          * @return The form password
427          */
428         public String getFormPassword() {
429                 return formPassword;
430         }
431
432         /**
433          * Returns the posts that have been announced as new in the
434          * {@link #newPostNotification}.
435          *
436          * @return The new posts
437          */
438         public Set<Post> getNewPosts() {
439                 return new SetBuilder<Post>().addAll(newPostNotification.getElements()).addAll(localPostNotification.getElements()).get();
440         }
441
442         /**
443          * Returns the replies that have been announced as new in the
444          * {@link #newReplyNotification}.
445          *
446          * @return The new replies
447          */
448         public Set<Reply> getNewReplies() {
449                 return new SetBuilder<Reply>().addAll(newReplyNotification.getElements()).addAll(localReplyNotification.getElements()).get();
450         }
451
452         /**
453          * Sets whether the current start of the plugin is the first start. It is
454          * considered a first start if the configuration file does not exist.
455          *
456          * @param firstStart
457          *            {@code true} if no configuration file existed when Sone was
458          *            loaded, {@code false} otherwise
459          */
460         public void setFirstStart(boolean firstStart) {
461                 if (firstStart) {
462                         Template firstStartNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/firstStartNotification.html"));
463                         Notification firstStartNotification = new TemplateNotification("first-start-notification", firstStartNotificationTemplate);
464                         notificationManager.addNotification(firstStartNotification);
465                 }
466         }
467
468         /**
469          * Sets whether Sone was started with a fresh configuration file.
470          *
471          * @param newConfig
472          *            {@code true} if Sone was started with a fresh configuration,
473          *            {@code false} if the existing configuration could be read
474          */
475         public void setNewConfig(boolean newConfig) {
476                 if (newConfig && !hasFirstStartNotification()) {
477                         Template configNotReadNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/configNotReadNotification.html"));
478                         Notification configNotReadNotification = new TemplateNotification("config-not-read-notification", configNotReadNotificationTemplate);
479                         notificationManager.addNotification(configNotReadNotification);
480                 }
481         }
482
483         //
484         // PRIVATE ACCESSORS
485         //
486
487         /**
488          * Returns whether the first start notification is currently displayed.
489          *
490          * @return {@code true} if the first-start notification is currently
491          *         displayed, {@code false} otherwise
492          */
493         private boolean hasFirstStartNotification() {
494                 return notificationManager.getNotification("first-start-notification") != null;
495         }
496
497         //
498         // ACTIONS
499         //
500
501         /**
502          * Starts the web interface and registers all toadlets.
503          */
504         public void start() {
505                 registerToadlets();
506
507                 /* notification templates. */
508                 Template startupNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/startupNotification.html"));
509
510                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
511                 notificationManager.addNotification(startupNotification);
512
513                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (120 * 1000), new Runnable() {
514
515                         @Override
516                         public void run() {
517                                 startupNotification.dismiss();
518                         }
519                 }, "Sone Startup Notification Remover");
520
521                 Template wotMissingNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/wotMissingNotification.html"));
522                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
523                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), new Runnable() {
524
525                         @Override
526                         @SuppressWarnings("synthetic-access")
527                         public void run() {
528                                 if (getCore().getIdentityManager().isConnected()) {
529                                         wotMissingNotification.dismiss();
530                                 } else {
531                                         notificationManager.addNotification(wotMissingNotification);
532                                 }
533                                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), this, "Sone WoT Connector Checker");
534                         }
535
536                 }, "Sone WoT Connector Checker");
537         }
538
539         /**
540          * Stops the web interface and unregisters all toadlets.
541          */
542         public void stop() {
543                 unregisterToadlets();
544                 Ticker.getInstance().stop();
545         }
546
547         //
548         // PRIVATE METHODS
549         //
550
551         /**
552          * Register all toadlets.
553          */
554         private void registerToadlets() {
555                 Template emptyTemplate = TemplateParser.parse(new StringReader(""));
556                 Template loginTemplate = TemplateParser.parse(createReader("/templates/login.html"));
557                 Template indexTemplate = TemplateParser.parse(createReader("/templates/index.html"));
558                 Template knownSonesTemplate = TemplateParser.parse(createReader("/templates/knownSones.html"));
559                 Template createSoneTemplate = TemplateParser.parse(createReader("/templates/createSone.html"));
560                 Template createPostTemplate = TemplateParser.parse(createReader("/templates/createPost.html"));
561                 Template createReplyTemplate = TemplateParser.parse(createReader("/templates/createReply.html"));
562                 Template bookmarksTemplate = TemplateParser.parse(createReader("/templates/bookmarks.html"));
563                 Template searchTemplate = TemplateParser.parse(createReader("/templates/search.html"));
564                 Template editProfileTemplate = TemplateParser.parse(createReader("/templates/editProfile.html"));
565                 Template editProfileFieldTemplate = TemplateParser.parse(createReader("/templates/editProfileField.html"));
566                 Template deleteProfileFieldTemplate = TemplateParser.parse(createReader("/templates/deleteProfileField.html"));
567                 Template viewSoneTemplate = TemplateParser.parse(createReader("/templates/viewSone.html"));
568                 Template viewPostTemplate = TemplateParser.parse(createReader("/templates/viewPost.html"));
569                 Template deletePostTemplate = TemplateParser.parse(createReader("/templates/deletePost.html"));
570                 Template deleteReplyTemplate = TemplateParser.parse(createReader("/templates/deleteReply.html"));
571                 Template deleteSoneTemplate = TemplateParser.parse(createReader("/templates/deleteSone.html"));
572                 Template noPermissionTemplate = TemplateParser.parse(createReader("/templates/noPermission.html"));
573                 Template optionsTemplate = TemplateParser.parse(createReader("/templates/options.html"));
574                 Template rescueTemplate = TemplateParser.parse(createReader("/templates/rescue.html"));
575                 Template aboutTemplate = TemplateParser.parse(createReader("/templates/about.html"));
576                 Template invalidTemplate = TemplateParser.parse(createReader("/templates/invalid.html"));
577                 Template postTemplate = TemplateParser.parse(createReader("/templates/include/viewPost.html"));
578                 Template replyTemplate = TemplateParser.parse(createReader("/templates/include/viewReply.html"));
579                 Template openSearchTemplate = TemplateParser.parse(createReader("/templates/xml/OpenSearch.xml"));
580
581                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
582                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RedirectPage("", "index.html")));
583                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
584                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
585                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
586                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
587                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldPage(editProfileFieldTemplate, this)));
588                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldPage(deleteProfileFieldTemplate, this)));
589                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
590                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
591                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
592                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
593                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(emptyTemplate, this)));
594                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(emptyTemplate, this)));
595                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
596                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
597                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(emptyTemplate, this)));
598                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(emptyTemplate, this)));
599                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(emptyTemplate, this)));
600                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(emptyTemplate, this)));
601                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustPage(emptyTemplate, this)));
602                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustPage(emptyTemplate, this)));
603                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustPage(emptyTemplate, this)));
604                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownPage(emptyTemplate, this)));
605                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkPage(emptyTemplate, this)));
606                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkPage(emptyTemplate, this)));
607                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarksPage(bookmarksTemplate, this), "Bookmarks"));
608                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SearchPage(searchTemplate, this)));
609                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
610                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
611                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(emptyTemplate, this), "Logout"));
612                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
613                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RescuePage(rescueTemplate, this), "Rescue"));
614                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, SonePlugin.VERSION), "About"));
615                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", noPermissionTemplate, "Page.NoPermission.Title", this)));
616                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationPage(emptyTemplate, this)));
617                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("invalid.html", invalidTemplate, "Page.Invalid.Title", this)));
618                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("css/", "/static/css/", "text/css")));
619                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("javascript/", "/static/javascript/", "text/javascript")));
620                 pageToadlets.add(pageToadletFactory.createPageToadlet(new StaticPage("images/", "/static/images/", "image/png")));
621                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TemplatePage("OpenSearch.xml", "application/opensearchdescription+xml", templateContextFactory, openSearchTemplate)));
622                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationPage(this)));
623                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetStatusAjaxPage(this)));
624                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetNotificationAjaxPage(this)));
625                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationAjaxPage(this)));
626                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostAjaxPage(this)));
627                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
628                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
629                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetPostAjaxPage(this, postTemplate)));
630                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTimesAjaxPage(this)));
631                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownAjaxPage(this)));
632                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
633                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
634                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSoneAjaxPage(this)));
635                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSoneAjaxPage(this)));
636                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
637                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
638                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustAjaxPage(this)));
639                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustAjaxPage(this)));
640                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustAjaxPage(this)));
641                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
642                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
643                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
644                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkAjaxPage(this)));
645                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkAjaxPage(this)));
646                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldAjaxPage(this)));
647                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldAjaxPage(this)));
648                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MoveProfileFieldAjaxPage(this)));
649
650                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
651                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Name", "Navigation.Menu.Tooltip", sonePlugin);
652                 for (PageToadlet toadlet : pageToadlets) {
653                         String menuName = toadlet.getMenuName();
654                         if (menuName != null) {
655                                 toadletContainer.register(toadlet, "Navigation.Menu.Name", toadlet.path(), true, "Navigation.Menu.Item." + menuName + ".Name", "Navigation.Menu.Item." + menuName + ".Tooltip", false, toadlet);
656                         } else {
657                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
658                         }
659                 }
660         }
661
662         /**
663          * Unregisters all toadlets.
664          */
665         private void unregisterToadlets() {
666                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
667                 for (PageToadlet pageToadlet : pageToadlets) {
668                         toadletContainer.unregister(pageToadlet);
669                 }
670                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Name");
671         }
672
673         /**
674          * Creates a {@link Reader} from the {@link InputStream} for the resource
675          * with the given name.
676          *
677          * @param resourceName
678          *            The name of the resource
679          * @return A {@link Reader} for the resource
680          */
681         private Reader createReader(String resourceName) {
682                 try {
683                         return new InputStreamReader(getClass().getResourceAsStream(resourceName), "UTF-8");
684                 } catch (UnsupportedEncodingException uee1) {
685                         return null;
686                 }
687         }
688
689         /**
690          * Returns all {@link Core#isLocalSone(Sone) local Sone}s that are
691          * referenced by {@link SonePart}s in the given text (after parsing it using
692          * {@link SoneTextParser}).
693          *
694          * @param text
695          *            The text to parse
696          * @return All mentioned local Sones
697          */
698         private Set<Sone> getMentionedSones(String text) {
699                 /* we need no context to find mentioned Sones. */
700                 Set<Sone> mentionedSones = new HashSet<Sone>();
701                 try {
702                         for (Part part : soneTextParser.parse(null, new StringReader(text))) {
703                                 if (part instanceof SonePart) {
704                                         mentionedSones.add(((SonePart) part).getSone());
705                                 }
706                         }
707                 } catch (IOException ioe1) {
708                         logger.log(Level.WARNING, "Could not parse post text: " + text, ioe1);
709                 }
710                 return Filters.filteredSet(mentionedSones, Sone.LOCAL_SONE_FILTER);
711         }
712
713         /**
714          * Returns the Sone insert notification for the given Sone. If no
715          * notification for the given Sone exists, a new notification is created and
716          * cached.
717          *
718          * @param sone
719          *            The Sone to get the insert notification for
720          * @return The Sone insert notification
721          */
722         private TemplateNotification getSoneInsertNotification(Sone sone) {
723                 synchronized (soneInsertNotifications) {
724                         TemplateNotification templateNotification = soneInsertNotifications.get(sone);
725                         if (templateNotification == null) {
726                                 templateNotification = new TemplateNotification(TemplateParser.parse(createReader("/templates/notify/soneInsertNotification.html")));
727                                 templateNotification.set("sone", sone);
728                                 soneInsertNotifications.put(sone, templateNotification);
729                         }
730                         return templateNotification;
731                 }
732         }
733
734         //
735         // CORELISTENER METHODS
736         //
737
738         /**
739          * {@inheritDoc}
740          */
741         @Override
742         public void rescuingSone(Sone sone) {
743                 rescuingSonesNotification.add(sone);
744                 notificationManager.addNotification(rescuingSonesNotification);
745         }
746
747         /**
748          * {@inheritDoc}
749          */
750         @Override
751         public void rescuedSone(Sone sone) {
752                 rescuingSonesNotification.remove(sone);
753                 sonesRescuedNotification.add(sone);
754                 notificationManager.addNotification(sonesRescuedNotification);
755         }
756
757         /**
758          * {@inheritDoc}
759          */
760         @Override
761         public void newSoneFound(Sone sone) {
762                 newSoneNotification.add(sone);
763                 if (!hasFirstStartNotification()) {
764                         notificationManager.addNotification(newSoneNotification);
765                 }
766         }
767
768         /**
769          * {@inheritDoc}
770          */
771         @Override
772         public void newPostFound(Post post) {
773                 boolean isLocal = getCore().isLocalSone(post.getSone());
774                 if (isLocal) {
775                         localPostNotification.add(post);
776                 } else {
777                         newPostNotification.add(post);
778                 }
779                 if (!hasFirstStartNotification()) {
780                         notificationManager.addNotification(isLocal ? localPostNotification : newPostNotification);
781                         if (!getMentionedSones(post.getText()).isEmpty() && !isLocal) {
782                                 mentionNotification.add(post);
783                                 notificationManager.addNotification(mentionNotification);
784                         }
785                 } else {
786                         getCore().markPostKnown(post);
787                 }
788         }
789
790         /**
791          * {@inheritDoc}
792          */
793         @Override
794         public void newReplyFound(Reply reply) {
795                 boolean isLocal = getCore().isLocalSone(reply.getSone());
796                 if (isLocal) {
797                         localReplyNotification.add(reply);
798                 } else {
799                         newReplyNotification.add(reply);
800                 }
801                 if (!hasFirstStartNotification()) {
802                         notificationManager.addNotification(isLocal ? localReplyNotification : newReplyNotification);
803                         if (!getMentionedSones(reply.getText()).isEmpty() && !isLocal) {
804                                 mentionNotification.add(reply.getPost());
805                                 notificationManager.addNotification(mentionNotification);
806                         }
807                 } else {
808                         getCore().markReplyKnown(reply);
809                 }
810         }
811
812         /**
813          * {@inheritDoc}
814          */
815         @Override
816         public void markSoneKnown(Sone sone) {
817                 newSoneNotification.remove(sone);
818         }
819
820         /**
821          * {@inheritDoc}
822          */
823         @Override
824         public void markPostKnown(Post post) {
825                 newPostNotification.remove(post);
826                 localPostNotification.remove(post);
827                 mentionNotification.remove(post);
828         }
829
830         /**
831          * {@inheritDoc}
832          */
833         @Override
834         public void markReplyKnown(Reply reply) {
835                 newReplyNotification.remove(reply);
836                 localReplyNotification.remove(reply);
837                 mentionNotification.remove(reply.getPost());
838         }
839
840         /**
841          * {@inheritDoc}
842          */
843         @Override
844         public void soneRemoved(Sone sone) {
845                 newSoneNotification.remove(sone);
846         }
847
848         /**
849          * {@inheritDoc}
850          */
851         @Override
852         public void postRemoved(Post post) {
853                 newPostNotification.remove(post);
854                 localPostNotification.remove(post);
855         }
856
857         /**
858          * {@inheritDoc}
859          */
860         @Override
861         public void replyRemoved(Reply reply) {
862                 newReplyNotification.remove(reply);
863                 localReplyNotification.remove(reply);
864         }
865
866         /**
867          * {@inheritDoc}
868          */
869         @Override
870         public void soneLocked(final Sone sone) {
871                 Object tickerObject = Ticker.getInstance().registerEvent(System.currentTimeMillis() + (5 * 60) * 1000, new Runnable() {
872
873                         @Override
874                         @SuppressWarnings("synthetic-access")
875                         public void run() {
876                                 lockedSonesNotification.add(sone);
877                                 lockedSonesTickerObjects.remove(sone);
878                                 notificationManager.addNotification(lockedSonesNotification);
879                         }
880                 }, "Sone Locked Notification");
881                 lockedSonesTickerObjects.put(sone, tickerObject);
882         }
883
884         /**
885          * {@inheritDoc}
886          */
887         @Override
888         public void soneUnlocked(Sone sone) {
889                 lockedSonesNotification.remove(sone);
890                 Ticker.getInstance().deregisterEvent(lockedSonesTickerObjects.remove(sone));
891         }
892
893         /**
894          * {@inheritDoc}
895          */
896         @Override
897         public void soneInserting(Sone sone) {
898                 TemplateNotification soneInsertNotification = getSoneInsertNotification(sone);
899                 soneInsertNotification.set("soneStatus", "inserting");
900                 notificationManager.addNotification(soneInsertNotification);
901         }
902
903         /**
904          * {@inheritDoc}
905          */
906         @Override
907         public void soneInserted(Sone sone, long insertDuration) {
908                 TemplateNotification soneInsertNotification = getSoneInsertNotification(sone);
909                 soneInsertNotification.set("soneStatus", "inserted");
910                 soneInsertNotification.set("insertDuration", insertDuration / 1000);
911                 notificationManager.addNotification(soneInsertNotification);
912         }
913
914         /**
915          * {@inheritDoc}
916          */
917         @Override
918         public void soneInsertAborted(Sone sone, Throwable cause) {
919                 notificationManager.addNotification(getSoneInsertNotification(sone).set("soneStatus", "insert-aborted").set("insert-error", cause));
920         }
921
922         /**
923          * {@inheritDoc}
924          */
925         @Override
926         public void updateFound(Version version, long releaseTime, long latestEdition) {
927                 newVersionNotification.getTemplateContext().set("latestVersion", version);
928                 newVersionNotification.getTemplateContext().set("latestEdition", latestEdition);
929                 newVersionNotification.getTemplateContext().set("releaseTime", releaseTime);
930                 notificationManager.addNotification(newVersionNotification);
931         }
932
933         /**
934          * Template provider implementation that uses
935          * {@link WebInterface#createReader(String)} to load templates for
936          * inclusion.
937          *
938          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
939          */
940         private class ClassPathTemplateProvider implements Provider {
941
942                 /** Cache for templates. */
943                 private final Cache<String, Template> templateCache = new MemoryCache<String, Template>(new ValueRetriever<String, Template>() {
944
945                         @Override
946                         @SuppressWarnings("synthetic-access")
947                         public CacheItem<Template> retrieve(String key) throws CacheException {
948                                 Template template = findTemplate(key);
949                                 if (template != null) {
950                                         return new DefaultCacheItem<Template>(template);
951                                 }
952                                 return null;
953                         }
954                 });
955
956                 /**
957                  * {@inheritDoc}
958                  */
959                 @Override
960                 @SuppressWarnings("synthetic-access")
961                 public Template getTemplate(TemplateContext templateContext, String templateName) {
962                         try {
963                                 return templateCache.get(templateName);
964                         } catch (CacheException ce1) {
965                                 logger.log(Level.WARNING, "Could not get template for " + templateName + "!", ce1);
966                                 return null;
967                         }
968                 }
969
970                 /**
971                  * Locates a template in the class path.
972                  *
973                  * @param templateName
974                  *            The name of the template to load
975                  * @return The loaded template, or {@code null} if no template could be
976                  *         found
977                  */
978                 @SuppressWarnings("synthetic-access")
979                 private Template findTemplate(String templateName) {
980                         Reader templateReader = createReader("/templates/" + templateName);
981                         if (templateReader == null) {
982                                 return null;
983                         }
984                         Template template = null;
985                         try {
986                                 template = TemplateParser.parse(templateReader);
987                         } catch (TemplateException te1) {
988                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
989                         }
990                         return template;
991                 }
992
993         }
994
995 }