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