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