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