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