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