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