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