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