Clean up SoneTemplatePage’s constructors
[Sone.git] / src / main / java / net / pterodactylus / sone / web / WebInterface.java
1 /*
2  * Sone - WebInterface.java - Copyright © 2010–2016 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 static com.google.common.collect.FluentIterable.from;
21 import static java.util.logging.Logger.getLogger;
22 import static net.pterodactylus.util.template.TemplateParser.parse;
23
24 import java.io.StringReader;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.TimeZone;
34 import java.util.UUID;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.ScheduledExecutorService;
37 import java.util.concurrent.ScheduledFuture;
38 import java.util.concurrent.TimeUnit;
39 import java.util.logging.Logger;
40 import javax.annotation.Nonnull;
41 import javax.annotation.Nullable;
42
43 import net.pterodactylus.sone.core.Core;
44 import net.pterodactylus.sone.core.ElementLoader;
45 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
46 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
47 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
48 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
49 import net.pterodactylus.sone.core.event.MarkPostKnownEvent;
50 import net.pterodactylus.sone.core.event.MarkPostReplyKnownEvent;
51 import net.pterodactylus.sone.core.event.MarkSoneKnownEvent;
52 import net.pterodactylus.sone.core.event.NewPostFoundEvent;
53 import net.pterodactylus.sone.core.event.NewPostReplyFoundEvent;
54 import net.pterodactylus.sone.core.event.NewSoneFoundEvent;
55 import net.pterodactylus.sone.core.event.PostRemovedEvent;
56 import net.pterodactylus.sone.core.event.PostReplyRemovedEvent;
57 import net.pterodactylus.sone.core.event.SoneInsertAbortedEvent;
58 import net.pterodactylus.sone.core.event.SoneInsertedEvent;
59 import net.pterodactylus.sone.core.event.SoneInsertingEvent;
60 import net.pterodactylus.sone.core.event.SoneLockedEvent;
61 import net.pterodactylus.sone.core.event.SoneRemovedEvent;
62 import net.pterodactylus.sone.core.event.SoneUnlockedEvent;
63 import net.pterodactylus.sone.core.event.UpdateFoundEvent;
64 import net.pterodactylus.sone.data.Album;
65 import net.pterodactylus.sone.data.Image;
66 import net.pterodactylus.sone.data.Post;
67 import net.pterodactylus.sone.data.PostReply;
68 import net.pterodactylus.sone.data.Profile;
69 import net.pterodactylus.sone.data.Reply;
70 import net.pterodactylus.sone.data.Sone;
71 import net.pterodactylus.sone.freenet.L10nFilter;
72 import net.pterodactylus.sone.freenet.wot.Identity;
73 import net.pterodactylus.sone.freenet.wot.Trust;
74 import net.pterodactylus.sone.main.Loaders;
75 import net.pterodactylus.sone.main.ReparseFilter;
76 import net.pterodactylus.sone.main.SonePlugin;
77 import net.pterodactylus.sone.main.SonePlugin.PluginHomepage;
78 import net.pterodactylus.sone.main.SonePlugin.PluginVersion;
79 import net.pterodactylus.sone.main.SonePlugin.PluginYear;
80 import net.pterodactylus.sone.notify.ListNotification;
81 import net.pterodactylus.sone.notify.ListNotificationFilter;
82 import net.pterodactylus.sone.notify.PostVisibilityFilter;
83 import net.pterodactylus.sone.notify.ReplyVisibilityFilter;
84 import net.pterodactylus.sone.template.AlbumAccessor;
85 import net.pterodactylus.sone.template.CollectionAccessor;
86 import net.pterodactylus.sone.template.CssClassNameFilter;
87 import net.pterodactylus.sone.template.HttpRequestAccessor;
88 import net.pterodactylus.sone.template.IdentityAccessor;
89 import net.pterodactylus.sone.template.ImageAccessor;
90 import net.pterodactylus.sone.template.ImageLinkFilter;
91 import net.pterodactylus.sone.template.JavascriptFilter;
92 import net.pterodactylus.sone.template.LinkedElementRenderFilter;
93 import net.pterodactylus.sone.template.LinkedElementsFilter;
94 import net.pterodactylus.sone.template.ParserFilter;
95 import net.pterodactylus.sone.template.PostAccessor;
96 import net.pterodactylus.sone.template.ProfileAccessor;
97 import net.pterodactylus.sone.template.RenderFilter;
98 import net.pterodactylus.sone.template.ReplyAccessor;
99 import net.pterodactylus.sone.template.ReplyGroupFilter;
100 import net.pterodactylus.sone.template.RequestChangeFilter;
101 import net.pterodactylus.sone.template.ShortenFilter;
102 import net.pterodactylus.sone.template.SoneAccessor;
103 import net.pterodactylus.sone.template.SubstringFilter;
104 import net.pterodactylus.sone.template.TrustAccessor;
105 import net.pterodactylus.sone.template.UniqueElementFilter;
106 import net.pterodactylus.sone.template.UnknownDateFilter;
107 import net.pterodactylus.sone.text.Part;
108 import net.pterodactylus.sone.text.SonePart;
109 import net.pterodactylus.sone.text.SoneTextParser;
110 import net.pterodactylus.sone.text.TimeTextConverter;
111 import net.pterodactylus.sone.web.ajax.BookmarkAjaxPage;
112 import net.pterodactylus.sone.web.ajax.CreatePostAjaxPage;
113 import net.pterodactylus.sone.web.ajax.CreateReplyAjaxPage;
114 import net.pterodactylus.sone.web.ajax.DeletePostAjaxPage;
115 import net.pterodactylus.sone.web.ajax.DeleteProfileFieldAjaxPage;
116 import net.pterodactylus.sone.web.ajax.DeleteReplyAjaxPage;
117 import net.pterodactylus.sone.web.ajax.DismissNotificationAjaxPage;
118 import net.pterodactylus.sone.web.ajax.DistrustAjaxPage;
119 import net.pterodactylus.sone.web.ajax.EditAlbumAjaxPage;
120 import net.pterodactylus.sone.web.ajax.EditImageAjaxPage;
121 import net.pterodactylus.sone.web.ajax.EditProfileFieldAjaxPage;
122 import net.pterodactylus.sone.web.ajax.FollowSoneAjaxPage;
123 import net.pterodactylus.sone.web.ajax.GetLikesAjaxPage;
124 import net.pterodactylus.sone.web.ajax.GetLinkedElementAjaxPage;
125 import net.pterodactylus.sone.web.ajax.GetNotificationsAjaxPage;
126 import net.pterodactylus.sone.web.ajax.GetPostAjaxPage;
127 import net.pterodactylus.sone.web.ajax.GetReplyAjaxPage;
128 import net.pterodactylus.sone.web.ajax.GetStatusAjaxPage;
129 import net.pterodactylus.sone.web.ajax.GetTimesAjaxPage;
130 import net.pterodactylus.sone.web.ajax.GetTranslationAjaxPage;
131 import net.pterodactylus.sone.web.ajax.LikeAjaxPage;
132 import net.pterodactylus.sone.web.ajax.LockSoneAjaxPage;
133 import net.pterodactylus.sone.web.ajax.MarkAsKnownAjaxPage;
134 import net.pterodactylus.sone.web.ajax.MoveProfileFieldAjaxPage;
135 import net.pterodactylus.sone.web.ajax.TrustAjaxPage;
136 import net.pterodactylus.sone.web.ajax.UnbookmarkAjaxPage;
137 import net.pterodactylus.sone.web.ajax.UnfollowSoneAjaxPage;
138 import net.pterodactylus.sone.web.ajax.UnlikeAjaxPage;
139 import net.pterodactylus.sone.web.ajax.UnlockSoneAjaxPage;
140 import net.pterodactylus.sone.web.ajax.UntrustAjaxPage;
141 import net.pterodactylus.sone.web.page.FreenetRequest;
142 import net.pterodactylus.sone.web.page.PageToadlet;
143 import net.pterodactylus.sone.web.page.PageToadletFactory;
144 import net.pterodactylus.sone.web.pages.AboutPage;
145 import net.pterodactylus.sone.web.pages.BookmarkPage;
146 import net.pterodactylus.sone.web.pages.BookmarksPage;
147 import net.pterodactylus.sone.web.pages.CreateAlbumPage;
148 import net.pterodactylus.sone.web.pages.CreatePostPage;
149 import net.pterodactylus.sone.web.pages.CreateReplyPage;
150 import net.pterodactylus.sone.web.pages.CreateSonePage;
151 import net.pterodactylus.sone.web.pages.DeleteAlbumPage;
152 import net.pterodactylus.sone.web.pages.DeleteImagePage;
153 import net.pterodactylus.sone.web.pages.DeletePostPage;
154 import net.pterodactylus.sone.web.pages.DeleteProfileFieldPage;
155 import net.pterodactylus.sone.web.pages.DeleteReplyPage;
156 import net.pterodactylus.sone.web.pages.DeleteSonePage;
157 import net.pterodactylus.sone.web.pages.DismissNotificationPage;
158 import net.pterodactylus.sone.web.pages.DistrustPage;
159 import net.pterodactylus.sone.web.pages.EditAlbumPage;
160 import net.pterodactylus.sone.web.pages.EditImagePage;
161 import net.pterodactylus.sone.web.pages.EditProfileFieldPage;
162 import net.pterodactylus.sone.web.pages.EditProfilePage;
163 import net.pterodactylus.sone.web.pages.FollowSonePage;
164 import net.pterodactylus.sone.web.pages.GetImagePage;
165 import net.pterodactylus.sone.web.pages.ImageBrowserPage;
166 import net.pterodactylus.sone.web.pages.IndexPage;
167 import net.pterodactylus.sone.web.pages.KnownSonesPage;
168 import net.pterodactylus.sone.web.pages.LikePage;
169 import net.pterodactylus.sone.web.pages.LockSonePage;
170 import net.pterodactylus.sone.web.pages.LoginPage;
171 import net.pterodactylus.sone.web.pages.LogoutPage;
172 import net.pterodactylus.sone.web.pages.MarkAsKnownPage;
173 import net.pterodactylus.sone.web.pages.NewPage;
174 import net.pterodactylus.sone.web.pages.OptionsPage;
175 import net.pterodactylus.sone.web.pages.RescuePage;
176 import net.pterodactylus.sone.web.pages.SearchPage;
177 import net.pterodactylus.sone.web.pages.SoneTemplatePage;
178 import net.pterodactylus.sone.web.pages.TrustPage;
179 import net.pterodactylus.sone.web.pages.UnbookmarkPage;
180 import net.pterodactylus.sone.web.pages.UnfollowSonePage;
181 import net.pterodactylus.sone.web.pages.UnlikePage;
182 import net.pterodactylus.sone.web.pages.UnlockSonePage;
183 import net.pterodactylus.sone.web.pages.UntrustPage;
184 import net.pterodactylus.sone.web.pages.UploadImagePage;
185 import net.pterodactylus.sone.web.pages.ViewPostPage;
186 import net.pterodactylus.sone.web.pages.ViewSonePage;
187 import net.pterodactylus.util.notify.Notification;
188 import net.pterodactylus.util.notify.NotificationManager;
189 import net.pterodactylus.util.notify.TemplateNotification;
190 import net.pterodactylus.util.template.CollectionSortFilter;
191 import net.pterodactylus.util.template.ContainsFilter;
192 import net.pterodactylus.util.template.DateFilter;
193 import net.pterodactylus.util.template.FormatFilter;
194 import net.pterodactylus.util.template.HtmlFilter;
195 import net.pterodactylus.util.template.MatchFilter;
196 import net.pterodactylus.util.template.ModFilter;
197 import net.pterodactylus.util.template.PaginationFilter;
198 import net.pterodactylus.util.template.ReflectionAccessor;
199 import net.pterodactylus.util.template.ReplaceFilter;
200 import net.pterodactylus.util.template.StoreFilter;
201 import net.pterodactylus.util.template.Template;
202 import net.pterodactylus.util.template.TemplateContextFactory;
203 import net.pterodactylus.util.template.TemplateProvider;
204 import net.pterodactylus.util.template.XmlFilter;
205 import net.pterodactylus.util.web.RedirectPage;
206 import net.pterodactylus.util.web.TemplatePage;
207
208 import freenet.clients.http.SessionManager;
209 import freenet.clients.http.SessionManager.Session;
210 import freenet.clients.http.ToadletContainer;
211 import freenet.clients.http.ToadletContext;
212 import freenet.l10n.BaseL10n;
213 import freenet.support.api.HTTPRequest;
214
215 import com.google.common.base.Optional;
216 import com.google.common.collect.Collections2;
217 import com.google.common.collect.ImmutableSet;
218 import com.google.common.eventbus.Subscribe;
219 import com.google.inject.Inject;
220
221 /**
222  * Bundles functionality that a web interface of a Freenet plugin needs, e.g.
223  * references to l10n helpers.
224  *
225  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
226  */
227 public class WebInterface implements SessionProvider {
228
229         /** The logger. */
230         private static final Logger logger = getLogger(WebInterface.class.getName());
231
232         /** The loaders for templates, pages, and classpath providers. */
233         private final Loaders loaders;
234
235         /** The notification manager. */
236         private final NotificationManager notificationManager = new NotificationManager();
237
238         /** The Sone plugin. */
239         private final SonePlugin sonePlugin;
240
241         /** The registered toadlets. */
242         private final List<PageToadlet> pageToadlets = new ArrayList<PageToadlet>();
243
244         /** The form password. */
245         private final String formPassword;
246
247         /** The template context factory. */
248         private final TemplateContextFactory templateContextFactory;
249
250         /** The Sone text parser. */
251         private final SoneTextParser soneTextParser;
252
253         /** The parser filter. */
254         private final ParserFilter parserFilter;
255         private final ShortenFilter shortenFilter;
256         private final RenderFilter renderFilter;
257
258         private final ListNotificationFilter listNotificationFilter;
259         private final PostVisibilityFilter postVisibilityFilter;
260         private final ReplyVisibilityFilter replyVisibilityFilter;
261
262         private final ElementLoader elementLoader;
263         private final LinkedElementRenderFilter linkedElementRenderFilter;
264         private final TimeTextConverter timeTextConverter = new TimeTextConverter();
265         private final L10nFilter l10nFilter = new L10nFilter(this);
266
267         /** The “new Sone” notification. */
268         private final ListNotification<Sone> newSoneNotification;
269
270         /** The “new post” notification. */
271         private final ListNotification<Post> newPostNotification;
272
273         /** The “new reply” notification. */
274         private final ListNotification<PostReply> newReplyNotification;
275
276         /** The invisible “local post” notification. */
277         private final ListNotification<Post> localPostNotification;
278
279         /** The invisible “local reply” notification. */
280         private final ListNotification<PostReply> localReplyNotification;
281
282         /** The “you have been mentioned” notification. */
283         private final ListNotification<Post> mentionNotification;
284
285         /** Notifications for sone inserts. */
286         private final Map<Sone, TemplateNotification> soneInsertNotifications = new HashMap<Sone, TemplateNotification>();
287
288         /** Sone locked notification ticker objects. */
289         private final Map<Sone, ScheduledFuture<?>> lockedSonesTickerObjects = Collections.synchronizedMap(new HashMap<Sone, ScheduledFuture<?>>());
290
291         /** The “Sone locked” notification. */
292         private final ListNotification<Sone> lockedSonesNotification;
293
294         /** The “new version” notification. */
295         private final TemplateNotification newVersionNotification;
296
297         /** The “inserting images” notification. */
298         private final ListNotification<Image> insertingImagesNotification;
299
300         /** The “inserted images” notification. */
301         private final ListNotification<Image> insertedImagesNotification;
302
303         /** The “image insert failed” notification. */
304         private final ListNotification<Image> imageInsertFailedNotification;
305
306         /** Scheduled executor for time-based notifications. */
307         private final ScheduledExecutorService ticker = Executors.newScheduledThreadPool(1);
308
309         /**
310          * Creates a new web interface.
311          *
312          * @param sonePlugin
313          *            The Sone plugin
314          */
315         @Inject
316         public WebInterface(SonePlugin sonePlugin, Loaders loaders, ListNotificationFilter listNotificationFilter, PostVisibilityFilter postVisibilityFilter, ReplyVisibilityFilter replyVisibilityFilter, ElementLoader elementLoader) {
317                 this.sonePlugin = sonePlugin;
318                 this.loaders = loaders;
319                 this.listNotificationFilter = listNotificationFilter;
320                 this.postVisibilityFilter = postVisibilityFilter;
321                 this.replyVisibilityFilter = replyVisibilityFilter;
322                 this.elementLoader = elementLoader;
323                 formPassword = sonePlugin.pluginRespirator().getToadletContainer().getFormPassword();
324                 soneTextParser = new SoneTextParser(getCore(), getCore());
325
326                 templateContextFactory = new TemplateContextFactory();
327                 templateContextFactory.addAccessor(Object.class, new ReflectionAccessor());
328                 templateContextFactory.addAccessor(Collection.class, new CollectionAccessor());
329                 templateContextFactory.addAccessor(Sone.class, new SoneAccessor(getCore(), new TimeTextConverter()));
330                 templateContextFactory.addAccessor(Post.class, new PostAccessor(getCore()));
331                 templateContextFactory.addAccessor(Reply.class, new ReplyAccessor(getCore()));
332                 templateContextFactory.addAccessor(Album.class, new AlbumAccessor());
333                 templateContextFactory.addAccessor(Image.class, new ImageAccessor());
334                 templateContextFactory.addAccessor(Identity.class, new IdentityAccessor(getCore()));
335                 templateContextFactory.addAccessor(Trust.class, new TrustAccessor());
336                 templateContextFactory.addAccessor(HTTPRequest.class, new HttpRequestAccessor());
337                 templateContextFactory.addAccessor(Profile.class, new ProfileAccessor(getCore()));
338                 templateContextFactory.addFilter("date", new DateFilter());
339                 templateContextFactory.addFilter("html", new HtmlFilter());
340                 templateContextFactory.addFilter("replace", new ReplaceFilter());
341                 templateContextFactory.addFilter("store", new StoreFilter());
342                 templateContextFactory.addFilter("l10n", new L10nFilter(this));
343                 templateContextFactory.addFilter("substring", new SubstringFilter());
344                 templateContextFactory.addFilter("xml", new XmlFilter());
345                 templateContextFactory.addFilter("change", new RequestChangeFilter());
346                 templateContextFactory.addFilter("match", new MatchFilter());
347                 templateContextFactory.addFilter("css", new CssClassNameFilter());
348                 templateContextFactory.addFilter("js", new JavascriptFilter());
349                 templateContextFactory.addFilter("parse", parserFilter = new ParserFilter(getCore(), soneTextParser));
350                 templateContextFactory.addFilter("shorten", shortenFilter = new ShortenFilter());
351                 templateContextFactory.addFilter("render", renderFilter = new RenderFilter(getCore(), templateContextFactory));
352                 templateContextFactory.addFilter("linked-elements", new LinkedElementsFilter(elementLoader));
353                 templateContextFactory.addFilter("render-linked-element", linkedElementRenderFilter = new LinkedElementRenderFilter(templateContextFactory));
354                 templateContextFactory.addFilter("reparse", new ReparseFilter());
355                 templateContextFactory.addFilter("unknown", new UnknownDateFilter(getL10n(), "View.Sone.Text.UnknownDate"));
356                 templateContextFactory.addFilter("format", new FormatFilter());
357                 templateContextFactory.addFilter("sort", new CollectionSortFilter());
358                 templateContextFactory.addFilter("image-link", new ImageLinkFilter(getCore(), templateContextFactory));
359                 templateContextFactory.addFilter("replyGroup", new ReplyGroupFilter());
360                 templateContextFactory.addFilter("in", new ContainsFilter());
361                 templateContextFactory.addFilter("unique", new UniqueElementFilter());
362                 templateContextFactory.addFilter("mod", new ModFilter());
363                 templateContextFactory.addFilter("paginate", new PaginationFilter());
364                 templateContextFactory.addProvider(TemplateProvider.TEMPLATE_CONTEXT_PROVIDER);
365                 templateContextFactory.addProvider(loaders.getTemplateProvider());
366                 templateContextFactory.addTemplateObject("webInterface", this);
367                 templateContextFactory.addTemplateObject("formPassword", formPassword);
368
369                 /* create notifications. */
370                 Template newSoneNotificationTemplate = loaders.loadTemplate("/templates/notify/newSoneNotification.html");
371                 newSoneNotification = new ListNotification<Sone>("new-sone-notification", "sones", newSoneNotificationTemplate, false);
372
373                 Template newPostNotificationTemplate = loaders.loadTemplate("/templates/notify/newPostNotification.html");
374                 newPostNotification = new ListNotification<Post>("new-post-notification", "posts", newPostNotificationTemplate, false);
375
376                 Template localPostNotificationTemplate = loaders.loadTemplate("/templates/notify/newPostNotification.html");
377                 localPostNotification = new ListNotification<Post>("local-post-notification", "posts", localPostNotificationTemplate, false);
378
379                 Template newReplyNotificationTemplate = loaders.loadTemplate("/templates/notify/newReplyNotification.html");
380                 newReplyNotification = new ListNotification<PostReply>("new-reply-notification", "replies", newReplyNotificationTemplate, false);
381
382                 Template localReplyNotificationTemplate = loaders.loadTemplate("/templates/notify/newReplyNotification.html");
383                 localReplyNotification = new ListNotification<PostReply>("local-reply-notification", "replies", localReplyNotificationTemplate, false);
384
385                 Template mentionNotificationTemplate = loaders.loadTemplate("/templates/notify/mentionNotification.html");
386                 mentionNotification = new ListNotification<Post>("mention-notification", "posts", mentionNotificationTemplate, false);
387
388                 Template lockedSonesTemplate = loaders.loadTemplate("/templates/notify/lockedSonesNotification.html");
389                 lockedSonesNotification = new ListNotification<Sone>("sones-locked-notification", "sones", lockedSonesTemplate);
390
391                 Template newVersionTemplate = loaders.loadTemplate("/templates/notify/newVersionNotification.html");
392                 newVersionNotification = new TemplateNotification("new-version-notification", newVersionTemplate);
393
394                 Template insertingImagesTemplate = loaders.loadTemplate("/templates/notify/inserting-images-notification.html");
395                 insertingImagesNotification = new ListNotification<Image>("inserting-images-notification", "images", insertingImagesTemplate);
396
397                 Template insertedImagesTemplate = loaders.loadTemplate("/templates/notify/inserted-images-notification.html");
398                 insertedImagesNotification = new ListNotification<Image>("inserted-images-notification", "images", insertedImagesTemplate);
399
400                 Template imageInsertFailedTemplate = loaders.loadTemplate("/templates/notify/image-insert-failed-notification.html");
401                 imageInsertFailedNotification = new ListNotification<Image>("image-insert-failed-notification", "images", imageInsertFailedTemplate);
402         }
403
404         //
405         // ACCESSORS
406         //
407
408         /**
409          * Returns the Sone core used by the Sone plugin.
410          *
411          * @return The Sone core
412          */
413         @Nonnull
414         public Core getCore() {
415                 return sonePlugin.core();
416         }
417
418         /**
419          * Returns the template context factory of the web interface.
420          *
421          * @return The template context factory
422          */
423         public TemplateContextFactory getTemplateContextFactory() {
424                 return templateContextFactory;
425         }
426
427         private Session getCurrentSessionWithoutCreation(ToadletContext toadletContenxt) {
428                 return getSessionManager().useSession(toadletContenxt);
429         }
430
431         private Session getOrCreateCurrentSession(ToadletContext toadletContenxt) {
432                 Session session = getCurrentSessionWithoutCreation(toadletContenxt);
433                 if (session == null) {
434                         session = getSessionManager().createSession(UUID.randomUUID().toString(), toadletContenxt);
435                 }
436                 return session;
437         }
438
439         public Sone getCurrentSoneCreatingSession(ToadletContext toadletContext) {
440                 Collection<Sone> localSones = getCore().getLocalSones();
441                 if (localSones.size() == 1) {
442                         return localSones.iterator().next();
443                 }
444                 return getCurrentSone(getOrCreateCurrentSession(toadletContext));
445         }
446
447         public Sone getCurrentSoneWithoutCreatingSession(ToadletContext toadletContext) {
448                 Collection<Sone> localSones = getCore().getLocalSones();
449                 if (localSones.size() == 1) {
450                         return localSones.iterator().next();
451                 }
452                 return getCurrentSone(getCurrentSessionWithoutCreation(toadletContext));
453         }
454
455         /**
456          * Returns the currently logged in Sone.
457          *
458          * @param session
459          *            The session
460          * @return The currently logged in Sone, or {@code null} if no Sone is
461          *         currently logged in
462          */
463         private Sone getCurrentSone(Session session) {
464                 if (session == null) {
465                         return null;
466                 }
467                 String soneId = (String) session.getAttribute("Sone.CurrentSone");
468                 if (soneId == null) {
469                         return null;
470                 }
471                 return getCore().getLocalSone(soneId);
472         }
473
474         @Override
475         @Nullable
476         public Sone getCurrentSone(@Nonnull ToadletContext toadletContext, boolean createSession) {
477                 return createSession ? getCurrentSoneCreatingSession(toadletContext) : getCurrentSoneWithoutCreatingSession(toadletContext);
478         }
479
480         /**
481          * Sets the currently logged in Sone.
482          *
483          * @param toadletContext
484          *            The toadlet context
485          * @param sone
486          *            The Sone to set as currently logged in
487          */
488         @Override
489         public void setCurrentSone(@Nonnull ToadletContext toadletContext, @Nullable Sone sone) {
490                 Session session = getOrCreateCurrentSession(toadletContext);
491                 if (sone == null) {
492                         session.removeAttribute("Sone.CurrentSone");
493                 } else {
494                         session.setAttribute("Sone.CurrentSone", sone.getId());
495                 }
496         }
497
498         /**
499          * Returns the notification manager.
500          *
501          * @return The notification manager
502          */
503         public NotificationManager getNotifications() {
504                 return notificationManager;
505         }
506
507         @Nonnull
508         public Optional<Notification> getNotification(@Nonnull String notificationId) {
509                 return Optional.fromNullable(notificationManager.getNotification(notificationId));
510         }
511
512         @Nonnull
513         public Collection<Notification> getNotifications(@Nullable Sone currentSone) {
514                 return listNotificationFilter.filterNotifications(notificationManager.getNotifications(), currentSone);
515         }
516
517         /**
518          * Returns the l10n helper of the node.
519          *
520          * @return The node’s l10n helper
521          */
522         public BaseL10n getL10n() {
523                 return sonePlugin.l10n().getBase();
524         }
525
526         /**
527          * Returns the session manager of the node.
528          *
529          * @return The node’s session manager
530          */
531         public SessionManager getSessionManager() {
532                 return sonePlugin.pluginRespirator().getSessionManager("Sone");
533         }
534
535         /**
536          * Returns the node’s form password.
537          *
538          * @return The form password
539          */
540         public String getFormPassword() {
541                 return formPassword;
542         }
543
544         /**
545          * Returns the posts that have been announced as new in the
546          * {@link #newPostNotification}.
547          *
548          * @return The new posts
549          */
550         public Set<Post> getNewPosts() {
551                 return ImmutableSet.<Post> builder().addAll(newPostNotification.getElements()).addAll(localPostNotification.getElements()).build();
552         }
553
554         @Nonnull
555         public Collection<Post> getNewPosts(@Nullable Sone currentSone) {
556                 Set<Post> allNewPosts = ImmutableSet.<Post> builder()
557                                 .addAll(newPostNotification.getElements())
558                                 .addAll(localPostNotification.getElements())
559                                 .build();
560                 return from(allNewPosts).filter(postVisibilityFilter.isVisible(currentSone)).toSet();
561         }
562
563         /**
564          * Returns the replies that have been announced as new in the
565          * {@link #newReplyNotification}.
566          *
567          * @return The new replies
568          */
569         public Set<PostReply> getNewReplies() {
570                 return ImmutableSet.<PostReply> builder().addAll(newReplyNotification.getElements()).addAll(localReplyNotification.getElements()).build();
571         }
572
573         @Nonnull
574         public Collection<PostReply> getNewReplies(@Nullable Sone currentSone) {
575                 Set<PostReply> allNewReplies = ImmutableSet.<PostReply>builder()
576                                 .addAll(newReplyNotification.getElements())
577                                 .addAll(localReplyNotification.getElements())
578                                 .build();
579                 return from(allNewReplies).filter(replyVisibilityFilter.isVisible(currentSone)).toSet();
580         }
581
582         /**
583          * Sets whether the current start of the plugin is the first start. It is
584          * considered a first start if the configuration file does not exist.
585          *
586          * @param firstStart
587          *            {@code true} if no configuration file existed when Sone was
588          *            loaded, {@code false} otherwise
589          */
590         public void setFirstStart(boolean firstStart) {
591                 if (firstStart) {
592                         Template firstStartNotificationTemplate = loaders.loadTemplate("/templates/notify/firstStartNotification.html");
593                         Notification firstStartNotification = new TemplateNotification("first-start-notification", firstStartNotificationTemplate);
594                         notificationManager.addNotification(firstStartNotification);
595                 }
596         }
597
598         /**
599          * Sets whether Sone was started with a fresh configuration file.
600          *
601          * @param newConfig
602          *            {@code true} if Sone was started with a fresh configuration,
603          *            {@code false} if the existing configuration could be read
604          */
605         public void setNewConfig(boolean newConfig) {
606                 if (newConfig && !hasFirstStartNotification()) {
607                         Template configNotReadNotificationTemplate = loaders.loadTemplate("/templates/notify/configNotReadNotification.html");
608                         Notification configNotReadNotification = new TemplateNotification("config-not-read-notification", configNotReadNotificationTemplate);
609                         notificationManager.addNotification(configNotReadNotification);
610                 }
611         }
612
613         //
614         // PRIVATE ACCESSORS
615         //
616
617         /**
618          * Returns whether the first start notification is currently displayed.
619          *
620          * @return {@code true} if the first-start notification is currently
621          *         displayed, {@code false} otherwise
622          */
623         private boolean hasFirstStartNotification() {
624                 return notificationManager.getNotification("first-start-notification") != null;
625         }
626
627         //
628         // ACTIONS
629         //
630
631         /**
632          * Starts the web interface and registers all toadlets.
633          */
634         public void start() {
635                 registerToadlets();
636
637                 /* notification templates. */
638                 Template startupNotificationTemplate = loaders.loadTemplate("/templates/notify/startupNotification.html");
639
640                 final TemplateNotification startupNotification = new TemplateNotification("startup-notification", startupNotificationTemplate);
641                 notificationManager.addNotification(startupNotification);
642
643                 ticker.schedule(new Runnable() {
644
645                         @Override
646                         public void run() {
647                                 startupNotification.dismiss();
648                         }
649                 }, 2, TimeUnit.MINUTES);
650
651                 Template wotMissingNotificationTemplate = loaders.loadTemplate("/templates/notify/wotMissingNotification.html");
652                 final TemplateNotification wotMissingNotification = new TemplateNotification("wot-missing-notification", wotMissingNotificationTemplate);
653                 ticker.scheduleAtFixedRate(new Runnable() {
654
655                         @Override
656                         @SuppressWarnings("synthetic-access")
657                         public void run() {
658                                 if (getCore().getIdentityManager().isConnected()) {
659                                         wotMissingNotification.dismiss();
660                                 } else {
661                                         notificationManager.addNotification(wotMissingNotification);
662                                 }
663                         }
664
665                 }, 15, 15, TimeUnit.SECONDS);
666         }
667
668         /**
669          * Stops the web interface and unregisters all toadlets.
670          */
671         public void stop() {
672                 unregisterToadlets();
673                 ticker.shutdownNow();
674         }
675
676         //
677         // PRIVATE METHODS
678         //
679
680         /**
681          * Register all toadlets.
682          */
683         private void registerToadlets() {
684                 Template emptyTemplate = parse(new StringReader(""));
685                 Template loginTemplate = loaders.loadTemplate("/templates/login.html");
686                 Template indexTemplate = loaders.loadTemplate("/templates/index.html");
687                 Template newTemplate = loaders.loadTemplate("/templates/new.html");
688                 Template knownSonesTemplate = loaders.loadTemplate("/templates/knownSones.html");
689                 Template createSoneTemplate = loaders.loadTemplate("/templates/createSone.html");
690                 Template createPostTemplate = loaders.loadTemplate("/templates/createPost.html");
691                 Template createReplyTemplate = loaders.loadTemplate("/templates/createReply.html");
692                 Template bookmarksTemplate = loaders.loadTemplate("/templates/bookmarks.html");
693                 Template searchTemplate = loaders.loadTemplate("/templates/search.html");
694                 Template editProfileTemplate = loaders.loadTemplate("/templates/editProfile.html");
695                 Template editProfileFieldTemplate = loaders.loadTemplate("/templates/editProfileField.html");
696                 Template deleteProfileFieldTemplate = loaders.loadTemplate("/templates/deleteProfileField.html");
697                 Template viewSoneTemplate = loaders.loadTemplate("/templates/viewSone.html");
698                 Template viewPostTemplate = loaders.loadTemplate("/templates/viewPost.html");
699                 Template deletePostTemplate = loaders.loadTemplate("/templates/deletePost.html");
700                 Template deleteReplyTemplate = loaders.loadTemplate("/templates/deleteReply.html");
701                 Template deleteSoneTemplate = loaders.loadTemplate("/templates/deleteSone.html");
702                 Template imageBrowserTemplate = loaders.loadTemplate("/templates/imageBrowser.html");
703                 Template createAlbumTemplate = loaders.loadTemplate("/templates/createAlbum.html");
704                 Template deleteAlbumTemplate = loaders.loadTemplate("/templates/deleteAlbum.html");
705                 Template deleteImageTemplate = loaders.loadTemplate("/templates/deleteImage.html");
706                 Template noPermissionTemplate = loaders.loadTemplate("/templates/noPermission.html");
707                 Template emptyImageTitleTemplate = loaders.loadTemplate("/templates/emptyImageTitle.html");
708                 Template emptyAlbumTitleTemplate = loaders.loadTemplate("/templates/emptyAlbumTitle.html");
709                 Template optionsTemplate = loaders.loadTemplate("/templates/options.html");
710                 Template rescueTemplate = loaders.loadTemplate("/templates/rescue.html");
711                 Template aboutTemplate = loaders.loadTemplate("/templates/about.html");
712                 Template invalidTemplate = loaders.loadTemplate("/templates/invalid.html");
713                 Template postTemplate = loaders.loadTemplate("/templates/include/viewPost.html");
714                 Template replyTemplate = loaders.loadTemplate("/templates/include/viewReply.html");
715                 Template openSearchTemplate = loaders.loadTemplate("/templates/xml/OpenSearch.xml");
716
717                 PageToadletFactory pageToadletFactory = new PageToadletFactory(sonePlugin.pluginRespirator().getHLSimpleClient(), "/Sone/");
718                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RedirectPage<FreenetRequest>("", "index.html")));
719                 pageToadlets.add(pageToadletFactory.createPageToadlet(new IndexPage(indexTemplate, this, postVisibilityFilter), "Index"));
720                 pageToadlets.add(pageToadletFactory.createPageToadlet(new NewPage(newTemplate, this), "New"));
721                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateSonePage(createSoneTemplate, this), "CreateSone"));
722                 pageToadlets.add(pageToadletFactory.createPageToadlet(new KnownSonesPage(knownSonesTemplate, this), "KnownSones"));
723                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfilePage(editProfileTemplate, this), "EditProfile"));
724                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldPage(editProfileFieldTemplate, this)));
725                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldPage(deleteProfileFieldTemplate, this)));
726                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostPage(createPostTemplate, this)));
727                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyPage(createReplyTemplate, this)));
728                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewSonePage(viewSoneTemplate, this)));
729                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ViewPostPage(viewPostTemplate, this)));
730                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikePage(emptyTemplate, this)));
731                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikePage(emptyTemplate, this)));
732                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostPage(deletePostTemplate, this)));
733                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyPage(deleteReplyTemplate, this)));
734                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSonePage(emptyTemplate, this)));
735                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSonePage(emptyTemplate, this)));
736                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSonePage(emptyTemplate, this)));
737                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSonePage(emptyTemplate, this)));
738                 pageToadlets.add(pageToadletFactory.createPageToadlet(new ImageBrowserPage(imageBrowserTemplate, this), "ImageBrowser"));
739                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateAlbumPage(createAlbumTemplate, this)));
740                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditAlbumPage(emptyTemplate, this)));
741                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteAlbumPage(deleteAlbumTemplate, this)));
742                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UploadImagePage(invalidTemplate, this)));
743                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditImagePage(emptyTemplate, this)));
744                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteImagePage(deleteImageTemplate, this)));
745                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustPage(emptyTemplate, this)));
746                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustPage(emptyTemplate, this)));
747                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustPage(emptyTemplate, this)));
748                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownPage(emptyTemplate, this)));
749                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkPage(emptyTemplate, this)));
750                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkPage(emptyTemplate, this)));
751                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarksPage(bookmarksTemplate, this), "Bookmarks"));
752                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SearchPage(searchTemplate, this)));
753                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteSonePage(deleteSoneTemplate, this), "DeleteSone"));
754                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LoginPage(loginTemplate, this), "Login"));
755                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LogoutPage(emptyTemplate, this), "Logout"));
756                 pageToadlets.add(pageToadletFactory.createPageToadlet(new OptionsPage(optionsTemplate, this), "Options"));
757                 pageToadlets.add(pageToadletFactory.createPageToadlet(new RescuePage(rescueTemplate, this), "Rescue"));
758                 pageToadlets.add(pageToadletFactory.createPageToadlet(new AboutPage(aboutTemplate, this, new PluginVersion(SonePlugin.getPluginVersion()), new PluginYear(SonePlugin.getYear()), new PluginHomepage(SonePlugin.getHomepage())), "About"));
759                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("noPermission.html", this, noPermissionTemplate, "Page.NoPermission.Title")));
760                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("emptyImageTitle.html", this, emptyImageTitleTemplate, "Page.EmptyImageTitle.Title")));
761                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("emptyAlbumTitle.html", this, emptyAlbumTitleTemplate, "Page.EmptyAlbumTitle.Title")));
762                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationPage(emptyTemplate, this)));
763                 pageToadlets.add(pageToadletFactory.createPageToadlet(new SoneTemplatePage("invalid.html", this, invalidTemplate, "Page.Invalid.Title")));
764                 pageToadlets.add(pageToadletFactory.createPageToadlet(loaders.<FreenetRequest>loadStaticPage("css/", "/static/css/", "text/css")));
765                 pageToadlets.add(pageToadletFactory.createPageToadlet(loaders.<FreenetRequest>loadStaticPage("javascript/", "/static/javascript/", "text/javascript")));
766                 pageToadlets.add(pageToadletFactory.createPageToadlet(loaders.<FreenetRequest>loadStaticPage("images/", "/static/images/", "image/png")));
767                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TemplatePage<FreenetRequest>("OpenSearch.xml", "application/opensearchdescription+xml", templateContextFactory, openSearchTemplate)));
768                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetImagePage(this)));
769                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTranslationAjaxPage(this)));
770                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetStatusAjaxPage(this, elementLoader, timeTextConverter, l10nFilter, TimeZone.getDefault())));
771                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetNotificationsAjaxPage(this)));
772                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DismissNotificationAjaxPage(this)));
773                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreatePostAjaxPage(this)));
774                 pageToadlets.add(pageToadletFactory.createPageToadlet(new CreateReplyAjaxPage(this)));
775                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetReplyAjaxPage(this, replyTemplate)));
776                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetPostAjaxPage(this, postTemplate)));
777                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLinkedElementAjaxPage(this, elementLoader, linkedElementRenderFilter)));
778                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetTimesAjaxPage(this, timeTextConverter, l10nFilter, TimeZone.getDefault())));
779                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MarkAsKnownAjaxPage(this)));
780                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeletePostAjaxPage(this)));
781                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteReplyAjaxPage(this)));
782                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LockSoneAjaxPage(this)));
783                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlockSoneAjaxPage(this)));
784                 pageToadlets.add(pageToadletFactory.createPageToadlet(new FollowSoneAjaxPage(this)));
785                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnfollowSoneAjaxPage(this)));
786                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditAlbumAjaxPage(this)));
787                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditImageAjaxPage(this, parserFilter, shortenFilter, renderFilter)));
788                 pageToadlets.add(pageToadletFactory.createPageToadlet(new TrustAjaxPage(this)));
789                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DistrustAjaxPage(this)));
790                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UntrustAjaxPage(this)));
791                 pageToadlets.add(pageToadletFactory.createPageToadlet(new LikeAjaxPage(this)));
792                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnlikeAjaxPage(this)));
793                 pageToadlets.add(pageToadletFactory.createPageToadlet(new GetLikesAjaxPage(this)));
794                 pageToadlets.add(pageToadletFactory.createPageToadlet(new BookmarkAjaxPage(this)));
795                 pageToadlets.add(pageToadletFactory.createPageToadlet(new UnbookmarkAjaxPage(this)));
796                 pageToadlets.add(pageToadletFactory.createPageToadlet(new EditProfileFieldAjaxPage(this)));
797                 pageToadlets.add(pageToadletFactory.createPageToadlet(new DeleteProfileFieldAjaxPage(this)));
798                 pageToadlets.add(pageToadletFactory.createPageToadlet(new MoveProfileFieldAjaxPage(this)));
799
800                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
801                 toadletContainer.getPageMaker().addNavigationCategory("/Sone/index.html", "Navigation.Menu.Sone.Name", "Navigation.Menu.Sone.Tooltip", sonePlugin);
802                 for (PageToadlet toadlet : pageToadlets) {
803                         String menuName = toadlet.getMenuName();
804                         if (menuName != null) {
805                                 toadletContainer.register(toadlet, "Navigation.Menu.Sone.Name", toadlet.path(), true, "Navigation.Menu.Sone.Item." + menuName + ".Name", "Navigation.Menu.Sone.Item." + menuName + ".Tooltip", false, toadlet);
806                         } else {
807                                 toadletContainer.register(toadlet, null, toadlet.path(), true, false);
808                         }
809                 }
810         }
811
812         /**
813          * Unregisters all toadlets.
814          */
815         private void unregisterToadlets() {
816                 ToadletContainer toadletContainer = sonePlugin.pluginRespirator().getToadletContainer();
817                 for (PageToadlet pageToadlet : pageToadlets) {
818                         toadletContainer.unregister(pageToadlet);
819                 }
820                 toadletContainer.getPageMaker().removeNavigationCategory("Navigation.Menu.Sone.Name");
821         }
822
823         /**
824          * Returns all {@link Sone#isLocal() local Sone}s that are referenced by
825          * {@link SonePart}s in the given text (after parsing it using
826          * {@link SoneTextParser}).
827          *
828          * @param text
829          *            The text to parse
830          * @return All mentioned local Sones
831          */
832         private Collection<Sone> getMentionedSones(String text) {
833                 /* we need no context to find mentioned Sones. */
834                 Set<Sone> mentionedSones = new HashSet<Sone>();
835                 for (Part part : soneTextParser.parse(text, null)) {
836                         if (part instanceof SonePart) {
837                                 mentionedSones.add(((SonePart) part).getSone());
838                         }
839                 }
840                 return Collections2.filter(mentionedSones, Sone.LOCAL_SONE_FILTER);
841         }
842
843         /**
844          * Returns the Sone insert notification for the given Sone. If no
845          * notification for the given Sone exists, a new notification is created and
846          * cached.
847          *
848          * @param sone
849          *            The Sone to get the insert notification for
850          * @return The Sone insert notification
851          */
852         private TemplateNotification getSoneInsertNotification(Sone sone) {
853                 synchronized (soneInsertNotifications) {
854                         TemplateNotification templateNotification = soneInsertNotifications.get(sone);
855                         if (templateNotification == null) {
856                                 templateNotification = new TemplateNotification(loaders.loadTemplate("/templates/notify/soneInsertNotification.html"));
857                                 templateNotification.set("insertSone", sone);
858                                 soneInsertNotifications.put(sone, templateNotification);
859                         }
860                         return templateNotification;
861                 }
862         }
863
864         private boolean localSoneMentionedInNewPostOrReply(Post post) {
865                 if (!post.getSone().isLocal()) {
866                         if (!getMentionedSones(post.getText()).isEmpty() && !post.isKnown()) {
867                                 return true;
868                         }
869                 }
870                 for (PostReply postReply : getCore().getReplies(post.getId())) {
871                         if (postReply.getSone().isLocal()) {
872                                 continue;
873                         }
874                         if (!getMentionedSones(postReply.getText()).isEmpty() && !postReply.isKnown()) {
875                                 return true;
876                         }
877                 }
878                 return false;
879         }
880
881         //
882         // EVENT HANDLERS
883         //
884
885         /**
886          * Notifies the web interface that a new {@link Sone} was found.
887          *
888          * @param newSoneFoundEvent
889          *            The event
890          */
891         @Subscribe
892         public void newSoneFound(NewSoneFoundEvent newSoneFoundEvent) {
893                 newSoneNotification.add(newSoneFoundEvent.sone());
894                 if (!hasFirstStartNotification()) {
895                         notificationManager.addNotification(newSoneNotification);
896                 }
897         }
898
899         /**
900          * Notifies the web interface that a new {@link Post} was found.
901          *
902          * @param newPostFoundEvent
903          *            The event
904          */
905         @Subscribe
906         public void newPostFound(NewPostFoundEvent newPostFoundEvent) {
907                 Post post = newPostFoundEvent.post();
908                 boolean isLocal = post.getSone().isLocal();
909                 if (isLocal) {
910                         localPostNotification.add(post);
911                 } else {
912                         newPostNotification.add(post);
913                 }
914                 if (!hasFirstStartNotification()) {
915                         notificationManager.addNotification(isLocal ? localPostNotification : newPostNotification);
916                         if (!getMentionedSones(post.getText()).isEmpty() && !isLocal) {
917                                 mentionNotification.add(post);
918                                 notificationManager.addNotification(mentionNotification);
919                         }
920                 } else {
921                         getCore().markPostKnown(post);
922                 }
923         }
924
925         /**
926          * Notifies the web interface that a new {@link PostReply} was found.
927          *
928          * @param newPostReplyFoundEvent
929          *            The event
930          */
931         @Subscribe
932         public void newReplyFound(NewPostReplyFoundEvent newPostReplyFoundEvent) {
933                 PostReply reply = newPostReplyFoundEvent.postReply();
934                 boolean isLocal = reply.getSone().isLocal();
935                 if (isLocal) {
936                         localReplyNotification.add(reply);
937                 } else {
938                         newReplyNotification.add(reply);
939                 }
940                 if (!hasFirstStartNotification()) {
941                         notificationManager.addNotification(isLocal ? localReplyNotification : newReplyNotification);
942                         if (reply.getPost().isPresent() && localSoneMentionedInNewPostOrReply(reply.getPost().get())) {
943                                 mentionNotification.add(reply.getPost().get());
944                                 notificationManager.addNotification(mentionNotification);
945                         }
946                 } else {
947                         getCore().markReplyKnown(reply);
948                 }
949         }
950
951         /**
952          * Notifies the web interface that a {@link Sone} was marked as known.
953          *
954          * @param markSoneKnownEvent
955          *            The event
956          */
957         @Subscribe
958         public void markSoneKnown(MarkSoneKnownEvent markSoneKnownEvent) {
959                 newSoneNotification.remove(markSoneKnownEvent.sone());
960         }
961
962         @Subscribe
963         public void markPostKnown(MarkPostKnownEvent markPostKnownEvent) {
964                 removePost(markPostKnownEvent.post());
965         }
966
967         @Subscribe
968         public void markReplyKnown(MarkPostReplyKnownEvent markPostReplyKnownEvent) {
969                 removeReply(markPostReplyKnownEvent.postReply());
970         }
971
972         @Subscribe
973         public void soneRemoved(SoneRemovedEvent soneRemovedEvent) {
974                 newSoneNotification.remove(soneRemovedEvent.sone());
975         }
976
977         @Subscribe
978         public void postRemoved(PostRemovedEvent postRemovedEvent) {
979                 removePost(postRemovedEvent.post());
980         }
981
982         private void removePost(Post post) {
983                 newPostNotification.remove(post);
984                 localPostNotification.remove(post);
985                 if (!localSoneMentionedInNewPostOrReply(post)) {
986                         mentionNotification.remove(post);
987                 }
988         }
989
990         @Subscribe
991         public void replyRemoved(PostReplyRemovedEvent postReplyRemovedEvent) {
992                 removeReply(postReplyRemovedEvent.postReply());
993         }
994
995         private void removeReply(PostReply reply) {
996                 newReplyNotification.remove(reply);
997                 localReplyNotification.remove(reply);
998                 if (reply.getPost().isPresent() && !localSoneMentionedInNewPostOrReply(reply.getPost().get())) {
999                         mentionNotification.remove(reply.getPost().get());
1000                 }
1001         }
1002
1003         /**
1004          * Notifies the web interface that a Sone was locked.
1005          *
1006          * @param soneLockedEvent
1007          *            The event
1008          */
1009         @Subscribe
1010         public void soneLocked(SoneLockedEvent soneLockedEvent) {
1011                 final Sone sone = soneLockedEvent.sone();
1012                 ScheduledFuture<?> tickerObject = ticker.schedule(new Runnable() {
1013
1014                         @Override
1015                         @SuppressWarnings("synthetic-access")
1016                         public void run() {
1017                                 lockedSonesNotification.add(sone);
1018                                 notificationManager.addNotification(lockedSonesNotification);
1019                         }
1020                 }, 5, TimeUnit.MINUTES);
1021                 lockedSonesTickerObjects.put(sone, tickerObject);
1022         }
1023
1024         /**
1025          * Notifies the web interface that a Sone was unlocked.
1026          *
1027          * @param soneUnlockedEvent
1028          *            The event
1029          */
1030         @Subscribe
1031         public void soneUnlocked(SoneUnlockedEvent soneUnlockedEvent) {
1032                 lockedSonesNotification.remove(soneUnlockedEvent.sone());
1033                 lockedSonesTickerObjects.remove(soneUnlockedEvent.sone()).cancel(false);
1034         }
1035
1036         /**
1037          * Notifies the web interface that a {@link Sone} is being inserted.
1038          *
1039          * @param soneInsertingEvent
1040          *            The event
1041          */
1042         @Subscribe
1043         public void soneInserting(SoneInsertingEvent soneInsertingEvent) {
1044                 TemplateNotification soneInsertNotification = getSoneInsertNotification(soneInsertingEvent.sone());
1045                 soneInsertNotification.set("soneStatus", "inserting");
1046                 if (soneInsertingEvent.sone().getOptions().isSoneInsertNotificationEnabled()) {
1047                         notificationManager.addNotification(soneInsertNotification);
1048                 }
1049         }
1050
1051         /**
1052          * Notifies the web interface that a {@link Sone} was inserted.
1053          *
1054          * @param soneInsertedEvent
1055          *            The event
1056          */
1057         @Subscribe
1058         public void soneInserted(SoneInsertedEvent soneInsertedEvent) {
1059                 TemplateNotification soneInsertNotification = getSoneInsertNotification(soneInsertedEvent.sone());
1060                 soneInsertNotification.set("soneStatus", "inserted");
1061                 soneInsertNotification.set("insertDuration", soneInsertedEvent.insertDuration() / 1000);
1062                 if (soneInsertedEvent.sone().getOptions().isSoneInsertNotificationEnabled()) {
1063                         notificationManager.addNotification(soneInsertNotification);
1064                 }
1065         }
1066
1067         /**
1068          * Notifies the web interface that a {@link Sone} insert was aborted.
1069          *
1070          * @param soneInsertAbortedEvent
1071          *            The event
1072          */
1073         @Subscribe
1074         public void soneInsertAborted(SoneInsertAbortedEvent soneInsertAbortedEvent) {
1075                 TemplateNotification soneInsertNotification = getSoneInsertNotification(soneInsertAbortedEvent.sone());
1076                 soneInsertNotification.set("soneStatus", "insert-aborted");
1077                 soneInsertNotification.set("insert-error", soneInsertAbortedEvent.cause());
1078                 if (soneInsertAbortedEvent.sone().getOptions().isSoneInsertNotificationEnabled()) {
1079                         notificationManager.addNotification(soneInsertNotification);
1080                 }
1081         }
1082
1083         /**
1084          * Notifies the web interface that a new Sone version was found.
1085          *
1086          * @param updateFoundEvent
1087          *            The event
1088          */
1089         @Subscribe
1090         public void updateFound(UpdateFoundEvent updateFoundEvent) {
1091                 newVersionNotification.set("latestVersion", updateFoundEvent.version());
1092                 newVersionNotification.set("latestEdition", updateFoundEvent.latestEdition());
1093                 newVersionNotification.set("releaseTime", updateFoundEvent.releaseTime());
1094                 newVersionNotification.set("disruptive", updateFoundEvent.disruptive());
1095                 notificationManager.addNotification(newVersionNotification);
1096         }
1097
1098         /**
1099          * Notifies the web interface that an image insert was started
1100          *
1101          * @param imageInsertStartedEvent
1102          *            The event
1103          */
1104         @Subscribe
1105         public void imageInsertStarted(ImageInsertStartedEvent imageInsertStartedEvent) {
1106                 insertingImagesNotification.add(imageInsertStartedEvent.image());
1107                 notificationManager.addNotification(insertingImagesNotification);
1108         }
1109
1110         /**
1111          * Notifies the web interface that an {@link Image} insert was aborted.
1112          *
1113          * @param imageInsertAbortedEvent
1114          *            The event
1115          */
1116         @Subscribe
1117         public void imageInsertAborted(ImageInsertAbortedEvent imageInsertAbortedEvent) {
1118                 insertingImagesNotification.remove(imageInsertAbortedEvent.image());
1119         }
1120
1121         /**
1122          * Notifies the web interface that an {@link Image} insert is finished.
1123          *
1124          * @param imageInsertFinishedEvent
1125          *            The event
1126          */
1127         @Subscribe
1128         public void imageInsertFinished(ImageInsertFinishedEvent imageInsertFinishedEvent) {
1129                 insertingImagesNotification.remove(imageInsertFinishedEvent.image());
1130                 insertedImagesNotification.add(imageInsertFinishedEvent.image());
1131                 notificationManager.addNotification(insertedImagesNotification);
1132         }
1133
1134         /**
1135          * Notifies the web interface that an {@link Image} insert has failed.
1136          *
1137          * @param imageInsertFailedEvent
1138          *            The event
1139          */
1140         @Subscribe
1141         public void imageInsertFailed(ImageInsertFailedEvent imageInsertFailedEvent) {
1142                 insertingImagesNotification.remove(imageInsertFailedEvent.image());
1143                 imageInsertFailedNotification.add(imageInsertFailedEvent.image());
1144                 notificationManager.addNotification(imageInsertFailedNotification);
1145         }
1146
1147 }