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