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