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