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