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