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