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