Use different notifications for local elements.
[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.filter.Filters;
104 import net.pterodactylus.util.logging.Logging;
105 import net.pterodactylus.util.notify.Notification;
106 import net.pterodactylus.util.notify.NotificationManager;
107 import net.pterodactylus.util.notify.TemplateNotification;
108 import net.pterodactylus.util.template.CollectionSortFilter;
109 import net.pterodactylus.util.template.ContainsFilter;
110 import net.pterodactylus.util.template.DateFilter;
111 import net.pterodactylus.util.template.FormatFilter;
112 import net.pterodactylus.util.template.HtmlFilter;
113 import net.pterodactylus.util.template.MatchFilter;
114 import net.pterodactylus.util.template.Provider;
115 import net.pterodactylus.util.template.ReflectionAccessor;
116 import net.pterodactylus.util.template.ReplaceFilter;
117 import net.pterodactylus.util.template.StoreFilter;
118 import net.pterodactylus.util.template.Template;
119 import net.pterodactylus.util.template.TemplateContext;
120 import net.pterodactylus.util.template.TemplateContextFactory;
121 import net.pterodactylus.util.template.TemplateException;
122 import net.pterodactylus.util.template.TemplateParser;
123 import net.pterodactylus.util.template.XmlFilter;
124 import net.pterodactylus.util.thread.Ticker;
125 import net.pterodactylus.util.version.Version;
126 import freenet.clients.http.SessionManager;
127 import freenet.clients.http.SessionManager.Session;
128 import freenet.clients.http.ToadletContainer;
129 import freenet.clients.http.ToadletContext;
130 import freenet.l10n.BaseL10n;
131 import freenet.support.api.HTTPRequest;
132
133 /**
134  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
135  * references to l10n helpers.
136  *
137  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
138  */
139 public class WebInterface implements CoreListener {
140
141         /** The logger. */
142         private static final Logger logger = Logging.getLogger(WebInterface.class);
143
144         /** The notification manager. */
145         private final NotificationManager notificationManager = new NotificationManager();
146
147         /** The Sone plugin. */
148         private final SonePlugin sonePlugin;
149
150         /** The registered toadlets. */
151         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
152
153         /** The form password. */
154         private final String formPassword;
155
156         /** The template context factory. */
157         private final TemplateContextFactory templateContextFactory;
158
159         /** The Sone text parser. */
160         private final SoneTextParser soneTextParser;
161
162         /** The “new Sone” notification. */
163         private final ListNotification<Sone> newSoneNotification;
164
165         /** The “new post” notification. */
166         private final ListNotification<Post> newPostNotification;
167
168         /** The “new reply” notification. */
169         private final ListNotification<Reply> newReplyNotification;
170
171         /** The invisible “local post” notification. */
172         private final ListNotification<Post> localPostNotification;
173
174         /** The invisible “local reply” notification. */
175         private final ListNotification<Reply> localReplyNotification;
176
177         /** The “you have been mentioned” notification. */
178         private final ListNotification<Post> mentionNotification;
179
180         /** The “rescuing Sone” notification. */
181         private final ListNotification<Sone> rescuingSonesNotification;
182
183         /** The “Sone rescued” notification. */
184         private final ListNotification<Sone> sonesRescuedNotification;
185
186         /** Sone locked notification ticker objects. */
187         private final Map<Sone, Object> lockedSonesTickerObjects = Collections.synchronizedMap(new HashMap<Sone, Object>());
188
189         /** The “Sone locked” notification. */
190         private final ListNotification<Sone> lockedSonesNotification;
191
192         /** The “new version” notification. */
193         private final TemplateNotification newVersionNotification;
194
195         /**
196          * Creates a new web interface.
197          *
198          * @param sonePlugin
199          *            The Sone plugin
200          */
201         @SuppressWarnings("synthetic-access")
202         public WebInterface(SonePlugin sonePlugin) {
203                 this.sonePlugin = sonePlugin;
204                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
205                 soneTextParser = new SoneTextParser(getCore(), getCore());
206
207                 templateContextFactory = new TemplateContextFactory();
208                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
209                 templateContextFactory.addAccessor(Collection.class, new CollectionAccessor());
210                 templateContextFactory.addAccessor(Sone.class, new SoneAccessor(getCore()));
211                 templateContextFactory.addAccessor(Post.class, new PostAccessor(getCore()));
212                 templateContextFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
213                 templateContextFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
214                 templateContextFactory.addAccessor(Trust.class, new TrustAccessor());
215                 templateContextFactory.addAccessor(HTTPRequest.class, new HttpRequestAccessor());
216                 templateContextFactory.addFilter("date", new DateFilter());
217                 templateContextFactory.addFilter("html", new HtmlFilter());
218                 templateContextFactory.addFilter("replace", new ReplaceFilter());
219                 templateContextFactory.addFilter("store", new StoreFilter());
220                 templateContextFactory.addFilter("l10n", new L10nFilter(getL10n()));
221                 templateContextFactory.addFilter("substring", new SubstringFilter());
222                 templateContextFactory.addFilter("xml", new XmlFilter());
223                 templateContextFactory.addFilter("change", new RequestChangeFilter());
224                 templateContextFactory.addFilter("match", new MatchFilter());
225                 templateContextFactory.addFilter("css", new CssClassNameFilter());
226                 templateContextFactory.addFilter("js", new JavascriptFilter());
227                 templateContextFactory.addFilter("parse", new ParserFilter(getCore(), templateContextFactory, soneTextParser));
228                 templateContextFactory.addFilter("unknown", new UnknownDateFilter(getL10n(), "View.Sone.Text.UnknownDate"));
229                 templateContextFactory.addFilter("format", new FormatFilter());
230                 templateContextFactory.addFilter("sort", new CollectionSortFilter());
231                 templateContextFactory.addFilter("replyGroup", new ReplyGroupFilter());
232                 templateContextFactory.addFilter("in", new ContainsFilter());
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                 localPostNotification = new ListNotification<Post>("local-post-notification", "posts", newPostNotificationTemplate, false);
245
246                 Template newReplyNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/newReplyNotification.html"));
247                 newReplyNotification = new ListNotification<Reply>("new-reply-notification", "replies", newReplyNotificationTemplate, false);
248                 localReplyNotification = new ListNotification<Reply>("local-reply-notification", "replies", newReplyNotificationTemplate, false);
249
250                 Template mentionNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/mentionNotification.html"));
251                 mentionNotification = new ListNotification<Post>("mention-notification", "posts", mentionNotificationTemplate, false);
252
253                 Template rescuingSonesTemplate = TemplateParser.parse(createReader("/templates/notify/rescuingSonesNotification.html"));
254                 rescuingSonesNotification = new ListNotification<Sone>("sones-being-rescued-notification", "sones", rescuingSonesTemplate);
255
256                 Template sonesRescuedTemplate = TemplateParser.parse(createReader("/templates/notify/sonesRescuedNotification.html"));
257                 sonesRescuedNotification = new ListNotification<Sone>("sones-rescued-notification", "sones", sonesRescuedTemplate);
258
259                 Template lockedSonesTemplate = TemplateParser.parse(createReader("/templates/notify/lockedSonesNotification.html"));
260                 lockedSonesNotification = new ListNotification<Sone>("sones-locked-notification", "sones", lockedSonesTemplate);
261
262                 Template newVersionTemplate = TemplateParser.parse(createReader("/templates/notify/newVersionNotification.html"));
263                 newVersionNotification = new TemplateNotification("new-version-notification", newVersionTemplate);
264         }
265
266         //
267         // ACCESSORS
268         //
269
270         /**
271          * Returns the Sone core used by the Sone plugin.
272          *
273          * @return The Sone core
274          */
275         public Core getCore() {
276                 return sonePlugin.core();
277         }
278
279         /**
280          * Returns the template context factory of the web interface.
281          *
282          * @return The template context factory
283          */
284         public TemplateContextFactory getTemplateContextFactory() {
285                 return templateContextFactory;
286         }
287
288         /**
289          * Returns the current session, creating a new session if there is no
290          * current session.
291          *
292          * @param toadletContenxt
293          *            The toadlet context
294          * @return The current session, or {@code null} if there is no current
295          *         session
296          */
297         public Session getCurrentSession(ToadletContext toadletContenxt) {
298                 return getCurrentSession(toadletContenxt, true);
299         }
300
301         /**
302          * Returns the current session, creating a new session if there is no
303          * current session and {@code create} is {@code true}.
304          *
305          * @param toadletContenxt
306          *            The toadlet context
307          * @param create
308          *            {@code true} to create a new session if there is no current
309          *            session, {@code false} otherwise
310          * @return The current session, or {@code null} if there is no current
311          *         session
312          */
313         public Session getCurrentSession(ToadletContext toadletContenxt, boolean create) {
314                 Session session = getSessionManager().useSession(toadletContenxt);
315                 if (create && (session == null)) {
316                         session = getSessionManager().createSession(UUID.randomUUID().toString(), toadletContenxt);
317                 }
318                 return session;
319         }
320
321         /**
322          * Returns the currently logged in Sone.
323          *
324          * @param toadletContext
325          *            The toadlet context
326          * @return The currently logged in Sone, or {@code null} if no Sone is
327          *         currently logged in
328          */
329         public Sone getCurrentSone(ToadletContext toadletContext) {
330                 return getCurrentSone(toadletContext, true);
331         }
332
333         /**
334          * Returns the currently logged in Sone.
335          *
336          * @param toadletContext
337          *            The toadlet context
338          * @param create
339          *            {@code true} to create a new session if no session exists,
340          *            {@code false} to not create a new session
341          * @return The currently logged in Sone, or {@code null} if no Sone is
342          *         currently logged in
343          */
344         public Sone getCurrentSone(ToadletContext toadletContext, boolean create) {
345                 Set<Sone> localSones = getCore().getLocalSones();
346                 if (localSones.size() == 1) {
347                         return localSones.iterator().next();
348                 }
349                 return getCurrentSone(getCurrentSession(toadletContext, create));
350         }
351
352         /**
353          * Returns the currently logged in Sone.
354          *
355          * @param session
356          *            The session
357          * @return The currently logged in Sone, or {@code null} if no Sone is
358          *         currently logged in
359          */
360         public Sone getCurrentSone(Session session) {
361                 if (session == null) {
362                         return null;
363                 }
364                 String soneId = (String) session.getAttribute("Sone.CurrentSone");
365                 if (soneId == null) {
366                         return null;
367                 }
368                 return getCore().getLocalSone(soneId, false);
369         }
370
371         /**
372          * Sets the currently logged in Sone.
373          *
374          * @param toadletContext
375          *            The toadlet context
376          * @param sone
377          *            The Sone to set as currently logged in
378          */
379         public void setCurrentSone(ToadletContext toadletContext, Sone sone) {
380                 Session session = getCurrentSession(toadletContext);
381                 if (sone == null) {
382                         session.removeAttribute("Sone.CurrentSone");
383                 } else {
384                         session.setAttribute("Sone.CurrentSone", sone.getId());
385                 }
386         }
387
388         /**
389          * Returns the notification manager.
390          *
391          * @return The notification manager
392          */
393         public NotificationManager getNotifications() {
394                 return notificationManager;
395         }
396
397         /**
398          * Returns the l10n helper of the node.
399          *
400          * @return The node’s l10n helper
401          */
402         public BaseL10n getL10n() {
403                 return sonePlugin.l10n().getBase();
404         }
405
406         /**
407          * Returns the session manager of the node.
408          *
409          * @return The node’s session manager
410          */
411         public SessionManager getSessionManager() {
412                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
413         }
414
415         /**
416          * Returns the node’s form password.
417          *
418          * @return The form password
419          */
420         public String getFormPassword() {
421                 return formPassword;
422         }
423
424         /**
425          * Returns the posts that have been announced as new in the
426          * {@link #newPostNotification}.
427          *
428          * @return The new posts
429          */
430         public Set<Post> getNewPosts() {
431                 return new HashSet<Post>(newPostNotification.getElements());
432         }
433
434         /**
435          * Returns the replies that have been announced as new in the
436          * {@link #newReplyNotification}.
437          *
438          * @return The new replies
439          */
440         public Set<Reply> getNewReplies() {
441                 return new HashSet<Reply>(newReplyNotification.getElements());
442         }
443
444         /**
445          * Sets whether the current start of the plugin is the first start. It is
446          * considered a first start if the configuration file does not exist.
447          *
448          * @param firstStart
449          *            {@code true} if no configuration file existed when Sone was
450          *            loaded, {@code false} otherwise
451          */
452         public void setFirstStart(boolean firstStart) {
453                 if (firstStart) {
454                         Template firstStartNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/firstStartNotification.html"));
455                         Notification firstStartNotification = new TemplateNotification("first-start-notification", firstStartNotificationTemplate);
456                         notificationManager.addNotification(firstStartNotification);
457                 }
458         }
459
460         /**
461          * Sets whether Sone was started with a fresh configuration file.
462          *
463          * @param newConfig
464          *            {@code true} if Sone was started with a fresh configuration,
465          *            {@code false} if the existing configuration could be read
466          */
467         public void setNewConfig(boolean newConfig) {
468                 if (newConfig && !hasFirstStartNotification()) {
469                         Template configNotReadNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/configNotReadNotification.html"));
470                         Notification configNotReadNotification = new TemplateNotification("config-not-read-notification", configNotReadNotificationTemplate);
471                         notificationManager.addNotification(configNotReadNotification);
472                 }
473         }
474
475         //
476         // PRIVATE ACCESSORS
477         //
478
479         /**
480          * Returns whether the first start notification is currently displayed.
481          *
482          * @return {@code true} if the first-start notification is currently
483          *         displayed, {@code false} otherwise
484          */
485         private boolean hasFirstStartNotification() {
486                 return notificationManager.getNotification("first-start-notification") != null;
487         }
488
489         //
490         // ACTIONS
491         //
492
493         /**
494          * Starts the web interface and registers all toadlets.
495          */
496         public void start() {
497                 registerToadlets();
498
499                 /* notification templates. */
500                 Template startupNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/startupNotification.html"));
501
502                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
503                 notificationManager.addNotification(startupNotification);
504
505                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (120 * 1000), new Runnable() {
506
507                         @Override
508                         public void run() {
509                                 startupNotification.dismiss();
510                         }
511                 }, "Sone Startup Notification Remover");
512
513                 Template wotMissingNotificationTemplate = TemplateParser.parse(createReader("/templates/notify/wotMissingNotification.html"));
514                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
515                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), new Runnable() {
516
517                         @Override
518                         @SuppressWarnings("synthetic-access")
519                         public void run() {
520                                 if (getCore().getIdentityManager().isConnected()) {
521                                         wotMissingNotification.dismiss();
522                                 } else {
523                                         notificationManager.addNotification(wotMissingNotification);
524                                 }
525                                 Ticker.getInstance().registerEvent(System.currentTimeMillis() + (15 * 1000), this, "Sone WoT Connector Checker");
526                         }
527
528                 }, "Sone WoT Connector Checker");
529         }
530
531         /**
532          * Stops the web interface and unregisters all toadlets.
533          */
534         public void stop() {
535                 unregisterToadlets();
536                 Ticker.getInstance().stop();
537         }
538
539         //
540         // PRIVATE METHODS
541         //
542
543         /**
544          * Register all toadlets.
545          */
546         private void registerToadlets() {
547                 Template emptyTemplate = TemplateParser.parse(new StringReader(""));
548                 Template loginTemplate = TemplateParser.parse(createReader("/templates/login.html"));
549                 Template indexTemplate = TemplateParser.parse(createReader("/templates/index.html"));
550                 Template knownSonesTemplate = TemplateParser.parse(createReader("/templates/knownSones.html"));
551                 Template createSoneTemplate = TemplateParser.parse(createReader("/templates/createSone.html"));
552                 Template createPostTemplate = TemplateParser.parse(createReader("/templates/createPost.html"));
553                 Template createReplyTemplate = TemplateParser.parse(createReader("/templates/createReply.html"));
554                 Template bookmarksTemplate = TemplateParser.parse(createReader("/templates/bookmarks.html"));
555                 Template searchTemplate = TemplateParser.parse(createReader("/templates/search.html"));
556                 Template editProfileTemplate = TemplateParser.parse(createReader("/templates/editProfile.html"));
557                 Template editProfileFieldTemplate = TemplateParser.parse(createReader("/templates/editProfileField.html"));
558                 Template deleteProfileFieldTemplate = TemplateParser.parse(createReader("/templates/deleteProfileField.html"));
559                 Template viewSoneTemplate = TemplateParser.parse(createReader("/templates/viewSone.html"));
560                 Template viewPostTemplate = TemplateParser.parse(createReader("/templates/viewPost.html"));
561                 Template deletePostTemplate = TemplateParser.parse(createReader("/templates/deletePost.html"));
562                 Template deleteReplyTemplate = TemplateParser.parse(createReader("/templates/deleteReply.html"));
563                 Template deleteSoneTemplate = TemplateParser.parse(createReader("/templates/deleteSone.html"));
564                 Template noPermissionTemplate = TemplateParser.parse(createReader("/templates/noPermission.html"));
565                 Template optionsTemplate = TemplateParser.parse(createReader("/templates/options.html"));
566                 Template aboutTemplate = TemplateParser.parse(createReader("/templates/about.html"));
567                 Template invalidTemplate = TemplateParser.parse(createReader("/templates/invalid.html"));
568                 Template postTemplate = TemplateParser.parse(createReader("/templates/include/viewPost.html"));
569                 Template replyTemplate = TemplateParser.parse(createReader("/templates/include/viewReply.html"));
570                 Template openSearchTemplate = TemplateParser.parse(createReader("/templates/xml/OpenSearch.xml"));
571
572                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
573                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RedirectPage("", "index.html")));
574                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this), "Index"));
575                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
576                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
577                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
578                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldPage(editProfileFieldTemplate, this)));
579                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldPage(deleteProfileFieldTemplate, this)));
580                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
581                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
582                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
583                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
584                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(emptyTemplate, this)));
585                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(emptyTemplate, this)));
586                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
587                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
588                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(emptyTemplate, this)));
589                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(emptyTemplate, this)));
590                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(emptyTemplate, this)));
591                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(emptyTemplate, this)));
592                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustPage(emptyTemplate, this)));
593                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustPage(emptyTemplate, this)));
594                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustPage(emptyTemplate, this)));
595                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownPage(emptyTemplate, this)));
596                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkPage(emptyTemplate, this)));
597                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkPage(emptyTemplate, this)));
598                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarksPage(bookmarksTemplate, this), "Bookmarks"));
599                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SearchPage(searchTemplate, this)));
600                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
601                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
602                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(emptyTemplate, this), "Logout"));
603                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
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         // CORELISTENER METHODS
705         //
706
707         /**
708          * {@inheritDoc}
709          */
710         @Override
711         public void rescuingSone(Sone sone) {
712                 rescuingSonesNotification.add(sone);
713                 notificationManager.addNotification(rescuingSonesNotification);
714         }
715
716         /**
717          * {@inheritDoc}
718          */
719         @Override
720         public void rescuedSone(Sone sone) {
721                 rescuingSonesNotification.remove(sone);
722                 sonesRescuedNotification.add(sone);
723                 notificationManager.addNotification(sonesRescuedNotification);
724         }
725
726         /**
727          * {@inheritDoc}
728          */
729         @Override
730         public void newSoneFound(Sone sone) {
731                 newSoneNotification.add(sone);
732                 if (!hasFirstStartNotification()) {
733                         notificationManager.addNotification(newSoneNotification);
734                 }
735         }
736
737         /**
738          * {@inheritDoc}
739          */
740         @Override
741         public void newPostFound(Post post) {
742                 boolean isLocal = getCore().isLocalSone(post.getSone());
743                 if (isLocal) {
744                         localPostNotification.add(post);
745                 } else {
746                         newPostNotification.add(post);
747                 }
748                 if (!hasFirstStartNotification()) {
749                         notificationManager.addNotification(isLocal ? localPostNotification : newPostNotification);
750                         if (!getMentionedSones(post.getText()).isEmpty() && !isLocal) {
751                                 mentionNotification.add(post);
752                                 notificationManager.addNotification(mentionNotification);
753                         }
754                 } else {
755                         getCore().markPostKnown(post);
756                 }
757         }
758
759         /**
760          * {@inheritDoc}
761          */
762         @Override
763         public void newReplyFound(Reply reply) {
764                 if (reply.getPost().getSone() == null) {
765                         return;
766                 }
767                 boolean isLocal = getCore().isLocalSone(reply.getSone());
768                 if (isLocal) {
769                         localReplyNotification.add(reply);
770                 } else {
771                         newReplyNotification.add(reply);
772                 }
773                 if (!hasFirstStartNotification()) {
774                         notificationManager.addNotification(isLocal ? localReplyNotification : newReplyNotification);
775                         if (!getMentionedSones(reply.getText()).isEmpty() && !isLocal) {
776                                 mentionNotification.add(reply.getPost());
777                                 notificationManager.addNotification(mentionNotification);
778                         }
779                 } else {
780                         getCore().markReplyKnown(reply);
781                 }
782         }
783
784         /**
785          * {@inheritDoc}
786          */
787         @Override
788         public void markSoneKnown(Sone sone) {
789                 newSoneNotification.remove(sone);
790         }
791
792         /**
793          * {@inheritDoc}
794          */
795         @Override
796         public void markPostKnown(Post post) {
797                 newPostNotification.remove(post);
798                 localPostNotification.remove(post);
799                 mentionNotification.remove(post);
800         }
801
802         /**
803          * {@inheritDoc}
804          */
805         @Override
806         public void markReplyKnown(Reply reply) {
807                 newReplyNotification.remove(reply);
808                 localReplyNotification.remove(reply);
809                 mentionNotification.remove(reply.getPost());
810         }
811
812         /**
813          * {@inheritDoc}
814          */
815         @Override
816         public void soneRemoved(Sone sone) {
817                 newSoneNotification.remove(sone);
818         }
819
820         /**
821          * {@inheritDoc}
822          */
823         @Override
824         public void postRemoved(Post post) {
825                 newPostNotification.remove(post);
826                 localPostNotification.remove(post);
827         }
828
829         /**
830          * {@inheritDoc}
831          */
832         @Override
833         public void replyRemoved(Reply reply) {
834                 newReplyNotification.remove(reply);
835                 localReplyNotification.remove(reply);
836         }
837
838         /**
839          * {@inheritDoc}
840          */
841         @Override
842         public void soneLocked(final Sone sone) {
843                 Object tickerObject = Ticker.getInstance().registerEvent(System.currentTimeMillis() + (5 * 60) * 1000, new Runnable() {
844
845                         @Override
846                         @SuppressWarnings("synthetic-access")
847                         public void run() {
848                                 lockedSonesNotification.add(sone);
849                                 lockedSonesTickerObjects.remove(sone);
850                                 notificationManager.addNotification(lockedSonesNotification);
851                         }
852                 }, "Sone Locked Notification");
853                 lockedSonesTickerObjects.put(sone, tickerObject);
854         }
855
856         /**
857          * {@inheritDoc}
858          */
859         @Override
860         public void soneUnlocked(Sone sone) {
861                 lockedSonesNotification.remove(sone);
862                 Ticker.getInstance().deregisterEvent(lockedSonesTickerObjects.remove(sone));
863         }
864
865         /**
866          * {@inheritDoc}
867          */
868         @Override
869         public void updateFound(Version version, long releaseTime, long latestEdition) {
870                 newVersionNotification.getTemplateContext().set("latestVersion", version);
871                 newVersionNotification.getTemplateContext().set("latestEdition", latestEdition);
872                 newVersionNotification.getTemplateContext().set("releaseTime", releaseTime);
873                 notificationManager.addNotification(newVersionNotification);
874         }
875
876         /**
877          * Template provider implementation that uses
878          * {@link WebInterface#createReader(String)} to load templates for
879          * inclusion.
880          *
881          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
882          */
883         private class ClassPathTemplateProvider implements Provider {
884
885                 /** Cache for templates. */
886                 private final Cache<String, Template> templateCache = new MemoryCache<String, Template>(new ValueRetriever<String, Template>() {
887
888                         @Override
889                         @SuppressWarnings("synthetic-access")
890                         public CacheItem<Template> retrieve(String key) throws CacheException {
891                                 Template template = findTemplate(key);
892                                 if (template != null) {
893                                         return new DefaultCacheItem<Template>(template);
894                                 }
895                                 return null;
896                         }
897                 });
898
899                 /**
900                  * {@inheritDoc}
901                  */
902                 @Override
903                 @SuppressWarnings("synthetic-access")
904                 public Template getTemplate(TemplateContext templateContext, String templateName) {
905                         try {
906                                 return templateCache.get(templateName);
907                         } catch (CacheException ce1) {
908                                 logger.log(Level.WARNING, "Could not get template for " + templateName + "!", ce1);
909                                 return null;
910                         }
911                 }
912
913                 /**
914                  * Locates a template in the class path.
915                  *
916                  * @param templateName
917                  *            The name of the template to load
918                  * @return The loaded template, or {@code null} if no template could be
919                  *         found
920                  */
921                 @SuppressWarnings("synthetic-access")
922                 private Template findTemplate(String templateName) {
923                         Reader templateReader = createReader("/templates/" + templateName);
924                         if (templateReader == null) {
925                                 return null;
926                         }
927                         Template template = null;
928                         try {
929                                 template = TemplateParser.parse(templateReader);
930                         } catch (TemplateException te1) {
931                                 logger.log(Level.WARNING, "Could not parse template “" + templateName + "” for inclusion!", te1);
932                         }
933                         return template;
934                 }
935
936         }
937
938 }