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