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