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